@cloudflare/realtimekit 2.0.2-staging.5 → 2.0.2-staging.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -1,18 +1,18 @@
1
- var RealtimeKitClient=function(){var Po,ar,or,Nv,Xt,Ii,ut,Zt,Oe,gs,cr,ft,xe,$n,Bn,dr,Fn,Lt,Hn,se,Ai,it,qn,hl,eS,_o,Xh,Vv,Mi,Lv,pl,tS,ml,sS,jn,Gn,ko,xv,qr,Wn,Oi,Uv,Jn,Co,Zh,Di,Ro,$v,Io,Bv,jr,Kn,xt,Fv,es,gl,oe,Ao,Ns,ze,Mo,ep,zn,ou,Gr,fs,Wr,Oo,vt,Ni,lr,Do,No,Vi,Hv,Ue,Li,vs,Yn,Jr,xi,fl,rS,Vo,tp,Lo,sp,xo,rp,qv,Uo,Qn,Xn,Zn,cu,jv,Ui,$i,qe,Ee,ve,ur,ts,$o,De,Bi,Bo,Fi,vl,ea,ss,Ye,Gv,Hi,Fo,ta,Ho,St,qi,qo,sa,ia,jo,na,aa,hr,Vs,nt,Kr,zr,Sl,iS,Yr,Qr,Go,ip,Wo,Ss,Tl,nS,oa,ca,Ut,ji,Wc,Xr,$a,Gi,Jc,yl,aS,pr,Jo,Zr,Wi,Kc,mr,El,Ko,np,bl,oS,wl,cS,Wv,ei,Ne,zo,ap,Ji,zc,da,du,Ki,kt,Jv,rs,Ts,la,Kv,Y,ua,ha,Pl,Tt,Gt,$t,pa,yt,ma,Qe,gr,fn,Xe,mt,ga,lu,$e,Ge,fa,va,Yo,op,zv,Qo,Ze,Xo,Zo,zi,Ls,kl,xs,li,ec,cp,Cl,dS,Rl,lS,ys,Sa,Ta,Yi,is,at,ti,ya,Il,Bt,_s,si,Al,Qi,Xi,fr,Zi,wa,et,tt,tc,sc,en,Pa,rc,_a,tn,Us,ka,uu,ic,dp,Ml,uS,nc,lp,Ol,hS,Dl,pS,Nl,mS,Vl,gS,Ll,fS,ac,up,ri,Ba,xl,ns,ii,ni,Ca,oc,$s,Ul,vr,Ra,cc,hp,$l,vS,Bl,SS,Fl,TS,Hl,yS,dc,lc,uc,Ia,Aa,Ma,hc,pc,Oa,Ct,Es,bs,sn,rn,Sr,mc,ql,ES,jl,bS,Gl,wS,Wl,PS,gc,fc,Tr,yr,Er,vc,Da,Na,ai,nn,Va,an,br,Bs,Kl,_S,Sc,pp,zl,kS,Yl,CS,yc,Ec,ht,q,Ql,Et,on,cn,dn,bc,Ft,Fs,pt,Rt,wr,vn,Xl,RS,Zl,IS,eu,AS,wc,mp,tu,MS,su,OS,bt,Wt,ln,Yc,ru,DS,iu,NS,nu,VS,La,ws,ee,It,os,Yv,Pc,_c,kc,Pr,xa,Ht,At,oi,Ua,ci,Ce,Re,Fe,as,st,Cc,gp,Rc,fp,Qv,qt,Se,Xv,di,un,hn,Ic,au,LS,pn,He,mn,Zv;"use strict";var X1=Object.defineProperty;var Z1=(Pe,be,_e)=>be in Pe?X1(Pe,be,{enumerable:!0,configurable:!0,writable:!0,value:_e}):Pe[be]=_e;var p=(Pe,be,_e)=>(Z1(Pe,typeof be!="symbol"?be+"":be,_e),_e),Qh=(Pe,be,_e)=>{if(!be.has(Pe))throw TypeError("Cannot "+_e)};var a=(Pe,be,_e)=>(Qh(Pe,be,"read from private field"),_e?_e.call(Pe):be.get(Pe)),g=(Pe,be,_e)=>{if(be.has(Pe))throw TypeError("Cannot add the same private member more than once");be instanceof WeakSet?be.add(Pe):be.set(Pe,_e)},f=(Pe,be,_e,Qc)=>(Qh(Pe,be,"write to private field"),Qc?Qc.call(Pe,_e):be.set(Pe,_e),_e);var V=(Pe,be,_e)=>(Qh(Pe,be,"access private method"),_e);function Pe(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:Pe});function be(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:be});var _e,Qc=new Uint8Array(16);function xS(){if(!_e&&(_e=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!_e))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return _e(Qc)}const US=/^(?:[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 hu(s){return typeof s=="string"&&US.test(s)}for(var rt=[],pu=0;pu<256;++pu)rt.push((pu+256).toString(16).substr(1));function $S(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(rt[s[t+0]]+rt[s[t+1]]+rt[s[t+2]]+rt[s[t+3]]+"-"+rt[s[t+4]]+rt[s[t+5]]+"-"+rt[s[t+6]]+rt[s[t+7]]+"-"+rt[s[t+8]]+rt[s[t+9]]+"-"+rt[s[t+10]]+rt[s[t+11]]+rt[s[t+12]]+rt[s[t+13]]+rt[s[t+14]]+rt[s[t+15]]).toLowerCase();if(!hu(e))throw TypeError("Stringified UUID is invalid");return e}function Sn(s,t,e){s=s||{};var r=s.random||(s.rng||xS)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){e=e||0;for(var i=0;i<16;++i)t[e+i]=r[i];return t}return $S(r)}const BS=s=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&s.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,i,n,o,c,d,l;s.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:(n=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:n.baseURL,method:(c=(o=t==null?void 0:t.reason)==null?void 0:o.config)==null?void 0:c.method,status:(d=t==null?void 0:t.reason)==null?void 0:d.status,statusText:(l=t==null?void 0:t.reason)==null?void 0:l.statusText}},!0)}),window.addEventListener("offline",()=>{s.info("window::offline")}),window.addEventListener("online",()=>{s.info("window::online")}))},FS={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},vp={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},Q={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},ot={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},_r={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"};class b{static getFirstMatch(t,e){const r=e.match(t);return r&&r.length>0&&r[1]||""}static getSecondMatch(t,e){const r=e.match(t);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(t,e,r){if(t.test(e))return r}static getWindowsVersionName(t){switch(t){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(t){const e=t.split(".").splice(0,2).map(n=>parseInt(n,10)||0);e.push(0);const r=e[0],i=e[1];if(r===10)switch(i){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}switch(r){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}}static getAndroidVersionName(t){const e=t.split(".").splice(0,2).map(r=>parseInt(r,10)||0);if(e.push(0),!(e[0]===1&&e[1]<5)){if(e[0]===1&&e[1]<6)return"Cupcake";if(e[0]===1&&e[1]>=6)return"Donut";if(e[0]===2&&e[1]<2)return"Eclair";if(e[0]===2&&e[1]===2)return"Froyo";if(e[0]===2&&e[1]>2)return"Gingerbread";if(e[0]===3)return"Honeycomb";if(e[0]===4&&e[1]<1)return"Ice Cream Sandwich";if(e[0]===4&&e[1]<4)return"Jelly Bean";if(e[0]===4&&e[1]>=4)return"KitKat";if(e[0]===5)return"Lollipop";if(e[0]===6)return"Marshmallow";if(e[0]===7)return"Nougat";if(e[0]===8)return"Oreo";if(e[0]===9)return"Pie"}}static getVersionPrecision(t){return t.split(".").length}static compareVersions(t,e,r=!1){const i=b.getVersionPrecision(t),n=b.getVersionPrecision(e);let o=Math.max(i,n),c=0;const d=b.map([t,e],l=>{const u=o-b.getVersionPrecision(l),h=l+new Array(u+1).join(".0");return b.map(h.split("."),m=>new Array(20-m.length).join("0")+m).reverse()});for(r&&(c=o-Math.min(i,n)),o-=1;o>=c;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===c)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(t,e){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)r.push(e(t[i]));return r}static find(t,e){let r,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(r=0,i=t.length;r<i;r+=1){const n=t[r];if(e(n,r))return n}}static assign(t,...e){const r=t;let i,n;if(Object.assign)return Object.assign(t,...e);for(i=0,n=e.length;i<n;i+=1){const o=e[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{r[d]=o[d]})}return t}static getBrowserAlias(t){return FS[t]}static getBrowserTypeByAlias(t){return vp[t]||""}}const X=/version\/(\d+(\.?_?\d+)+)/i,HS=[{test:[/gptbot/i],describe(s){const t={name:"GPTBot"},e=b.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/chatgpt-user/i],describe(s){const t={name:"ChatGPT-User"},e=b.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/oai-searchbot/i],describe(s){const t={name:"OAI-SearchBot"},e=b.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(s){const t={name:"ClaudeBot"},e=b.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/omgilibot/i,/webzio-extended/i],describe(s){const t={name:"Omgilibot"},e=b.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/diffbot/i],describe(s){const t={name:"Diffbot"},e=b.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/perplexitybot/i],describe(s){const t={name:"PerplexityBot"},e=b.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/perplexity-user/i],describe(s){const t={name:"Perplexity-User"},e=b.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/youbot/i],describe(s){const t={name:"YouBot"},e=b.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-webindexer/i],describe(s){const t={name:"Meta-WebIndexer"},e=b.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalads/i],describe(s){const t={name:"Meta-ExternalAds"},e=b.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalagent/i],describe(s){const t={name:"Meta-ExternalAgent"},e=b.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalfetcher/i],describe(s){const t={name:"Meta-ExternalFetcher"},e=b.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=b.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/linespider/i],describe(s){const t={name:"Linespider"},e=b.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/amazonbot/i],describe(s){const t={name:"AmazonBot"},e=b.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/bingbot/i],describe(s){const t={name:"BingCrawler"},e=b.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/baiduspider/i],describe(s){const t={name:"BaiduSpider"},e=b.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/duckduckbot/i],describe(s){const t={name:"DuckDuckBot"},e=b.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/ia_archiver/i],describe(s){const t={name:"InternetArchiveCrawler"},e=b.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(s){const t={name:"SlackBot"},e=b.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/yahoo!?[\s/]*slurp/i],describe(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe(){return{name:"PingdomBot"}}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=b.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Whale/i],describe(s){const t={name:"NAVER Whale Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/PaleMoon/i],describe(s){const t={name:"Pale Moon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=b.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=b.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=b.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(s){const t={name:"Opera Touch"},e=b.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=b.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/k-meleon/i],describe(s){const t={name:"K-Meleon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=b.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/qqbrowser/i],describe(s){const t={name:/qqbrowserlite/i.test(s)?"QQ Browser Lite":"QQ Browser"},e=b.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=b.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=b.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/edg([ea]|ios)/i],describe(s){const t={name:"Microsoft Edge"},e=b.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=b.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=b.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=b.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,s);return e&&(t.version=e),t}},{test:[/silk/i],describe(s){const t={name:"Amazon Silk"},e=b.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=b.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=b.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t={name:"BlackBerry"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(web|hpw)[o0]s/i],describe(s){const t={name:"WebOS Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/bada/i],describe(s){const t={name:"Bada"},e=b.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=b.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=b.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/librewolf/i],describe(s){const t={name:"LibreWolf"},e=b.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=b.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/electron/i],describe(s){const t={name:"Electron"},e=b.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe(s){const t={name:"Sogou Browser"},e=b.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,s),r=b.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s),i=b.getFirstMatch(/se ([\d.]+)x/i,s),n=e||r||i;return n&&(t.version=n),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=b.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.hasBrand("DuckDuckGo")?!0:s.test(/\sDdg\/[\d.]+$/i)},describe(s,t){const e={name:"DuckDuckGo"};if(t){const i=t.getBrandVersion("DuckDuckGo");if(i)return e.version=i,e}const r=b.getFirstMatch(/\sDdg\/([\d.]+)$/i,s);return r&&(e.version=r),e}},{test(s){return s.hasBrand("Brave")},describe(s,t){const e={name:"Brave"};if(t){const r=t.getBrandVersion("Brave");if(r)return e.version=r,e}return e}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=b.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=b.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/GSA/i],describe(s){const t={name:"Google Search"},e=b.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t={name:"Android Browser"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,i=s.search("\\(")!==-1?e:t;return{name:b.getFirstMatch(i,s),version:b.getSecondMatch(i,s)}}}],qS=[{test:[/Roku\/DVP/],describe(s){const t=b.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:ot.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=b.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:ot.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=b.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=b.getWindowsVersionName(t);return{name:ot.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:ot.iOS},e=b.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=b.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=b.getMacOSVersionName(t),r={name:ot.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=b.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:ot.iOS,version:t}}},{test:[/OpenHarmony/i],describe(s){const t=b.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,s);return{name:ot.HarmonyOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=b.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=b.getAndroidVersionName(t),r={name:ot.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=b.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:ot.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=b.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||b.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||b.getFirstMatch(/\bbb(\d+)/i,s);return{name:ot.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=b.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:ot.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=b.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:ot.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:ot.Linux}}},{test:[/CrOS/],describe(){return{name:ot.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=b.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:ot.PlayStation4,version:t}}}],jS=[{test:[/googlebot/i],describe(){return{type:Q.bot,vendor:"Google"}}},{test:[/linespider/i],describe(){return{type:Q.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe(){return{type:Q.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe(){return{type:Q.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe(){return{type:Q.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe(){return{type:Q.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(){return{type:Q.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe(){return{type:Q.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe(){return{type:Q.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe(){return{type:Q.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe(){return{type:Q.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe(){return{type:Q.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe(){return{type:Q.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(){return{type:Q.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe(){return{type:Q.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{type:Q.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe(){return{type:Q.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe(s){const t=b.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Q.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Q.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Q.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Q.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Q.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Q.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Q.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=b.getFirstMatch(/(ipod|iphone)/i,s);return{type:Q.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Q.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe(s){const t=b.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,s),e={type:Q.mobile,vendor:"Nokia"};return t&&(e.model=t),e}},{test:[/[^-]mobi/i],describe(){return{type:Q.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Q.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Q.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Q.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Q.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Q.mobile}}},{test:[/smart-?tv|smarttv/i],describe(){return{type:Q.tv}}},{test:[/netcast/i],describe(){return{type:Q.tv}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Q.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Q.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Q.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Q.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Q.tv}}}],GS=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:_r.Blink};const e=b.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:_r.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:_r.Trident},e=b.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:_r.Presto},e=b.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=s.test(/gecko/i),e=s.test(/like gecko/i);return t&&!e},describe(s){const t={name:_r.Gecko},e=b.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:_r.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:_r.WebKit},e=b.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class Sp{constructor(t,e=!1,r=null){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t;let i=!1;typeof e=="boolean"?(i=e,this._hints=r):e!=null&&typeof e=="object"?this._hints=e:this._hints=null,this.parsedResult={},i!==!0&&this.parse()}getHints(){return this._hints}hasBrand(t){if(!this._hints||!Array.isArray(this._hints.brands))return!1;const e=t.toLowerCase();return this._hints.brands.some(r=>r.brand&&r.brand.toLowerCase()===e)}getBrandVersion(t){if(!this._hints||!Array.isArray(this._hints.brands))return;const e=t.toLowerCase(),r=this._hints.brands.find(i=>i.brand&&i.brand.toLowerCase()===e);return r?r.version:void 0}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=b.find(HS,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA(),this)),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(t){return t?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 t=b.find(qS,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os}getOSName(t){const{name:e}=this.getOS();return t?String(e).toLowerCase()||"":e||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(t=!1){const{type:e}=this.getPlatform();return t?String(e).toLowerCase()||"":e||""}parsePlatform(){this.parsedResult.platform={};const t=b.find(jS,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(t){return t?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const t=b.find(GS,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return b.assign({},this.parsedResult)}satisfies(t){const e={};let r=0;const i={};let n=0;if(Object.keys(t).forEach(c=>{const d=t[c];typeof d=="string"?(i[c]=d,n+=1):typeof d=="object"&&(e[c]=d,r+=1)}),r>0){const c=Object.keys(e),d=b.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(e[d]);if(u!==void 0)return u}const l=b.find(c,u=>this.isPlatform(u));if(l){const u=this.satisfies(e[l]);if(u!==void 0)return u}}if(n>0){const c=Object.keys(i),d=b.find(c,l=>this.isBrowser(l,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(t,e=!1){const r=this.getBrowserName().toLowerCase();let i=t.toLowerCase();const n=b.getBrowserTypeByAlias(i);return e&&n&&(i=n.toLowerCase()),i===r}compareVersion(t){let e=[0],r=t,i=!1;const n=this.getBrowserVersion();if(typeof n=="string")return t[0]===">"||t[0]==="<"?(r=t.substr(1),t[1]==="="?(i=!0,r=t.substr(2)):e=[],t[0]===">"?e.push(1):e.push(-1)):t[0]==="="?r=t.substr(1):t[0]==="~"&&(i=!0,r=t.substr(1)),e.indexOf(b.compareVersions(n,r,i))>-1}isOS(t){return this.getOSName(!0)===String(t).toLowerCase()}isPlatform(t){return this.getPlatformType(!0)===String(t).toLowerCase()}isEngine(t){return this.getEngineName(!0)===String(t).toLowerCase()}is(t,e=!1){return this.isBrowser(t,e)||this.isOS(t)||this.isPlatform(t)}some(t=[]){return t.some(e=>this.is(e))}}/*!
1
+ var RealtimeKitClient=function(){var Po,ar,or,VS,Xt,Ii,ht,Zt,De,gs,cr,St,Ue,$n,Bn,dr,Fn,xt,Hn,se,Ai,nt,qn,pl,tv,_o,Xh,LS,Mi,xS,ml,sv,gl,rv,jn,Gn,ko,US,qr,Wn,Oi,$S,Jn,Co,Zh,Di,Ro,BS,Io,FS,jr,Kn,Ut,HS,es,fl,oe,Ao,Ns,Ye,Mo,ep,zn,cu,Gr,fs,Wr,Oo,vt,Ni,lr,Do,No,Vi,qS,$e,Li,Ss,Yn,Jr,xi,Sl,iv,Vo,tp,Lo,sp,xo,rp,jS,Uo,Qn,Xn,Zn,du,GS,Ui,$i,je,Ee,Se,ur,ts,$o,Ne,Bi,Bo,Fi,vl,ea,ss,Qe,WS,Hi,Fo,ta,Ho,Tt,qi,qo,sa,ia,jo,na,aa,hr,Vs,at,Kr,zr,Tl,nv,Yr,Qr,Go,ip,Wo,vs,yl,av,oa,ca,$t,ji,Wc,Xr,$a,Gi,Jc,El,ov,pr,Jo,Zr,Wi,Kc,mr,bl,Ko,np,wl,cv,Pl,dv,JS,ei,Ve,zo,ap,Ji,zc,da,lu,Ki,Ct,KS,rs,Ts,la,zS,Y,ua,ha,_l,yt,Gt,Bt,pa,Et,ma,Xe,gr,fn,Ze,gt,ga,uu,Be,We,fa,Sa,Yo,op,YS,Qo,et,Xo,Zo,zi,Ls,Cl,xs,li,ec,cp,Rl,lv,Il,uv,ys,va,Ta,Yi,is,ot,ti,ya,Al,Ft,_s,si,Ml,Qi,Xi,fr,Zi,wa,tt,st,tc,sc,en,Pa,rc,_a,tn,Us,ka,hu,ic,dp,Ol,hv,nc,lp,Dl,pv,Nl,mv,Vl,gv,Ll,fv,xl,Sv,ac,up,ri,Ba,Ul,ns,ii,ni,Ca,oc,$s,$l,Sr,Ra,cc,hp,Bl,vv,Fl,Tv,Hl,yv,ql,Ev,dc,lc,uc,Ia,Aa,Ma,hc,pc,Oa,Rt,Es,bs,sn,rn,vr,mc,jl,bv,Gl,wv,Wl,Pv,Jl,_v,gc,fc,Tr,yr,Er,Sc,Da,Na,ai,nn,Va,an,br,Bs,zl,kv,vc,pp,Yl,Cv,Ql,Rv,yc,Ec,pt,q,Xl,bt,on,cn,dn,bc,Ht,Fs,mt,It,wr,Sn,Zl,Iv,eu,Av,tu,Mv,wc,mp,su,Ov,ru,Dv,wt,Wt,ln,Yc,iu,Nv,nu,Vv,au,Lv,La,ws,ee,At,os,QS,Pc,_c,kc,Pr,xa,qt,Mt,oi,Ua,ci,Re,Ie,He,as,rt,Cc,gp,Rc,fp,XS,jt,ve,ZS,di,un,hn,Ic,ou,xv,pn,qe,mn,ev;"use strict";var Z1=Object.defineProperty;var eN=(_e,we,ke)=>we in _e?Z1(_e,we,{enumerable:!0,configurable:!0,writable:!0,value:ke}):_e[we]=ke;var p=(_e,we,ke)=>(eN(_e,typeof we!="symbol"?we+"":we,ke),ke),Qh=(_e,we,ke)=>{if(!we.has(_e))throw TypeError("Cannot "+ke)};var a=(_e,we,ke)=>(Qh(_e,we,"read from private field"),ke?ke.call(_e):we.get(_e)),g=(_e,we,ke)=>{if(we.has(_e))throw TypeError("Cannot add the same private member more than once");we instanceof WeakSet?we.add(_e):we.set(_e,ke)},f=(_e,we,ke,Qc)=>(Qh(_e,we,"write to private field"),Qc?Qc.call(_e,ke):we.set(_e,ke),ke);var L=(_e,we,ke)=>(Qh(_e,we,"access private method"),ke);function _e(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}Array.prototype.at||Object.assign(Array.prototype,{at:_e});function we(s){const{length:t}=this,e=s>=0?s:t+s;return e<0||e>=t?void 0:this[e]}String.prototype.at||Object.assign(String.prototype,{at:we});var ke,Qc=new Uint8Array(16);function Uv(){if(!ke&&(ke=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto!="undefined"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!ke))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ke(Qc)}const $v=/^(?:[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 pu(s){return typeof s=="string"&&$v.test(s)}for(var it=[],mu=0;mu<256;++mu)it.push((mu+256).toString(16).substr(1));function Bv(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(it[s[t+0]]+it[s[t+1]]+it[s[t+2]]+it[s[t+3]]+"-"+it[s[t+4]]+it[s[t+5]]+"-"+it[s[t+6]]+it[s[t+7]]+"-"+it[s[t+8]]+it[s[t+9]]+"-"+it[s[t+10]]+it[s[t+11]]+it[s[t+12]]+it[s[t+13]]+it[s[t+14]]+it[s[t+15]]).toLowerCase();if(!pu(e))throw TypeError("Stringified UUID is invalid");return e}function vn(s,t,e){s=s||{};var r=s.random||(s.rng||Uv)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){e=e||0;for(var i=0;i<16;++i)t[e+i]=r[i];return t}return Bv(r)}const Fv=s=>{!navigator.isReactNative&&typeof window!="undefined"&&(window.addEventListener("error",t=>{var e;!((e=t.filename)!=null&&e.includes("localhost"))&&t.lineno!==0&&s.error("window::error",{error:t.error},!0)}),window.addEventListener("unhandledrejection",t=>{var e,r,i,n,o,c,d,l;s.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:(n=(i=t==null?void 0:t.reason)==null?void 0:i.config)==null?void 0:n.baseURL,method:(c=(o=t==null?void 0:t.reason)==null?void 0:o.config)==null?void 0:c.method,status:(d=t==null?void 0:t.reason)==null?void 0:d.status,statusText:(l=t==null?void 0:t.reason)==null?void 0:l.statusText}},!0)}),window.addEventListener("offline",()=>{s.info("window::offline")}),window.addEventListener("online",()=>{s.info("window::online")}))},Hv={AmazonBot:"amazonbot","Amazon Silk":"amazon_silk","Android Browser":"android",BaiduSpider:"baiduspider",Bada:"bada",BingCrawler:"bingcrawler",Brave:"brave",BlackBerry:"blackberry","ChatGPT-User":"chatgpt_user",Chrome:"chrome",ClaudeBot:"claudebot",Chromium:"chromium",Diffbot:"diffbot",DuckDuckBot:"duckduckbot",DuckDuckGo:"duckduckgo",Electron:"electron",Epiphany:"epiphany",FacebookExternalHit:"facebookexternalhit",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot",GPTBot:"gptbot","Internet Explorer":"ie",InternetArchiveCrawler:"internetarchivecrawler","K-Meleon":"k_meleon",LibreWolf:"librewolf",Linespider:"linespider",Maxthon:"maxthon","Meta-ExternalAds":"meta_externalads","Meta-ExternalAgent":"meta_externalagent","Meta-ExternalFetcher":"meta_externalfetcher","Meta-WebIndexer":"meta_webindexer","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver","OAI-SearchBot":"oai_searchbot",Omgilibot:"omgilibot",Opera:"opera","Opera Coast":"opera_coast","Pale Moon":"pale_moon",PerplexityBot:"perplexitybot","Perplexity-User":"perplexity_user",PhantomJS:"phantomjs",PingdomBot:"pingdombot",Puffin:"puffin",QQ:"qq",QQLite:"qqlite",QupZilla:"qupzilla",Roku:"roku",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SlackBot:"slackbot",SeaMonkey:"seamonkey",Sleipnir:"sleipnir","Sogou Browser":"sogou",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat",YahooSlurp:"yahooslurp","Yandex Browser":"yandex",YandexBot:"yandexbot",YouBot:"youbot"},Sp={amazonbot:"AmazonBot",amazon_silk:"Amazon Silk",android:"Android Browser",baiduspider:"BaiduSpider",bada:"Bada",bingcrawler:"BingCrawler",blackberry:"BlackBerry",brave:"Brave",chatgpt_user:"ChatGPT-User",chrome:"Chrome",claudebot:"ClaudeBot",chromium:"Chromium",diffbot:"Diffbot",duckduckbot:"DuckDuckBot",duckduckgo:"DuckDuckGo",edge:"Microsoft Edge",electron:"Electron",epiphany:"Epiphany",facebookexternalhit:"FacebookExternalHit",firefox:"Firefox",focus:"Focus",generic:"Generic",google_search:"Google Search",googlebot:"Googlebot",gptbot:"GPTBot",ie:"Internet Explorer",internetarchivecrawler:"InternetArchiveCrawler",k_meleon:"K-Meleon",librewolf:"LibreWolf",linespider:"Linespider",maxthon:"Maxthon",meta_externalads:"Meta-ExternalAds",meta_externalagent:"Meta-ExternalAgent",meta_externalfetcher:"Meta-ExternalFetcher",meta_webindexer:"Meta-WebIndexer",mz:"MZ Browser",naver:"NAVER Whale Browser",oai_searchbot:"OAI-SearchBot",omgilibot:"Omgilibot",opera:"Opera",opera_coast:"Opera Coast",pale_moon:"Pale Moon",perplexitybot:"PerplexityBot",perplexity_user:"Perplexity-User",phantomjs:"PhantomJS",pingdombot:"PingdomBot",puffin:"Puffin",qq:"QQ Browser",qqlite:"QQ Browser Lite",qupzilla:"QupZilla",roku:"Roku",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",slackbot:"SlackBot",sleipnir:"Sleipnir",sogou:"Sogou Browser",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yahooslurp:"YahooSlurp",yandex:"Yandex Browser",yandexbot:"YandexBot",youbot:"YouBot"},Q={bot:"bot",desktop:"desktop",mobile:"mobile",tablet:"tablet",tv:"tv"},ct={Android:"Android",Bada:"Bada",BlackBerry:"BlackBerry",ChromeOS:"Chrome OS",HarmonyOS:"HarmonyOS",iOS:"iOS",Linux:"Linux",MacOS:"macOS",PlayStation4:"PlayStation 4",Roku:"Roku",Tizen:"Tizen",WebOS:"WebOS",Windows:"Windows",WindowsPhone:"Windows Phone"},_r={Blink:"Blink",EdgeHTML:"EdgeHTML",Gecko:"Gecko",Presto:"Presto",Trident:"Trident",WebKit:"WebKit"};class b{static getFirstMatch(t,e){const r=e.match(t);return r&&r.length>0&&r[1]||""}static getSecondMatch(t,e){const r=e.match(t);return r&&r.length>1&&r[2]||""}static matchAndReturnConst(t,e,r){if(t.test(e))return r}static getWindowsVersionName(t){switch(t){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(t){const e=t.split(".").splice(0,2).map(n=>parseInt(n,10)||0);e.push(0);const r=e[0],i=e[1];if(r===10)switch(i){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}switch(r){case 11:return"Big Sur";case 12:return"Monterey";case 13:return"Ventura";case 14:return"Sonoma";case 15:return"Sequoia";default:return}}static getAndroidVersionName(t){const e=t.split(".").splice(0,2).map(r=>parseInt(r,10)||0);if(e.push(0),!(e[0]===1&&e[1]<5)){if(e[0]===1&&e[1]<6)return"Cupcake";if(e[0]===1&&e[1]>=6)return"Donut";if(e[0]===2&&e[1]<2)return"Eclair";if(e[0]===2&&e[1]===2)return"Froyo";if(e[0]===2&&e[1]>2)return"Gingerbread";if(e[0]===3)return"Honeycomb";if(e[0]===4&&e[1]<1)return"Ice Cream Sandwich";if(e[0]===4&&e[1]<4)return"Jelly Bean";if(e[0]===4&&e[1]>=4)return"KitKat";if(e[0]===5)return"Lollipop";if(e[0]===6)return"Marshmallow";if(e[0]===7)return"Nougat";if(e[0]===8)return"Oreo";if(e[0]===9)return"Pie"}}static getVersionPrecision(t){return t.split(".").length}static compareVersions(t,e,r=!1){const i=b.getVersionPrecision(t),n=b.getVersionPrecision(e);let o=Math.max(i,n),c=0;const d=b.map([t,e],l=>{const u=o-b.getVersionPrecision(l),h=l+new Array(u+1).join(".0");return b.map(h.split("."),m=>new Array(20-m.length).join("0")+m).reverse()});for(r&&(c=o-Math.min(i,n)),o-=1;o>=c;){if(d[0][o]>d[1][o])return 1;if(d[0][o]===d[1][o]){if(o===c)return 0;o-=1}else if(d[0][o]<d[1][o])return-1}}static map(t,e){const r=[];let i;if(Array.prototype.map)return Array.prototype.map.call(t,e);for(i=0;i<t.length;i+=1)r.push(e(t[i]));return r}static find(t,e){let r,i;if(Array.prototype.find)return Array.prototype.find.call(t,e);for(r=0,i=t.length;r<i;r+=1){const n=t[r];if(e(n,r))return n}}static assign(t,...e){const r=t;let i,n;if(Object.assign)return Object.assign(t,...e);for(i=0,n=e.length;i<n;i+=1){const o=e[i];typeof o=="object"&&o!==null&&Object.keys(o).forEach(d=>{r[d]=o[d]})}return t}static getBrowserAlias(t){return Hv[t]}static getBrowserTypeByAlias(t){return Sp[t]||""}}const X=/version\/(\d+(\.?_?\d+)+)/i,qv=[{test:[/gptbot/i],describe(s){const t={name:"GPTBot"},e=b.getFirstMatch(/gptbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/chatgpt-user/i],describe(s){const t={name:"ChatGPT-User"},e=b.getFirstMatch(/chatgpt-user\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/oai-searchbot/i],describe(s){const t={name:"OAI-SearchBot"},e=b.getFirstMatch(/oai-searchbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(s){const t={name:"ClaudeBot"},e=b.getFirstMatch(/(?:claudebot|claude-web|claude-user|claude-searchbot)\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/omgilibot/i,/webzio-extended/i],describe(s){const t={name:"Omgilibot"},e=b.getFirstMatch(/(?:omgilibot|webzio-extended)\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/diffbot/i],describe(s){const t={name:"Diffbot"},e=b.getFirstMatch(/diffbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/perplexitybot/i],describe(s){const t={name:"PerplexityBot"},e=b.getFirstMatch(/perplexitybot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/perplexity-user/i],describe(s){const t={name:"Perplexity-User"},e=b.getFirstMatch(/perplexity-user\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/youbot/i],describe(s){const t={name:"YouBot"},e=b.getFirstMatch(/youbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-webindexer/i],describe(s){const t={name:"Meta-WebIndexer"},e=b.getFirstMatch(/meta-webindexer\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalads/i],describe(s){const t={name:"Meta-ExternalAds"},e=b.getFirstMatch(/meta-externalads\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalagent/i],describe(s){const t={name:"Meta-ExternalAgent"},e=b.getFirstMatch(/meta-externalagent\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/meta-externalfetcher/i],describe(s){const t={name:"Meta-ExternalFetcher"},e=b.getFirstMatch(/meta-externalfetcher\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=b.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/linespider/i],describe(s){const t={name:"Linespider"},e=b.getFirstMatch(/(?:linespider)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/amazonbot/i],describe(s){const t={name:"AmazonBot"},e=b.getFirstMatch(/amazonbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/bingbot/i],describe(s){const t={name:"BingCrawler"},e=b.getFirstMatch(/bingbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/baiduspider/i],describe(s){const t={name:"BaiduSpider"},e=b.getFirstMatch(/baiduspider\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/duckduckbot/i],describe(s){const t={name:"DuckDuckBot"},e=b.getFirstMatch(/duckduckbot\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/ia_archiver/i],describe(s){const t={name:"InternetArchiveCrawler"},e=b.getFirstMatch(/ia_archiver\/(\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{name:"FacebookExternalHit"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(s){const t={name:"SlackBot"},e=b.getFirstMatch(/(?:slackbot|slack-imgproxy)(?:-[-\w]+)?[\s/](\d+(\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/yahoo!?[\s/]*slurp/i],describe(){return{name:"YahooSlurp"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{name:"YandexBot"}}},{test:[/pingdom/i],describe(){return{name:"PingdomBot"}}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=b.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Whale/i],describe(s){const t={name:"NAVER Whale Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/PaleMoon/i],describe(s){const t={name:"Pale Moon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:PaleMoon)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=b.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=b.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=b.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(s){const t={name:"Opera Touch"},e=b.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=b.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/k-meleon/i],describe(s){const t={name:"K-Meleon"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=b.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/qqbrowser/i],describe(s){const t={name:/qqbrowserlite/i.test(s)?"QQ Browser Lite":"QQ Browser"},e=b.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=b.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=b.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/edg([ea]|ios)/i],describe(s){const t={name:"Microsoft Edge"},e=b.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=b.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=b.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=b.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,s);return e&&(t.version=e),t}},{test:[/silk/i],describe(s){const t={name:"Amazon Silk"},e=b.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=b.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=b.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t={name:"BlackBerry"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(web|hpw)[o0]s/i],describe(s){const t={name:"WebOS Browser"},e=b.getFirstMatch(X,s)||b.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/bada/i],describe(s){const t={name:"Bada"},e=b.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=b.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=b.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/librewolf/i],describe(s){const t={name:"LibreWolf"},e=b.getFirstMatch(/(?:librewolf)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=b.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/electron/i],describe(s){const t={name:"Electron"},e=b.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sogoumobilebrowser/i,/metasr/i,/se 2\.[x]/i],describe(s){const t={name:"Sogou Browser"},e=b.getFirstMatch(/(?:sogoumobilebrowser)[\s/](\d+(\.?_?\d+)+)/i,s),r=b.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s),i=b.getFirstMatch(/se ([\d.]+)x/i,s),n=e||r||i;return n&&(t.version=n),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=b.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.hasBrand("DuckDuckGo")?!0:s.test(/\sDdg\/[\d.]+$/i)},describe(s,t){const e={name:"DuckDuckGo"};if(t){const i=t.getBrandVersion("DuckDuckGo");if(i)return e.version=i,e}const r=b.getFirstMatch(/\sDdg\/([\d.]+)$/i,s);return r&&(e.version=r),e}},{test(s){return s.hasBrand("Brave")},describe(s,t){const e={name:"Brave"};if(t){const r=t.getBrandVersion("Brave");if(r)return e.version=r,e}return e}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=b.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=b.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/GSA/i],describe(s){const t={name:"Google Search"},e=b.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t={name:"Android Browser"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=b.getFirstMatch(X,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,i=s.search("\\(")!==-1?e:t;return{name:b.getFirstMatch(i,s),version:b.getSecondMatch(i,s)}}}],jv=[{test:[/Roku\/DVP/],describe(s){const t=b.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:ct.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=b.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:ct.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=b.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=b.getWindowsVersionName(t);return{name:ct.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:ct.iOS},e=b.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=b.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=b.getMacOSVersionName(t),r={name:ct.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=b.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:ct.iOS,version:t}}},{test:[/OpenHarmony/i],describe(s){const t=b.getFirstMatch(/OpenHarmony\s+(\d+(\.\d+)*)/i,s);return{name:ct.HarmonyOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=b.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=b.getAndroidVersionName(t),r={name:ct.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=b.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:ct.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=b.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||b.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||b.getFirstMatch(/\bbb(\d+)/i,s);return{name:ct.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=b.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:ct.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=b.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:ct.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:ct.Linux}}},{test:[/CrOS/],describe(){return{name:ct.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=b.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:ct.PlayStation4,version:t}}}],Gv=[{test:[/googlebot/i],describe(){return{type:Q.bot,vendor:"Google"}}},{test:[/linespider/i],describe(){return{type:Q.bot,vendor:"Line"}}},{test:[/amazonbot/i],describe(){return{type:Q.bot,vendor:"Amazon"}}},{test:[/gptbot/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/chatgpt-user/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/oai-searchbot/i],describe(){return{type:Q.bot,vendor:"OpenAI"}}},{test:[/baiduspider/i],describe(){return{type:Q.bot,vendor:"Baidu"}}},{test:[/bingbot/i],describe(){return{type:Q.bot,vendor:"Bing"}}},{test:[/duckduckbot/i],describe(){return{type:Q.bot,vendor:"DuckDuckGo"}}},{test:[/claudebot/i,/claude-web/i,/claude-user/i,/claude-searchbot/i],describe(){return{type:Q.bot,vendor:"Anthropic"}}},{test:[/omgilibot/i,/webzio-extended/i],describe(){return{type:Q.bot,vendor:"Webz.io"}}},{test:[/diffbot/i],describe(){return{type:Q.bot,vendor:"Diffbot"}}},{test:[/perplexitybot/i],describe(){return{type:Q.bot,vendor:"Perplexity AI"}}},{test:[/perplexity-user/i],describe(){return{type:Q.bot,vendor:"Perplexity AI"}}},{test:[/youbot/i],describe(){return{type:Q.bot,vendor:"You.com"}}},{test:[/ia_archiver/i],describe(){return{type:Q.bot,vendor:"Internet Archive"}}},{test:[/meta-webindexer/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalads/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalagent/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/meta-externalfetcher/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/facebookexternalhit/i,/facebookcatalog/i],describe(){return{type:Q.bot,vendor:"Meta"}}},{test:[/slackbot/i,/slack-imgProxy/i],describe(){return{type:Q.bot,vendor:"Slack"}}},{test:[/yahoo/i],describe(){return{type:Q.bot,vendor:"Yahoo"}}},{test:[/yandexbot/i,/yandexmobilebot/i],describe(){return{type:Q.bot,vendor:"Yandex"}}},{test:[/pingdom/i],describe(){return{type:Q.bot,vendor:"Pingdom"}}},{test:[/huawei/i],describe(s){const t=b.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Q.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Q.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Q.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Q.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Q.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Q.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Q.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=b.getFirstMatch(/(ipod|iphone)/i,s);return{type:Q.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Q.mobile,vendor:"Nexus"}}},{test:[/Nokia/i],describe(s){const t=b.getFirstMatch(/Nokia\s+([0-9]+(\.[0-9]+)?)/i,s),e={type:Q.mobile,vendor:"Nokia"};return t&&(e.model=t),e}},{test:[/[^-]mobi/i],describe(){return{type:Q.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Q.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Q.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Q.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Q.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Q.mobile}}},{test:[/smart-?tv|smarttv/i],describe(){return{type:Q.tv}}},{test:[/netcast/i],describe(){return{type:Q.tv}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Q.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Q.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Q.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Q.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Q.tv}}}],Wv=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:_r.Blink};const e=b.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:_r.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:_r.Trident},e=b.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:_r.Presto},e=b.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){const t=s.test(/gecko/i),e=s.test(/like gecko/i);return t&&!e},describe(s){const t={name:_r.Gecko},e=b.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:_r.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:_r.WebKit},e=b.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class vp{constructor(t,e=!1,r=null){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t;let i=!1;typeof e=="boolean"?(i=e,this._hints=r):e!=null&&typeof e=="object"?this._hints=e:this._hints=null,this.parsedResult={},i!==!0&&this.parse()}getHints(){return this._hints}hasBrand(t){if(!this._hints||!Array.isArray(this._hints.brands))return!1;const e=t.toLowerCase();return this._hints.brands.some(r=>r.brand&&r.brand.toLowerCase()===e)}getBrandVersion(t){if(!this._hints||!Array.isArray(this._hints.brands))return;const e=t.toLowerCase(),r=this._hints.brands.find(i=>i.brand&&i.brand.toLowerCase()===e);return r?r.version:void 0}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=b.find(qv,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.browser=t.describe(this.getUA(),this)),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(t){return t?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 t=b.find(jv,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.os=t.describe(this.getUA())),this.parsedResult.os}getOSName(t){const{name:e}=this.getOS();return t?String(e).toLowerCase()||"":e||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(t=!1){const{type:e}=this.getPlatform();return t?String(e).toLowerCase()||"":e||""}parsePlatform(){this.parsedResult.platform={};const t=b.find(Gv,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.platform=t.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(t){return t?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const t=b.find(Wv,e=>{if(typeof e.test=="function")return e.test(this);if(Array.isArray(e.test))return e.test.some(r=>this.test(r));throw new Error("Browser's test function is not valid")});return t&&(this.parsedResult.engine=t.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return b.assign({},this.parsedResult)}satisfies(t){const e={};let r=0;const i={};let n=0;if(Object.keys(t).forEach(c=>{const d=t[c];typeof d=="string"?(i[c]=d,n+=1):typeof d=="object"&&(e[c]=d,r+=1)}),r>0){const c=Object.keys(e),d=b.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(e[d]);if(u!==void 0)return u}const l=b.find(c,u=>this.isPlatform(u));if(l){const u=this.satisfies(e[l]);if(u!==void 0)return u}}if(n>0){const c=Object.keys(i),d=b.find(c,l=>this.isBrowser(l,!0));if(d!==void 0)return this.compareVersion(i[d])}}isBrowser(t,e=!1){const r=this.getBrowserName().toLowerCase();let i=t.toLowerCase();const n=b.getBrowserTypeByAlias(i);return e&&n&&(i=n.toLowerCase()),i===r}compareVersion(t){let e=[0],r=t,i=!1;const n=this.getBrowserVersion();if(typeof n=="string")return t[0]===">"||t[0]==="<"?(r=t.substr(1),t[1]==="="?(i=!0,r=t.substr(2)):e=[],t[0]===">"?e.push(1):e.push(-1)):t[0]==="="?r=t.substr(1):t[0]==="~"&&(i=!0,r=t.substr(1)),e.indexOf(b.compareVersions(n,r,i))>-1}isOS(t){return this.getOSName(!0)===String(t).toLowerCase()}isPlatform(t){return this.getPlatformType(!0)===String(t).toLowerCase()}isEngine(t){return this.getEngineName(!0)===String(t).toLowerCase()}is(t,e=!1){return this.isBrowser(t,e)||this.isOS(t)||this.isPlatform(t)}some(t=[]){return t.some(e=>this.is(e))}}/*!
2
2
  * Bowser - a browser detector
3
3
  * https://github.com/bowser-js/bowser
4
4
  * MIT License | (c) Dustin Diaz 2012-2015
5
5
  * MIT License | (c) Denis Demchenko 2015-2019
6
- */class Tp{static getParser(t,e=!1,r=null){if(typeof t!="string")throw new Error("UserAgent should be a string");return new Sp(t,e,r)}static parse(t,e=null){return new Sp(t,e).getResult()}static get BROWSER_MAP(){return vp}static get ENGINE_MAP(){return _r}static get OS_MAP(){return ot}static get PLATFORMS_MAP(){return Q}}const Fa="chrome",yp="opera",Ep="firefox",bp="iexplorer",wp="safari",Pp="nwjs",_p="electron",kp="react-native",mu="unknown",Xc={Chrome:Fa,Chromium:Fa,Opera:yp,Firefox:Ep,"Internet Explorer":bp,Safari:wp};function WS(){const{userAgent:s}=navigator,t={name:mu,version:void 0};if(s.match(/Chrome/)&&!s.match(/Edge/))if(s.match(/Edg(A?)/)){const e=s.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(e,10)>72&&(t.name=Fa,t.version=e)}else t.name=Fa,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function JS(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:_p,version:t}}return null}function KS(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Pp,version:t}}}function zS(){const s=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(s||navigator.product==="ReactNative")return s&&s.length>2&&(s[1],t=s[2]),t||(t="unknown"),{name:kp,version:t}}function YS(s){let t;const e=[zS,JS,KS];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in Xc?{name:Xc[r],version:s.getBrowserVersion()}:(t=WS(),t||{name:mu,version:void 0})}class QS{constructor(){p(this,"_bowser");p(this,"_name");p(this,"_version");p(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(t){let e,r;if(this._bowser=Tp.getParser(navigator.userAgent),typeof t=="undefined"){const i=YS(this._bowser);e=i.name,r=i.version}else t.name in Xc?(e=Xc[t.name],r=t.version):(e=mu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===Fa}isOpera(){return this._name===yp}isFirefox(){return this._name===Ep}isIExplorer(){return this._name===bp}isSafari(){return this._name===wp}isNWJS(){return this._name===Pp}isElectron(){return this._name===_p}isReactNative(){return this._name===kp||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(t){if(this._version)return this._bowser.satisfies(t)}isVersionGreaterThan(t){return this._checkCondition({[this._name]:`>${t}`})}isVersionLessThan(t){return this._checkCondition({[this._name]:`<${t}`})}isVersionEqualTo(t){return this._checkCondition({[this._name]:`~${t}`})}}class XS extends QS{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 t=new ReadableStream;try{return window.postMessage(t,"*",[t]),!0}catch(e){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const t=navigator.userAgent;if(t.match(/Chrome/))return Number.parseInt(t.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const Te=new XS;var ct={},ZS={get exports(){return ct},set exports(s){ct=s}},Tn=typeof Reflect=="object"?Reflect:null,Cp=Tn&&typeof Tn.apply=="function"?Tn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Zc;Tn&&typeof Tn.ownKeys=="function"?Zc=Tn.ownKeys:Object.getOwnPropertySymbols?Zc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Zc=function(t){return Object.getOwnPropertyNames(t)};function eT(s){console&&console.warn&&console.warn(s)}var Rp=Number.isNaN||function(t){return t!==t};function ce(){ce.init.call(this)}ZS.exports=ce,ct.once=iT,ce.EventEmitter=ce,ce.prototype._events=void 0,ce.prototype._eventsCount=0,ce.prototype._maxListeners=void 0;var Ip=10;function ed(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return Ip},set:function(s){if(typeof s!="number"||s<0||Rp(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Ip=s}}),ce.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},ce.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Rp(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 Ap(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return Ap(this)},ce.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",n=this._events;if(n!==void 0)i=i&&n.error===void 0;else if(!i)return!1;if(i){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var d=n[t];if(d===void 0)return!1;if(typeof d=="function")Cp(d,this,e);else for(var l=d.length,u=Vp(d,l),r=0;r<l;++r)Cp(u[r],this,e);return!0};function Mp(s,t,e,r){var i,n,o;if(ed(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Ap(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,eT(c)}return s}ce.prototype.addListener=function(t,e){return Mp(this,t,e,!1)},ce.prototype.on=ce.prototype.addListener,ce.prototype.prependListener=function(t,e){return Mp(this,t,e,!0)};function tT(){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 Op(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=tT.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(t,e){return ed(e),this.on(t,Op(this,t,e)),this},ce.prototype.prependOnceListener=function(t,e){return ed(e),this.prependListener(t,Op(this,t,e)),this},ce.prototype.removeListener=function(t,e){var r,i,n,o,c;if(ed(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(n=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():sT(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},ce.prototype.off=ce.prototype.removeListener,ce.prototype.removeAllListeners=function(t){var e,r,i;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 n=Object.keys(r),o;for(i=0;i<n.length;++i)o=n[i],o!=="removeListener"&&this.removeAllListeners(o);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(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function Dp(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?rT(i):Vp(i,i.length)}ce.prototype.listeners=function(t){return Dp(this,t,!0)},ce.prototype.rawListeners=function(t){return Dp(this,t,!1)},ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Np.call(s,t)},ce.prototype.listenerCount=Np;function Np(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ce.prototype.eventNames=function(){return this._eventsCount>0?Zc(this._events):[]};function Vp(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function sT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function rT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function iT(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Lp(s,t,n,{once:!0}),t!=="error"&&nT(s,i,{once:!0})})}function nT(s,t,e){typeof s.on=="function"&&Lp(s,"error",t,e)}function Lp(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var W;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(W||(W={}));var D;(function(s){s.PRECALL_TEST_BEGIN="precall_begin",s.PRECALL_TEST_COMPLETE="precall_end",s.CALL_JOIN_BEGIN="call_join",s.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",s.NET_QUALITY_TEST_END="net_quality_test_end",s.WEBSOCKET_CONNECTED="websocket_connected",s.TRANSPORT_CONNECTED="transport_connected",s.AUDIO_ON="audio_on",s.AUDIO_OFF="audio_off",s.VIDEO_ON="video_on",s.VIDEO_OFF="video_off",s.PARTICIPANT_ROLE="participant_role",s.PING_STAT="ping_stat",s.DISCONNECT="disconnect",s.RECONNECT_ATTEMPT="reconnect_attempt",s.SCREENSHARE_START_REQUESTED="screenshare_start_requested",s.SCREENSHARE_STARTED="screenshare_started",s.SCREENSHARE_STOPPED="screenshare_stopped",s.TAB_CHANGE="tab_change",s.BROWSER_BACKGROUNDED="browser_backgrounded",s.BROWSER_FOREGROUNDED="browser_foregrounded",s.DOMINANT_SPEAKER="dominant_speaker",s.AUDIO_DEVICES_UPDATES="audio_devices_updates",s.VIDEO_DEVICES_UPDATES="video_devices_updates",s.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",s.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",s.SELECTED_CAMERA_UPDATE="selected_camera_update",s.SELECTED_SPEAKER_UPDATE="selected_speaker_update",s.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",s.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",s.MEDIA_PERMISSION="media_permission",s.LEGACY_SWITCH="legacy_switch",s.AUDIO_PLAY_FAILED="audio_play_failed",s.VIDEO_PLAY_FAILED="video_play_failed",s.AUDIO_TRACK_MUTED="audio_track_muted",s.VIDEO_TRACK_MUTED="video_track_muted",s.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",s.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",s.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",s.IVS_PLAYER_ERROR="ivs_player_error",s.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",s.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",s.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",s.LIVESTREAM_LATENCY="livestream_latency",s.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",s.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",s.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",s.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(D||(D={}));const aT=new Map([[D.PRECALL_TEST_BEGIN,W.MINOR_EVENT],[D.PRECALL_TEST_COMPLETE,W.MINOR_EVENT],[D.CALL_JOIN_BEGIN,W.MAJOR_EVENT],[D.NET_QUALITY_TEST_BEGIN,W.MINOR_EVENT],[D.NET_QUALITY_TEST_END,W.MINOR_EVENT],[D.WEBSOCKET_CONNECTED,W.MINOR_EVENT],[D.TRANSPORT_CONNECTED,W.MAJOR_EVENT],[D.AUDIO_ON,W.MINOR_EVENT],[D.AUDIO_OFF,W.MINOR_EVENT],[D.VIDEO_ON,W.MINOR_EVENT],[D.VIDEO_OFF,W.MINOR_EVENT],[D.PARTICIPANT_ROLE,W.MINOR_EVENT],[D.PING_STAT,W.MAJOR_EVENT],[D.DISCONNECT,W.MAJOR_EVENT],[D.RECONNECT_ATTEMPT,W.MAJOR_EVENT],[D.SCREENSHARE_START_REQUESTED,W.MINOR_EVENT],[D.SCREENSHARE_STARTED,W.MINOR_EVENT],[D.SCREENSHARE_STOPPED,W.MINOR_EVENT],[D.TAB_CHANGE,W.MINOR_EVENT],[D.BROWSER_BACKGROUNDED,W.MINOR_EVENT],[D.BROWSER_FOREGROUNDED,W.MINOR_EVENT],[D.DOMINANT_SPEAKER,W.MINOR_EVENT],[D.AUDIO_DEVICES_UPDATES,W.MINOR_EVENT],[D.VIDEO_DEVICES_UPDATES,W.MINOR_EVENT],[D.SPEAKER_DEVICES_UPDATES,W.MINOR_EVENT],[D.SELECTED_MICROHPONE_UPDATE,W.MINOR_EVENT],[D.SELECTED_CAMERA_UPDATE,W.MINOR_EVENT],[D.SELECTED_SPEAKER_UPDATE,W.MINOR_EVENT],[D.MEDIA_PERMISSION,W.MINOR_EVENT],[D.LEGACY_SWITCH,W.MINOR_EVENT],[D.AUDIO_PLAY_FAILED,W.MINOR_EVENT],[D.VIDEO_PLAY_FAILED,W.MINOR_EVENT],[D.AUDIO_TRACK_MUTED,W.MINOR_EVENT],[D.VIDEO_TRACK_MUTED,W.MINOR_EVENT],[D.IVS_PLAYER_REBUFFERING,W.MAJOR_EVENT],[D.IVS_PLAYER_AUDIO_BLOCKED,W.MAJOR_EVENT],[D.IVS_PLAYER_PLAYBACK_BLOCKED,W.MAJOR_EVENT],[D.IVS_PLAYER_ERROR,W.MAJOR_EVENT],[D.IVS_PLAYER_RECOVERABLE_ERROR,W.MAJOR_EVENT],[D.IVS_PLAYER_WORKER_ERROR,W.MAJOR_EVENT],[D.IVS_PLAYER_NETWORK_UNAVAILABLE,W.MAJOR_EVENT],[D.LIVESTREAM_LATENCY,W.MAJOR_EVENT],[D.IVS_PLAYER_ANALYTICS_EVENT,W.MINOR_EVENT],[D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,W.MINOR_EVENT],[D.IVS_PLAYER_QUALITY_CHANGED,W.MINOR_EVENT],[D.IVS_PLAYER_INITIALIZED,W.MINOR_EVENT],[D.EXPECTED_VIDEO_RESOLUTION,W.MINOR_EVENT],[D.EXPECTED_SCREENSHARE_RESOLUTION,W.MINOR_EVENT]]);class oT{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class cT extends ct{constructor({logger:e,peerId:r,apiHostnames:i,authToken:n}){super();p(this,"logger");p(this,"peerId");p(this,"eventStore");p(this,"apiEndpoint");p(this,"authToken");this.logger=e,this.peerId=r,this.authToken=n,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new oT}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,n=setTimeout(()=>i.abort(),3e3);try{return await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.authToken}`},body:JSON.stringify(r),signal:i.signal}),!0}catch(o){return this.logger.error("callStats::sendEventsChunkToServer::catch",{peerId:this.peerId,endpoint:this.apiEndpoint,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),!1}finally{clearTimeout(n)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),aT.get(e.event)===W.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();if((r=e==null?void 0:e.entries)!=null&&r.length){const i=await this.sendEventsChunkToServer(e);return i||e.entries.forEach(n=>{this.eventStore.add(n)}),i}return!1}}var xp;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(xp||(xp={}));const Up={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Jt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Jt||(Jt={}));var $p;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})($p||($p={}));function kr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function td({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function sd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Bp=240,Fp=720,Hp=8,qp=3,rd=10,id=.02,nd=.03;function Hs({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:i}){return s==null?t:e===r?i==="UP"?s<=e?t:0:s>=r?t:0:i==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:i==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function jp({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const n=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((n+Number.EPSILON)*100)/100}function Gp({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Wp({packetsLost:s,packetsSent:t,jitter:e}){const i=Hs({stat:Gp({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:rd,rangeRankingDirection:"UP"}),o=Hs({stat:e,weight:.3,rangeMin:id,rangeMax:nd,rangeRankingDirection:"UP"});return i+o}function dT({frameWidth:s,isScreenShare:t}){return s<(t?Fp:Bp)}function lT({framesPerSecond:s,isScreenShare:t}){return s<(t?qp:Hp)}function uT({framesEncoded:s}){return s===0}function Jp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Hs({stat:Gp({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:rd,rangeRankingDirection:"UP"}),d=Hs({stat:i,weight:1,rangeMin:id,rangeMax:nd,rangeRankingDirection:"UP"}),l=dT({frameWidth:s,isScreenShare:n}),u=lT({framesPerSecond:t,isScreenShare:n}),h=uT({framesEncoded:o,isScreenShare:n});return jp({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function Kp({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function zp({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Hs({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Hs({stat:Kp({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:rd,rangeRankingDirection:"UP"}),l=Hs({stat:r,weight:.3,rangeMin:id,rangeMax:nd,rangeRankingDirection:"UP"});return n+c+l}function hT({framesDecoded:s}){return s===0}function pT({framesPerSecond:s,isScreenShare:t}){return s<(t?qp:Hp)}function mT({frameWidth:s,isScreenShare:t}){return s<(t?Fp:Bp)}function Yp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Hs({stat:Kp({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:rd,rangeRankingDirection:"UP"}),d=Hs({stat:i,weight:1,rangeMin:id,rangeMax:nd,rangeRankingDirection:"UP"}),l=mT({frameWidth:s,isScreenShare:n}),u=pT({framesPerSecond:t,isScreenShare:n}),h=hT({framesDecoded:o,isScreenShare:n});return jp({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class qs{constructor(t){p(this,"pc1");p(this,"pc2");p(this,"constrainVideoBitrateKbps");p(this,"constrainOfferToRemoveVideoFec",!1);p(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=qs.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,i=t.substr(r).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=qs.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
6
+ */class Tp{static getParser(t,e=!1,r=null){if(typeof t!="string")throw new Error("UserAgent should be a string");return new vp(t,e,r)}static parse(t,e=null){return new vp(t,e).getResult()}static get BROWSER_MAP(){return Sp}static get ENGINE_MAP(){return _r}static get OS_MAP(){return ct}static get PLATFORMS_MAP(){return Q}}const Fa="chrome",yp="opera",Ep="firefox",bp="iexplorer",wp="safari",Pp="nwjs",_p="electron",kp="react-native",gu="unknown",Xc={Chrome:Fa,Chromium:Fa,Opera:yp,Firefox:Ep,"Internet Explorer":bp,Safari:wp};function Jv(){const{userAgent:s}=navigator,t={name:gu,version:void 0};if(s.match(/Chrome/)&&!s.match(/Edge/))if(s.match(/Edg(A?)/)){const e=s.match(/Chrome\/([\d.]+)/)[1];Number.parseInt(e,10)>72&&(t.name=Fa,t.version=e)}else t.name=Fa,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function Kv(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:_p,version:t}}return null}function zv(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Pp,version:t}}}function Yv(){const s=navigator.userAgent.match(/\b(react[ \t_-]*native)(?:\/(\S+))?/i);let t;if(s||navigator.product==="ReactNative")return s&&s.length>2&&(s[1],t=s[2]),t||(t="unknown"),{name:kp,version:t}}function Qv(s){let t;const e=[Yv,Kv,zv];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in Xc?{name:Xc[r],version:s.getBrowserVersion()}:(t=Jv(),t||{name:gu,version:void 0})}class Xv{constructor(){p(this,"_bowser");p(this,"_name");p(this,"_version");p(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(t){let e,r;if(this._bowser=Tp.getParser(navigator.userAgent),typeof t=="undefined"){const i=Qv(this._bowser);e=i.name,r=i.version}else t.name in Xc?(e=Xc[t.name],r=t.version):(e=gu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===Fa}isOpera(){return this._name===yp}isFirefox(){return this._name===Ep}isIExplorer(){return this._name===bp}isSafari(){return this._name===wp}isNWJS(){return this._name===Pp}isElectron(){return this._name===_p}isReactNative(){return this._name===kp||navigator.isReactNative===!0}getVersion(){return this._version}isMobile(){return this._bowser.getPlatformType()==="mobile"}_checkCondition(t){if(this._version)return this._bowser.satisfies(t)}isVersionGreaterThan(t){return this._checkCondition({[this._name]:`>${t}`})}isVersionLessThan(t){return this._checkCondition({[this._name]:`<${t}`})}isVersionEqualTo(t){return this._checkCondition({[this._name]:`~${t}`})}}class Zv extends Xv{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 t=new ReadableStream;try{return window.postMessage(t,"*",[t]),!0}catch(e){return!1}}supportsAudioRed(){return Boolean(window.RTCRtpSender&&window.RTCRtpSender.getCapabilities&&window.RTCRtpSender.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red")&&window.RTCRtpReceiver&&window.RTCRtpReceiver.getCapabilities&&window.RTCRtpReceiver.getCapabilities("audio").codecs.some(t=>t.mimeType==="audio/red"))}supportsSdpSemantics(){return this.isChromiumBased()}_getChromiumBasedVersion(){if(this.isChromiumBased()){if(this.isNWJS())return Number.parseInt(process.versions.chromium,10);const t=navigator.userAgent;if(t.match(/Chrome/))return Number.parseInt(t.match(/Chrome\/([\d.]+)/)[1],10)}return-1}isIOSMobile(){return this.isMobile&&this._bowser.getOSName()==="iOS"}}const Te=new Zv;var dt={},eT={get exports(){return dt},set exports(s){dt=s}},Tn=typeof Reflect=="object"?Reflect:null,Cp=Tn&&typeof Tn.apply=="function"?Tn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Zc;Tn&&typeof Tn.ownKeys=="function"?Zc=Tn.ownKeys:Object.getOwnPropertySymbols?Zc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Zc=function(t){return Object.getOwnPropertyNames(t)};function tT(s){console&&console.warn&&console.warn(s)}var Rp=Number.isNaN||function(t){return t!==t};function ce(){ce.init.call(this)}eT.exports=ce,dt.once=nT,ce.EventEmitter=ce,ce.prototype._events=void 0,ce.prototype._eventsCount=0,ce.prototype._maxListeners=void 0;var Ip=10;function ed(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ce,"defaultMaxListeners",{enumerable:!0,get:function(){return Ip},set:function(s){if(typeof s!="number"||s<0||Rp(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Ip=s}}),ce.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},ce.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Rp(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 Ap(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return Ap(this)},ce.prototype.emit=function(t){for(var e=[],r=1;r<arguments.length;r++)e.push(arguments[r]);var i=t==="error",n=this._events;if(n!==void 0)i=i&&n.error===void 0;else if(!i)return!1;if(i){var o;if(e.length>0&&(o=e[0]),o instanceof Error)throw o;var c=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw c.context=o,c}var d=n[t];if(d===void 0)return!1;if(typeof d=="function")Cp(d,this,e);else for(var l=d.length,u=Vp(d,l),r=0;r<l;++r)Cp(u[r],this,e);return!0};function Mp(s,t,e,r){var i,n,o;if(ed(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=Ap(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,tT(c)}return s}ce.prototype.addListener=function(t,e){return Mp(this,t,e,!1)},ce.prototype.on=ce.prototype.addListener,ce.prototype.prependListener=function(t,e){return Mp(this,t,e,!0)};function sT(){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 Op(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=sT.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(t,e){return ed(e),this.on(t,Op(this,t,e)),this},ce.prototype.prependOnceListener=function(t,e){return ed(e),this.prependListener(t,Op(this,t,e)),this},ce.prototype.removeListener=function(t,e){var r,i,n,o,c;if(ed(e),i=this._events,i===void 0)return this;if(r=i[t],r===void 0)return this;if(r===e||r.listener===e)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,r.listener||e));else if(typeof r!="function"){for(n=-1,o=r.length-1;o>=0;o--)if(r[o]===e||r[o].listener===e){c=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():rT(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},ce.prototype.off=ce.prototype.removeListener,ce.prototype.removeAllListeners=function(t){var e,r,i;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 n=Object.keys(r),o;for(i=0;i<n.length;++i)o=n[i],o!=="removeListener"&&this.removeAllListeners(o);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(i=e.length-1;i>=0;i--)this.removeListener(t,e[i]);return this};function Dp(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?iT(i):Vp(i,i.length)}ce.prototype.listeners=function(t){return Dp(this,t,!0)},ce.prototype.rawListeners=function(t){return Dp(this,t,!1)},ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Np.call(s,t)},ce.prototype.listenerCount=Np;function Np(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ce.prototype.eventNames=function(){return this._eventsCount>0?Zc(this._events):[]};function Vp(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function rT(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function iT(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function nT(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Lp(s,t,n,{once:!0}),t!=="error"&&aT(s,i,{once:!0})})}function aT(s,t,e){typeof s.on=="function"&&Lp(s,"error",t,e)}function Lp(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}var W;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(W||(W={}));var N;(function(s){s.PRECALL_TEST_BEGIN="precall_begin",s.PRECALL_TEST_COMPLETE="precall_end",s.CALL_JOIN_BEGIN="call_join",s.NET_QUALITY_TEST_BEGIN="net_quality_test_begin",s.NET_QUALITY_TEST_END="net_quality_test_end",s.WEBSOCKET_CONNECTED="websocket_connected",s.TRANSPORT_CONNECTED="transport_connected",s.AUDIO_ON="audio_on",s.AUDIO_OFF="audio_off",s.VIDEO_ON="video_on",s.VIDEO_OFF="video_off",s.PARTICIPANT_ROLE="participant_role",s.PING_STAT="ping_stat",s.DISCONNECT="disconnect",s.RECONNECT_ATTEMPT="reconnect_attempt",s.SCREENSHARE_START_REQUESTED="screenshare_start_requested",s.SCREENSHARE_STARTED="screenshare_started",s.SCREENSHARE_STOPPED="screenshare_stopped",s.TAB_CHANGE="tab_change",s.BROWSER_BACKGROUNDED="browser_backgrounded",s.BROWSER_FOREGROUNDED="browser_foregrounded",s.DOMINANT_SPEAKER="dominant_speaker",s.AUDIO_DEVICES_UPDATES="audio_devices_updates",s.VIDEO_DEVICES_UPDATES="video_devices_updates",s.SPEAKER_DEVICES_UPDATES="speaker_devices_updates",s.SELECTED_MICROHPONE_UPDATE="selected_microphone_update",s.SELECTED_CAMERA_UPDATE="selected_camera_update",s.SELECTED_SPEAKER_UPDATE="selected_speaker_update",s.EXPECTED_VIDEO_RESOLUTION="expected_video_resolution",s.EXPECTED_SCREENSHARE_RESOLUTION="expected_screenshare_resolution",s.MEDIA_PERMISSION="media_permission",s.LEGACY_SWITCH="legacy_switch",s.AUDIO_PLAY_FAILED="audio_play_failed",s.VIDEO_PLAY_FAILED="video_play_failed",s.AUDIO_TRACK_MUTED="audio_track_muted",s.VIDEO_TRACK_MUTED="video_track_muted",s.IVS_PLAYER_REBUFFERING="ivs_player_rebuffering",s.IVS_PLAYER_AUDIO_BLOCKED="ivs_player_audio_blocked",s.IVS_PLAYER_PLAYBACK_BLOCKED="ivs_player_playback_blocked",s.IVS_PLAYER_ERROR="ivs_player_error",s.IVS_PLAYER_RECOVERABLE_ERROR="ivs_player_recoverable_error",s.IVS_PLAYER_WORKER_ERROR="ivs_player_worker_error",s.IVS_PLAYER_NETWORK_UNAVAILABLE="ivs_player_network_unavailable",s.LIVESTREAM_LATENCY="livestream_latency",s.IVS_PLAYER_ANALYTICS_EVENT="ivs_player_analytics_event",s.IVS_PLAYER_PLAYBACK_RATE_CHANGED="ivs_player_playback_rate_changed",s.IVS_PLAYER_QUALITY_CHANGED="ivs_player_quality_changed",s.IVS_PLAYER_INITIALIZED="ivs_player_initialized"})(N||(N={}));const oT=new Map([[N.PRECALL_TEST_BEGIN,W.MINOR_EVENT],[N.PRECALL_TEST_COMPLETE,W.MINOR_EVENT],[N.CALL_JOIN_BEGIN,W.MAJOR_EVENT],[N.NET_QUALITY_TEST_BEGIN,W.MINOR_EVENT],[N.NET_QUALITY_TEST_END,W.MINOR_EVENT],[N.WEBSOCKET_CONNECTED,W.MINOR_EVENT],[N.TRANSPORT_CONNECTED,W.MAJOR_EVENT],[N.AUDIO_ON,W.MINOR_EVENT],[N.AUDIO_OFF,W.MINOR_EVENT],[N.VIDEO_ON,W.MINOR_EVENT],[N.VIDEO_OFF,W.MINOR_EVENT],[N.PARTICIPANT_ROLE,W.MINOR_EVENT],[N.PING_STAT,W.MAJOR_EVENT],[N.DISCONNECT,W.MAJOR_EVENT],[N.RECONNECT_ATTEMPT,W.MAJOR_EVENT],[N.SCREENSHARE_START_REQUESTED,W.MINOR_EVENT],[N.SCREENSHARE_STARTED,W.MINOR_EVENT],[N.SCREENSHARE_STOPPED,W.MINOR_EVENT],[N.TAB_CHANGE,W.MINOR_EVENT],[N.BROWSER_BACKGROUNDED,W.MINOR_EVENT],[N.BROWSER_FOREGROUNDED,W.MINOR_EVENT],[N.DOMINANT_SPEAKER,W.MINOR_EVENT],[N.AUDIO_DEVICES_UPDATES,W.MINOR_EVENT],[N.VIDEO_DEVICES_UPDATES,W.MINOR_EVENT],[N.SPEAKER_DEVICES_UPDATES,W.MINOR_EVENT],[N.SELECTED_MICROHPONE_UPDATE,W.MINOR_EVENT],[N.SELECTED_CAMERA_UPDATE,W.MINOR_EVENT],[N.SELECTED_SPEAKER_UPDATE,W.MINOR_EVENT],[N.MEDIA_PERMISSION,W.MINOR_EVENT],[N.LEGACY_SWITCH,W.MINOR_EVENT],[N.AUDIO_PLAY_FAILED,W.MINOR_EVENT],[N.VIDEO_PLAY_FAILED,W.MINOR_EVENT],[N.AUDIO_TRACK_MUTED,W.MINOR_EVENT],[N.VIDEO_TRACK_MUTED,W.MINOR_EVENT],[N.IVS_PLAYER_REBUFFERING,W.MAJOR_EVENT],[N.IVS_PLAYER_AUDIO_BLOCKED,W.MAJOR_EVENT],[N.IVS_PLAYER_PLAYBACK_BLOCKED,W.MAJOR_EVENT],[N.IVS_PLAYER_ERROR,W.MAJOR_EVENT],[N.IVS_PLAYER_RECOVERABLE_ERROR,W.MAJOR_EVENT],[N.IVS_PLAYER_WORKER_ERROR,W.MAJOR_EVENT],[N.IVS_PLAYER_NETWORK_UNAVAILABLE,W.MAJOR_EVENT],[N.LIVESTREAM_LATENCY,W.MAJOR_EVENT],[N.IVS_PLAYER_ANALYTICS_EVENT,W.MINOR_EVENT],[N.IVS_PLAYER_PLAYBACK_RATE_CHANGED,W.MINOR_EVENT],[N.IVS_PLAYER_QUALITY_CHANGED,W.MINOR_EVENT],[N.IVS_PLAYER_INITIALIZED,W.MINOR_EVENT],[N.EXPECTED_VIDEO_RESOLUTION,W.MINOR_EVENT],[N.EXPECTED_SCREENSHARE_RESOLUTION,W.MINOR_EVENT]]);class cT{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class dT extends dt{constructor({logger:e,peerId:r,apiHostnames:i,authToken:n}){super();p(this,"logger");p(this,"peerId");p(this,"eventStore");p(this,"apiEndpoint");p(this,"authToken");this.logger=e,this.peerId=r,this.authToken=n,this.apiEndpoint=`https://${i.daCollector}/api/v1/message`,this.eventStore=new cT}async sendEventsChunkToServer(e){const r={payload:e,peerId:this.peerId},i=new AbortController,n=setTimeout(()=>i.abort(),3e3);try{return await fetch(this.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.authToken}`},body:JSON.stringify(r),signal:i.signal}),!0}catch(o){return this.logger.error("callStats::sendEventsChunkToServer::catch",{peerId:this.peerId,endpoint:this.apiEndpoint,error:o instanceof Error?o.message:String(o),stack:o instanceof Error?o.stack:void 0}),!1}finally{clearTimeout(n)}}callEvent(e){e.timestamp=new Date,this.eventStore.add(e),this.emit(e.event,e.metaData),oT.get(e.event)===W.MAJOR_EVENT&&this.flush()}async flush(){var r;const e=this.eventStore.flush();if((r=e==null?void 0:e.entries)!=null&&r.length){const i=await this.sendEventsChunkToServer(e);return i||e.entries.forEach(n=>{this.eventStore.add(n)}),i}return!1}}var xp;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(xp||(xp={}));const Up={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Jt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Jt||(Jt={}));var $p;(function(s){s[s.INIT=0]="INIT",s[s.ACCEPTED=1]="ACCEPTED",s[s.DENIED=2]="DENIED",s[s.SYS_DENIED=3]="SYS_DENIED",s[s.FAILED=4]="FAILED",s[s.NOTFOUND=5]="NOTFOUND",s[s.NOT_APPLICABLE=6]="NOT_APPLICABLE"})($p||($p={}));function kr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function td({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function sd({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Bp=240,Fp=720,Hp=8,qp=3,rd=10,id=.02,nd=.03;function Hs({stat:s,weight:t,rangeMin:e,rangeMax:r,rangeRankingDirection:i}){return s==null?t:e===r?i==="UP"?s<=e?t:0:s>=r?t:0:i==="UP"?(1-Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e))*t:i==="DOWN"?Math.max(Math.min(r,Math.abs(s))-e,0)/(r-e)*t:t}function jp({isLowQualityVideo:s,isVideoStuck:t,isVideoLagging:e,jitterQuality:r,packetsLostQuality:i}){const n=.8*((s?.85:1)*(e?.7:1)*(t?.5:1))+.2*(r*i);return Math.round((n+Number.EPSILON)*100)/100}function Gp({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Wp({packetsLost:s,packetsSent:t,jitter:e}){const i=Hs({stat:Gp({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:rd,rangeRankingDirection:"UP"}),o=Hs({stat:e,weight:.3,rangeMin:id,rangeMax:nd,rangeRankingDirection:"UP"});return i+o}function lT({frameWidth:s,isScreenShare:t}){return s<(t?Fp:Bp)}function uT({framesPerSecond:s,isScreenShare:t}){return s<(t?qp:Hp)}function hT({framesEncoded:s}){return s===0}function Jp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Hs({stat:Gp({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:rd,rangeRankingDirection:"UP"}),d=Hs({stat:i,weight:1,rangeMin:id,rangeMax:nd,rangeRankingDirection:"UP"}),l=lT({frameWidth:s,isScreenShare:n}),u=uT({framesPerSecond:t,isScreenShare:n}),h=hT({framesEncoded:o,isScreenShare:n});return jp({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function Kp({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function zp({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Hs({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Hs({stat:Kp({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:rd,rangeRankingDirection:"UP"}),l=Hs({stat:r,weight:.3,rangeMin:id,rangeMax:nd,rangeRankingDirection:"UP"});return n+c+l}function pT({framesDecoded:s}){return s===0}function mT({framesPerSecond:s,isScreenShare:t}){return s<(t?qp:Hp)}function gT({frameWidth:s,isScreenShare:t}){return s<(t?Fp:Bp)}function Yp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Hs({stat:Kp({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:rd,rangeRankingDirection:"UP"}),d=Hs({stat:i,weight:1,rangeMin:id,rangeMax:nd,rangeRankingDirection:"UP"}),l=gT({frameWidth:s,isScreenShare:n}),u=mT({framesPerSecond:t,isScreenShare:n}),h=pT({framesDecoded:o,isScreenShare:n});return jp({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class qs{constructor(t){p(this,"pc1");p(this,"pc2");p(this,"constrainVideoBitrateKbps");p(this,"constrainOfferToRemoveVideoFec",!1);p(this,"iceCandidateFilter");const e=new RTCPeerConnection(t),r=new RTCPeerConnection(t);this.pc1=e,this.pc2=r,this.iceCandidateFilter=qs.noFilter,this.pc1.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc2)),this.pc2.addEventListener("icecandidate",this.onIceCandidate.bind(this,this.pc1))}static parseCandidate(t){const e="candidate:",r=t.indexOf(e)+e.length,i=t.substr(r).split(" ");return{type:i[7],protocol:i[2],address:i[4]}}static isNotHostCandidate(t){return t.type!=="host"}static isHost(t){return t.type==="host"}static isRelay(t){return t.type==="relay"}static isReflexive(t){return t.type==="srflx"}static noFilter(t){return!0}onIceCandidate(t,e){if(e.candidate){const r=qs.parseCandidate(e.candidate.candidate);this.iceCandidateFilter(r)&&t.addIceCandidate(e.candidate)}}setIceCandidateFilter(t){this.iceCandidateFilter=t}constrainVideoBitrate(t){this.constrainVideoBitrateKbps=t}disableVideoFec(){this.constrainOfferToRemoveVideoFec=!0}gotOffer(t){this.constrainOfferToRemoveVideoFec&&(t.sdp=t.sdp.replace(/(m=video 1 [^\r]+)(116 117)(\r\n)/g,`$1\r
7
7
  `),t.sdp=t.sdp.replace(/a=rtpmap:116 red\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:117 ulpfec\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=rtpmap:98 rtx\/90000\r\n/g,""),t.sdp=t.sdp.replace(/a=fmtp:98 apt=116\r\n/g,"")),this.pc1.setLocalDescription(t),this.pc2.setRemoteDescription(t),this.pc2.createAnswer().then(this.gotAnswer.bind(this),this.reportFatal.bind(this))}gotAnswer(t){this.constrainVideoBitrateKbps&&(t.sdp=t.sdp.replace(/a=mid:video\r\n/g,`a=mid:video\r
8
8
  b=AS:${this.constrainVideoBitrateKbps}\r
9
- `)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesSent>0&&(r=n)}),e.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesReceived>0&&(i=n)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const n=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:n,backendRTT:n}}catch(n){return}}close(){this.pc1.close(),this.pc2.close()}}class Qp extends ct{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new qs(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 gT=8,fT=1/1e3;class vT extends Qp{constructor(e){super(e);p(this,"senderChannel");p(this,"recieveChannel");p(this,"startTime");p(this,"lastBitrateMeasureTime");p(this,"sentPayloadBytes",0);p(this,"recievedPayloadBytes",0);p(this,"lastReceivedPayloadBytes",0);p(this,"stopSending",!1);p(this,"testProgress",0);p(this,"samplePacket","");p(this,"finalBitrateSum",0);p(this,"bitRateSampels",0);p(this,"maxNumberOfPacketsToSend",0);p(this,"bytesToKeepBuffered",0);p(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(qs.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 i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(n){}}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,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*gT/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const n=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(n*fT)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class gu extends Qp{constructor(e,r=qs.noFilter){super(e);p(this,"ch1");p(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class ST extends gu{constructor(t){super(t,qs.isHost)}}class TT extends gu{constructor(t){super(t,qs.isRelay)}}class yT extends gu{constructor(t){super(t,qs.isReflexive)}}class ET{constructor(){p(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,n,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(n=this.ipInformation)!=null&&n.ip&&(this.ipInformation.ip=kr(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=kr(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Xp=new ET,Zp=[{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 em(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class tm{constructor(){p(this,"transport");p(this,"candidatePair");p(this,"outboundVideoRtp",new Map);p(this,"inboundVideoRtp",new Map);p(this,"outboundAudioRtp",new Map);p(this,"inboundAudioRtp",new Map);p(this,"remoteInboundRtp",new Map);p(this,"producerStreamMap",new Map);p(this,"consumerStreamMap",new Map);p(this,"staleProducerStreamMap",!1);p(this,"staleConsumerStreamMap",!1)}}class sm extends ct{constructor(){super();p(this,"observer");p(this,"outboundProducerMap",new Map);p(this,"inboundConsumerMap",new Map);p(this,"consumerPeerIdMap",new Map);p(this,"pausedConsumerMap",new Map);p(this,"pausedProducerMap",new Map);p(this,"overallProducingTransportsStatsMap",{});p(this,"overallConsumingTransportsStatsMap",{});p(this,"overallConsumersStatsMap",{});p(this,"overallProducersStatsMap",{});p(this,"videoProducerToStatsMap",new Map);p(this,"audioProducerToStatsMap",new Map);p(this,"videoConsumerToStatsMap",new Map);p(this,"audioConsumerToStatsMap",new Map);p(this,"consumerIdsWithFreezedVideo",new Set);p(this,"consumerIdsWithFreezedAudio",new Set);p(this,"producerIdsWithFreezedVideo",new Set);p(this,"producerIdsWithFreezedAudio",new Set);p(this,"freezedProducingTransportIds",new Set);p(this,"freezedConsumingTransportIds",new Set);p(this,"screenShareProducers",new Set);p(this,"screenShareConsumers",new Set);p(this,"ipDetails");p(this,"callStatsInstance");this.observer=new ct}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var u;const n=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=n,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,u)=>l||u.audio||u.video||u.screen,!1);r.totalPacketsReceived===i.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=i.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))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return n}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return n}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),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(i=>{const n=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return n&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,n=void 0,o=void 0){var w,R,P,N,$,x,H,F,Z,je,jt,Ps,gn;const c=e,d=new tm,l=r.length?new Set(r):void 0,u=[],h=[],m=[],v=new Map,y=new Map;for(const A of c.values()){if(l){if(l.size===0)break;if(l.has(A.type))i&&l.delete(A.type);else continue}switch(A.type){case"local-candidate":{u.push(this.getIceCandidateStats(A));break}case"remote-candidate":{h.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:T}=A,{selected:_}=A,B=A,we={nominated:T!=null?T:_,currentRoundTripTime:B.currentRoundTripTime,totalRoundTripTime:B.totalRoundTripTime,bytesReceived:B.bytesReceived,bytesSent:B.bytesSent,availableOutgoingBitrate:B.availableOutgoingBitrate,availableIncomingBitrate:B.availableIncomingBitrate,lastPacketReceivedTimestamp:B.lastPacketReceivedTimestamp,lastPacketSentTimestamp:B.lastPacketSentTimestamp,localCandidateId:B.localCandidateId,remoteCandidateId:B.remoteCandidateId,bytesDiscardedOnSend:B.bytesDiscardedOnSend,packetsSent:B.packetsSent,packetsReceived:B.packetsReceived,packetsDiscardedOnSend:B.packetsDiscardedOnSend};m.push(we),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=we);break}case"transport":{const T=A;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const _={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=_,o){if(o.producing){const B=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,B,_)}if(o.consuming){const B=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,B,_)}}break}case"remote-inbound-rtp":{const T=A,_={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,_);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const T=A,_=n||this.outboundProducerMap.get(A.id),B=this.pausedProducerMap.get(_);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(_,{lastReportCalculated:!0})}this.overallProducersStatsMap[_]||(this.overallProducersStatsMap[_]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const we=this.overallProducersStatsMap[_];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const Ve=this.callStatsInstance.producers.get(_);if(((w=Ve==null?void 0:Ve.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(_)||d.producerStreamMap.set(_,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const L={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const I=T,Be={frameHeight:I.frameHeight,frameWidth:I.frameWidth,framesEncoded:I.framesEncoded,framesDropped:I.framesDropped,framesPerSecond:I.framesPerSecond,framesSent:I.framesSent,keyFramesEncoded:I.keyFramesEncoded,firCount:I.firCount,encoderImplementation:I.encoderImplementation,hugeFramesSent:I.hugeFramesSent,pliCount:I.pliCount,qpSum:I.qpSum,qualityLimitationDurations:I.qualityLimitationDurations,qualityLimitationReason:I.qualityLimitationReason,qualityLimitationResolutionChanges:I.qualityLimitationResolutionChanges,totalEncodeTime:I.targetBitrate,totalPacketSendDelay:I.totalPacketSendDelay,retransmittedBytesSent:I.retransmittedBytesSent,retransmittedPacketsSent:I.retransmittedPacketsSent,scalabilityMode:I.scalabilityMode,powerEfficientEncoder:I.powerEfficientEncoder,...L};d.outboundVideoRtp.set(A.id,Be),d.producerStreamMap.get(_).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(_,we,Be)}else if(T.mediaType==="audio"||T.kind==="audio"){const I=T,Be={retransmittedBytesSent:I.retransmittedBytesSent,retransmittedPacketsSent:I.retransmittedPacketsSent,...L};d.outboundAudioRtp.set(A.id,Be),d.producerStreamMap.get(_).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(_,we,Be)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const T=A,_=n||this.inboundConsumerMap.get(A.id),B=this.pausedConsumerMap.get(_);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(_,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[_]||(this.overallConsumersStatsMap[_]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const we=this.overallConsumersStatsMap[_];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(_)||d.consumerStreamMap.set(_,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Ve={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const L=T,I={frameHeight:L.frameHeight,frameWidth:L.frameWidth,framesDecoded:L.framesDecoded,framesDropped:L.framesDropped,framesPerSecond:L.framesPerSecond,framesReceived:L.framesReceived,keyFramesDecoded:L.keyFramesDecoded,firCount:L.firCount,decoderImplementation:L.decoderImplementation,pliCount:L.pliCount,totalProcessingDelay:L.totalProcessingDelay,qpSum:L.qpSum||0,totalAssemblyTime:L.totalAssemblyTime||0,totalDecodeTime:L.totalDecodeTime||0,totalFreezesDuration:L.totalFreezesDuration||0,totalInterFrameDelay:L.totalInterFrameDelay||0,totalPausesDuration:L.totalPausesDuration||0,totalSquaredInterFrameDelay:L.totalSquaredInterFrameDelay||0,freezeCount:L.freezeCount||0,pauseCount:L.pauseCount||0,powerEfficientDecoder:L.powerEfficientDecoder,...Ve};I.score=Yp({frameWidth:I.frameWidth||0,framesDecoded:(I.framesDecoded||0)-(((R=this.videoConsumerToStatsMap.get(_))==null?void 0:R.framesDecoded)||0),framesPerSecond:I.framesPerSecond||0,packetsLost:(I.packetsLost||0)-(((P=this.videoConsumerToStatsMap.get(_))==null?void 0:P.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(_))==null?void 0:N.packetsReceived)||0),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(_)}),y.set(_,{score:+(I.score*10).toFixed(),frameWidth:I.frameWidth||0,frameHeight:I.frameHeight||0,framesPerSecond:I.framesPerSecond||0,packetsLostPercentage:sd({packetsLost:(I.packetsLost||0)-((($=this.videoConsumerToStatsMap.get(_))==null?void 0:$.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(_))==null?void 0:x.packetsReceived)||0)}),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((I.bytesReceived||0)-(((H=this.videoConsumerToStatsMap.get(_))==null?void 0:H.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(_,I),d.inboundVideoRtp.set(A.id,I),d.consumerStreamMap.get(_).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(_,we,I)}else if(T.mediaType==="audio"||T.kind==="audio"){const L=T,I={audioLevel:L.audioLevel,concealedSamples:L.concealedSamples,concealmentEvents:L.concealmentEvents,totalAudioEnergy:L.totalAudioEnergy,totalSamplesDuration:L.totalSamplesDuration,totalSamplesReceived:L.totalSamplesReceived,fecPacketsDiscarded:L.fecPacketsDiscarded||0,fecPacketsReceived:L.fecPacketsReceived||0,insertedSamplesForDeceleration:L.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:L.removedSamplesForAcceleration||0,silentConcealedSamples:L.silentConcealedSamples||0,playoutId:L.playoutId,...Ve};I.score=zp({concealmentEvents:(I.concealmentEvents||0)-(((F=this.audioConsumerToStatsMap.get(_))==null?void 0:F.concealmentEvents)||0),packetsLost:(I.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(_))==null?void 0:Z.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((je=this.audioConsumerToStatsMap.get(_))==null?void 0:je.packetsReceived)||0),jitter:I.jitter||0}),y.set(_,{score:+(I.score*10).toFixed(),packetsLostPercentage:sd({packetsLost:(I.packetsLost||0)-(((jt=this.audioConsumerToStatsMap.get(_))==null?void 0:jt.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((Ps=this.audioConsumerToStatsMap.get(_))==null?void 0:Ps.packetsReceived)||0)}),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((I.bytesReceived||0)-(((gn=this.audioConsumerToStatsMap.get(_))==null?void 0:gn.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(_,I),d.inboundAudioRtp.set(A.id,I),d.consumerStreamMap.get(_).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(_,we,I)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((A,T)=>{var _,B,we,Ve,L,I,Be,Ac,Mc,Oc,Dc,Nc,Vc,Lc,xc,Uc,$c,Bc,Fc,Hc,qc,jc,Gc;if(A.outboundVideoRtpId.length>0){const me=[];A.outboundVideoRtpId.forEach(Yh=>{me.push(d.outboundVideoRtp.get(Yh))});const te=this.getWorkingSimulcastVideoStats(me);te.score=Jp({frameWidth:te.frameWidth||0,framesPerSecond:te.framesPerSecond||0,jitter:((_=te.remoteData)==null?void 0:_.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(te.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(T))==null?void 0:B.packetsSent)||0),packetsLost:(((we=te.remoteData)==null?void 0:we.packetsLost)||0)-(((L=(Ve=this.videoProducerToStatsMap.get(T))==null?void 0:Ve.remoteData)==null?void 0:L.packetsLost)||0),framesEncoded:(te.framesEncoded||0)-(((I=this.videoProducerToStatsMap.get(T))==null?void 0:I.framesEncoded)||0)}),v.set(T,{score:+(te.score*10).toFixed(),frameWidth:te.frameWidth||0,frameHeight:te.frameHeight||0,framesPerSecond:te.framesPerSecond||0,jitter:((Be=te.remoteData)==null?void 0:Be.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:td({packetsSent:(te.packetsSent||0)-(((Ac=this.videoProducerToStatsMap.get(T))==null?void 0:Ac.packetsSent)||0),packetsLost:(((Mc=te.remoteData)==null?void 0:Mc.packetsLost)||0)-(((Dc=(Oc=this.videoProducerToStatsMap.get(T))==null?void 0:Oc.remoteData)==null?void 0:Dc.packetsLost)||0)}),bitrate:((te.bytesSent||0)-(((Nc=this.videoProducerToStatsMap.get(T))==null?void 0:Nc.bytesSent)||0))*8/7,cpuLimitations:te.qualityLimitationReason==="cpu",bandwidthLimitations:te.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,te)}else if(A.outboundAudioRtpId.length>0){const me=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);me.score=Wp({packetsSent:(me.packetsSent||0)-(((Vc=this.audioProducerToStatsMap.get(T))==null?void 0:Vc.packetsSent)||0),packetsLost:(((Lc=me.remoteData)==null?void 0:Lc.packetsLost)||0)-(((Uc=(xc=this.audioProducerToStatsMap.get(T))==null?void 0:xc.remoteData)==null?void 0:Uc.packetsLost)||0),jitter:(($c=me.remoteData)==null?void 0:$c.jitter)||0}),v.set(T,{score:+(me.score*10).toFixed(),bitrate:((me.bytesSent||0)-(((Bc=this.audioProducerToStatsMap.get(T))==null?void 0:Bc.bytesSent)||0))*8/7,packetsLostPercentage:td({packetsSent:(me.packetsSent||0)-(((Fc=this.audioProducerToStatsMap.get(T))==null?void 0:Fc.packetsSent)||0),packetsLost:(((Hc=me.remoteData)==null?void 0:Hc.packetsLost)||0)-(((jc=(qc=this.audioProducerToStatsMap.get(T))==null?void 0:qc.remoteData)==null?void 0:jc.packetsLost)||0)}),jitter:((Gc=me.remoteData)==null?void 0:Gc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,me)}}),m.forEach(A=>{const T=u.find(B=>B.id===A.localCandidateId?(A.localCandidateId=B.id,B):null),_=h.find(B=>B.id===A.remoteCandidateId?(A.remoteCandidateId=B.id,B):null);T&&(A.localCandidateType=T.type,A.localCandidateAddress=kr(T.address),A.localCandidatePort=T.port,A.localCandidateProtocol=T.protocol,A.localCandidateUrl=T.url,A.localCandidateNetworkType=T.networkType,A.localCandidateRelatedAddress=kr(T.relatedAddress),A.localCandidateRelatedPort=T.relatedPort),_&&(A.remoteCandidateType=_.type,A.remoteCandidateAddress=kr(_.address),A.remoteCandidatePort=_.port,A.remoteCandidateProtocol=_.protocol,A.remoteCandidateUrl=_.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=m),d.transport&&!d.transport.roundTripTime){let A=0,T=0;d.remoteInboundRtp.forEach((_,B)=>{_.roundTripTime&&_.roundTripTime>A&&(A=_.roundTripTime,T=_.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(A){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(A){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const n=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=n,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),h=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,consumerReport:h}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{var o,c;r.push({producerId:n,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(n))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(n);r.push({consumerId:n,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||Zp},i=new Promise((u,h)=>{try{const m=new ST(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){h(m)}}),n=new Promise((u,h)=>{try{const m=new TT(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){h(m)}}),o=new Promise((u,h)=>{try{const m=new yT(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){h(m)}}),[c,d,l]=await Promise.all([i,n,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((n,o)=>{try{const c={iceServers:e||Zp},d=new vT(c);d.addListener("done",n),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Xp.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?em(l==null?void 0:l.loc):void 0}}const[i,n,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?em(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}}}class bT extends sm{}class rm extends sm{constructor(){super(...arguments);p(this,"producerMap",new Map);p(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...n.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(n,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),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=[],i=!1,n=void 0,o=void 0){var w,R,P,N,$,x,H,F,Z,je,jt,Ps,gn;const c=e,d=new tm,l=r.length?new Set(r):void 0,u=[],h=[],m=[],v=new Map,y=new Map;for(const A of c.values()){if(l){if(l.size===0)break;if(l.has(A.type))i&&l.delete(A.type);else continue}switch(A.type){case"local-candidate":{u.push(this.getIceCandidateStats(A));break}case"remote-candidate":{h.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:T}=A,{selected:_}=A,B=A,we={nominated:T!=null?T:_,currentRoundTripTime:B.currentRoundTripTime,totalRoundTripTime:B.totalRoundTripTime,bytesReceived:B.bytesReceived,bytesSent:B.bytesSent,availableOutgoingBitrate:B.availableOutgoingBitrate,availableIncomingBitrate:B.availableIncomingBitrate,lastPacketReceivedTimestamp:B.lastPacketReceivedTimestamp,lastPacketSentTimestamp:B.lastPacketSentTimestamp,localCandidateId:B.localCandidateId,remoteCandidateId:B.remoteCandidateId,bytesDiscardedOnSend:B.bytesDiscardedOnSend,packetsSent:B.packetsSent,packetsReceived:B.packetsReceived,packetsDiscardedOnSend:B.packetsDiscardedOnSend};m.push(we),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=we);break}case"transport":{const T=A;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const _={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=_,o){if(o.producing){const B=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,B,_)}if(o.consuming){const B=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,B,_)}}break}case"remote-inbound-rtp":{const T=A,_={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,_);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const T=A,_=n||this.outboundProducerMap.get(A.id),B=this.pausedProducerMap.get(_);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(_,{lastReportCalculated:!0})}this.overallProducersStatsMap[_]||(this.overallProducersStatsMap[_]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const we=this.overallProducersStatsMap[_];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const Ve=this.callStatsInstance.producers.get(_);if(((w=Ve==null?void 0:Ve.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(_)||d.producerStreamMap.set(_,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const L={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const I=T,Be={frameHeight:I.frameHeight,frameWidth:I.frameWidth,framesEncoded:I.framesEncoded,framesDropped:I.framesDropped?I.framesDropped:I.droppedFrames,framesPerSecond:I.framesPerSecond?I.framesPerSecond:I.framerateMean,framesSent:I.framesSent,keyFramesEncoded:I.keyFramesEncoded,firCount:I.firCount,encoderImplementation:I.encoderImplementation,hugeFramesSent:I.hugeFramesSent,pliCount:I.pliCount,qpSum:I.qpSum,qualityLimitationReason:I.qualityLimitationReason,qualityLimitationDurations:I.qualityLimitationDurations,qualityLimitationResolutionChanges:I.qualityLimitationResolutionChanges,totalEncodeTime:I.totalEncodeTime,totalPacketSendDelay:I.totalEncodeTime,retransmittedBytesSent:I.retransmittedBytesSent,retransmittedPacketsSent:I.retransmittedPacketsSent,scalabilityMode:I.scalabilityMode,powerEfficientEncoder:I.powerEfficientEncoder,...L};d.outboundVideoRtp.set(A.id,Be),d.producerStreamMap.get(_).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(_,we,Be)}else if(T.mediaType==="audio"||T.kind==="audio"){const I=T,Be={retransmittedBytesSent:I.retransmittedBytesSent,retransmittedPacketsSent:I.retransmittedPacketsSent,...L};d.outboundAudioRtp.set(A.id,Be),d.producerStreamMap.get(_).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(_,we,Be)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const T=A,_=n||this.inboundConsumerMap.get(A.id),B=this.pausedConsumerMap.get(_);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(_,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[_]||(this.overallConsumersStatsMap[_]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const we=this.overallConsumersStatsMap[_];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(_)||d.consumerStreamMap.set(_,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Ve={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const L=T,I={frameHeight:L.frameHeight,frameWidth:L.frameWidth,framesDecoded:L.framesDecoded,framesDropped:L.framesDropped?L.framesDropped:L.droppedFrames,framesPerSecond:L.framesPerSecond?L.framesPerSecond:L.framerateMean,framesReceived:L.framesReceived,keyFramesDecoded:L.keyFramesDecoded,firCount:L.firCount,decoderImplementation:L.decoderImplementation,pliCount:L.pliCount,totalProcessingDelay:L.totalProcessingDelay,qpSum:L.qpSum||0,totalAssemblyTime:L.totalAssemblyTime||0,totalDecodeTime:L.totalDecodeTime||0,totalFreezesDuration:L.totalFreezesDuration||0,totalInterFrameDelay:L.totalInterFrameDelay||0,totalPausesDuration:L.totalPausesDuration||0,totalSquaredInterFrameDelay:L.totalSquaredInterFrameDelay||0,freezeCount:L.freezeCount||0,pauseCount:L.pauseCount||0,powerEfficientDecoder:L.powerEfficientDecoder,...Ve};I.score=Yp({frameWidth:I.frameWidth||0,framesDecoded:(I.framesDecoded||0)-(((R=this.videoConsumerToStatsMap.get(_))==null?void 0:R.framesDecoded)||0),framesPerSecond:I.framesPerSecond||0,packetsLost:(I.packetsLost||0)-(((P=this.videoConsumerToStatsMap.get(_))==null?void 0:P.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(_))==null?void 0:N.packetsReceived)||0),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(_)}),y.set(_,{score:+(I.score*10).toFixed(),frameWidth:I.frameWidth||0,frameHeight:I.frameHeight||0,framesPerSecond:I.framesPerSecond||0,packetsLostPercentage:sd({packetsLost:(I.packetsLost||0)-((($=this.videoConsumerToStatsMap.get(_))==null?void 0:$.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((x=this.videoConsumerToStatsMap.get(_))==null?void 0:x.packetsReceived)||0)}),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((I.bytesReceived||0)-(((H=this.videoConsumerToStatsMap.get(_))==null?void 0:H.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(_,I),d.inboundVideoRtp.set(A.id,I),d.consumerStreamMap.get(_).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(_,we,I)}else if(T.mediaType==="audio"||T.kind==="audio"){const L=T,I={audioLevel:L.audioLevel,concealedSamples:L.concealedSamples,concealmentEvents:L.concealmentEvents,totalAudioEnergy:L.totalAudioEnergy,totalSamplesDuration:L.totalSamplesDuration,totalSamplesReceived:L.totalSamplesReceived,fecPacketsDiscarded:L.fecPacketsDiscarded||0,fecPacketsReceived:L.fecPacketsReceived||0,insertedSamplesForDeceleration:L.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:L.removedSamplesForAcceleration||0,silentConcealedSamples:L.silentConcealedSamples||0,playoutId:L.playoutId,...Ve};I.score=zp({concealmentEvents:(I.concealmentEvents||0)-(((F=this.audioConsumerToStatsMap.get(_))==null?void 0:F.concealmentEvents)||0),packetsLost:(I.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(_))==null?void 0:Z.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((je=this.audioConsumerToStatsMap.get(_))==null?void 0:je.packetsReceived)||0),jitter:I.jitter||0}),y.set(_,{score:+(I.score*10).toFixed(),packetsLostPercentage:sd({packetsLost:(I.packetsLost||0)-(((jt=this.audioConsumerToStatsMap.get(_))==null?void 0:jt.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((Ps=this.audioConsumerToStatsMap.get(_))==null?void 0:Ps.packetsReceived)||0)}),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(_),bitrate:((I.bytesReceived||0)-(((gn=this.audioConsumerToStatsMap.get(_))==null?void 0:gn.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(_,I),d.inboundAudioRtp.set(A.id,I),d.consumerStreamMap.get(_).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(_,we,I)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((A,T)=>{var _,B,we,Ve,L,I,Be,Ac,Mc,Oc,Dc,Nc,Vc,Lc,xc,Uc,$c,Bc,Fc,Hc,qc,jc,Gc;if(A.outboundVideoRtpId.length>0){const me=[];A.outboundVideoRtpId.forEach(Yh=>{me.push(d.outboundVideoRtp.get(Yh))});const te=this.getWorkingSimulcastVideoStats(me);te.score=Jp({frameWidth:te.frameWidth||0,framesPerSecond:te.framesPerSecond||0,jitter:((_=te.remoteData)==null?void 0:_.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(te.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(T))==null?void 0:B.packetsSent)||0),packetsLost:(((we=te.remoteData)==null?void 0:we.packetsLost)||0)-(((L=(Ve=this.videoProducerToStatsMap.get(T))==null?void 0:Ve.remoteData)==null?void 0:L.packetsLost)||0),framesEncoded:(te.framesEncoded||0)-(((I=this.videoProducerToStatsMap.get(T))==null?void 0:I.framesEncoded)||0)}),v.set(T,{score:+(te.score*10).toFixed(),frameWidth:te.frameWidth||0,frameHeight:te.frameHeight||0,framesPerSecond:te.framesPerSecond||0,jitter:((Be=te.remoteData)==null?void 0:Be.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:td({packetsSent:(te.packetsSent||0)-(((Ac=this.videoProducerToStatsMap.get(T))==null?void 0:Ac.packetsSent)||0),packetsLost:(((Mc=te.remoteData)==null?void 0:Mc.packetsLost)||0)-(((Dc=(Oc=this.videoProducerToStatsMap.get(T))==null?void 0:Oc.remoteData)==null?void 0:Dc.packetsLost)||0)}),bitrate:((te.bytesSent||0)-(((Nc=this.videoProducerToStatsMap.get(T))==null?void 0:Nc.bytesSent)||0))*8/7,cpuLimitations:te.qualityLimitationReason==="cpu",bandwidthLimitations:te.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,te)}else if(A.outboundAudioRtpId.length>0){const me=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);me.score=Wp({packetsSent:(me.packetsSent||0)-(((Vc=this.audioProducerToStatsMap.get(T))==null?void 0:Vc.packetsSent)||0),packetsLost:(((Lc=me.remoteData)==null?void 0:Lc.packetsLost)||0)-(((Uc=(xc=this.audioProducerToStatsMap.get(T))==null?void 0:xc.remoteData)==null?void 0:Uc.packetsLost)||0),jitter:(($c=me.remoteData)==null?void 0:$c.jitter)||0}),v.set(T,{score:+(me.score*10).toFixed(),bitrate:((me.bytesSent||0)-(((Bc=this.audioProducerToStatsMap.get(T))==null?void 0:Bc.bytesSent)||0))*8/7,packetsLostPercentage:td({packetsSent:(me.packetsSent||0)-(((Fc=this.audioProducerToStatsMap.get(T))==null?void 0:Fc.packetsSent)||0),packetsLost:(((Hc=me.remoteData)==null?void 0:Hc.packetsLost)||0)-(((jc=(qc=this.audioProducerToStatsMap.get(T))==null?void 0:qc.remoteData)==null?void 0:jc.packetsLost)||0)}),jitter:((Gc=me.remoteData)==null?void 0:Gc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,me)}}),m.forEach(A=>{const T=u.find(B=>B.id===A.localCandidateId?(A.localCandidateId=B.id,B):null),_=h.find(B=>B.id===A.remoteCandidateId?(A.remoteCandidateId=B.id,B):null);T&&(A.localCandidateType=T.type,A.localCandidateAddress=kr(T.address),A.localCandidatePort=T.port,A.localCandidateProtocol=T.protocol,A.localCandidateUrl=T.url,A.localCandidateNetworkType=T.networkType,A.localCandidateRelatedAddress=kr(T.relatedAddress),A.localCandidateRelatedPort=T.relatedPort),_&&(A.remoteCandidateType=_.type,A.remoteCandidateAddress=kr(_.address),A.remoteCandidatePort=_.port,A.remoteCandidateProtocol=_.protocol,A.remoteCandidateUrl=_.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=m),d.transport&&!d.transport.roundTripTime){let A=0,T=0;d.remoteInboundRtp.forEach((_,B)=>{_.roundTripTime&&_.roundTripTime>A&&(A=_.roundTripTime,T=_.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(A){}if(v.size>0)try{this.observer.emit("producer_score",v)}catch(A){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{const o=this.producerMap.get(n),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const h=e.outboundVideoRtp.get(u);return h.frameHeight||(h.frameHeight=c.height,h.frameWidth=c.width,h.framesPerSecond=c.frameRate),h}),l={producerId:n,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let n;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const m=this.consumerMap.get(i).track.getSettings(),v=e.inboundVideoRtp.get(u);return v.frameHeight||(v.frameHeight=m.height,v.frameWidth=m.width,v.framesPerSecond=m.frameRate),v});n={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return n}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,n))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class wT extends rm{}function ad(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function im(s,t,e){const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{ad(this,t,e,o)}):n}catch(n){ad(this,t,e,n)}return null},s}const z=(s,t)=>(e,r,i)=>{const n=i.value;return i.value=function(...o){try{const c=n.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{ad(this,s,t,d)}):c}catch(c){ad(this,s,t,c)}return null},i},PT=(s,t)=>(e,r,i)=>{if(i)return im(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);o.value instanceof Function&&Object.defineProperty(e.prototype,n,im(o,s,t))}};var J=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(n=(i<3?o(n):i>3?o(t,e,n):o(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n};const K=console;let j=class extends ct{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Up.PROD,n,o,c,d,l){super();p(this,"observer");p(this,"eventHandler");p(this,"measurements");p(this,"producingTransport");p(this,"consumingTransport");p(this,"producers",new Map);p(this,"consumers",new Map);p(this,"iceServers");p(this,"connectionInfoPromise");p(this,"pingStatsTimeout");p(this,"logger");p(this,"env");p(this,"apiHostnames");p(this,"peerId");p(this,"consumerSharedMediaStatesMap",new Map);p(this,"currentUserMediaStates",{});if(!l)throw Error("authToken is missing but required to initialize CallStats!");switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new cT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new bT;break;case"Gecko":this.measurements=new rm;break;case"WebKit":this.measurements=new wT;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new ct,this.measurements.observer.on("consumer_score",u=>{o.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{o.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(n=>{this.registerProducer(n)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(n=>{this.registerConsumer(n)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:D.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:D.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?D.SCREENSHARE_STARTED:D.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:D.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:D.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===Jt.AUDIO&&D.AUDIO_DEVICES_UPDATES||e===Jt.VIDEO&&D.VIDEO_DEVICES_UPDATES||e===Jt.SPEAKER&&D.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Jt.AUDIO&&D.SELECTED_MICROHPONE_UPDATE||e===Jt.VIDEO&&D.SELECTED_CAMERA_UPDATE||e===Jt.SPEAKER&&D.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:D.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===Jt.AUDIO&&D.AUDIO_PLAY_FAILED||e===Jt.VIDEO&&D.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Jt.AUDIO&&D.AUDIO_TRACK_MUTED||e===Jt.VIDEO&&D.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:D.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:D.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:D.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:D.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:D.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(n,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}n({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(n=>{this.eventHandler.callEvent({event:D.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:D.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:D.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=D.AUDIO_ON:i=D.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=D.VIDEO_ON:i=D.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:D.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){var c,d;let i,n;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!((c=i==null?void 0:i.producerReport)!=null&&c.length))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const l=await this.measurements.getProducersReport([...this.producers.values()]);i&&l?i.producerReport=l:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!((d=n.consumerReport)!=null&&d.length))){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const l=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&l?n.consumerReport=l:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:D.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:D.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:D.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:D.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:D.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:D.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:D.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerIceServers",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerConsumer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerProducer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendConsumerSharedMediaStateEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerProducingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerConsumingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"deRegisterConsumer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"deRegisterProducer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"disconnectConsumingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"disconnectProducingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPreCallTestBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendScreenShareToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendScreenShareRequestedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendActiveSpeakerEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"devices",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"selectedDevice",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaPermission",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaPlaybackFailed",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaTrackMuted",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"tabChanged",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"browserBackgrounded",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"browserForegrounded",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"legacySwitch",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"getPreCallTestResults",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendCallJoinBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendNetworkQualityTestBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendWebSocketConnectedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendTransportConnectedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendAudioToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendVideoToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendParticipantRoleToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"startPingStats",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"stopPingStats",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPingStatsEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerRebufferEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerAudioBlockEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerInitializedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerWorkerErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerRecoverableErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerAnalyticsEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerQualityChanged",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPlayerLiveLatency",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendDisconnectEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendReconnectEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"expectedVideoResolution",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"expectedScreenshareResolution",null),j=J([PT(TypeError,(s,t)=>K.error(t,s))],j);const _T=j;class nm extends ct{constructor(){super(...arguments);p(this,"stats");p(this,"peerId");p(this,"backend");p(this,"iceServers");p(this,"initialized",!1);p(this,"stalled",!1);p(this,"ipInformation");p(this,"logger")}async initialize({peerId:e,engineName:r,env:i=Up.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:h}){var m,v,y;try{if(this.peerId=e,this.logger=d,!h){this.logger.error("callStats::initialize",{event:"auth_token_missing",peerId:this.peerId}),this.stallCallStats();return}this.ipInformation=await Xp.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new _T(o,r,i,c,d,e,l,h),this.iceServers=n,(m=this.backend)==null||m.registerIceServers(this.iceServers),this.initialized=!0,(y=(v=this.backend)==null?void 0:v.eventHandler)==null||y.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(w){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:w instanceof Error?w.message:String(w),stack:w instanceof Error?w.stack:void 0}),this.stallCallStats()}}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,n;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(n=this.backend)==null||n.startPingStats()})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const i=new Date;this.onSafeInitialization(()=>{var n,o,c,d,l,u,h,m,v,y,w;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(m=this.backend)==null||m.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(v=this.backend)==null||v.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(y=this.backend)==null||y.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(w=this.backend)==null||w.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedScreenshareResolution(e,r,i)})}}new nm().setMaxListeners(30);class kT{constructor(){g(this,Po,void 0)}get telemetry(){var t;return(t=a(this,Po))==null?void 0:t.getValue("telemetry")}init(t){f(this,Po,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}Po=new WeakMap;class CT extends ct.EventEmitter{constructor(e){super();g(this,ar,void 0);g(this,or,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,ar,new Map),f(this,or,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,ar).set(e,[]);const i=a(this,or).get(e).map(()=>new Promise(n=>{a(this,ar).get(e).push(n)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((n,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),a(this,ar).delete(e)}onAsync(e,r){const i=a(this,ar),n=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return a(this,or).get(e)||a(this,or).set(e,[]),a(this,or).get(e).push(n),super.on(e,n)}reset(){f(this,ar,new Map),f(this,or,new Map),super.removeAllListeners()}}ar=new WeakMap,or=new WeakMap;var RT=typeof global=="object"&&global&&global.Object===Object&&global;const am=RT;var IT=typeof self=="object"&&self&&self.Object===Object&&self,AT=am||IT||Function("return this")();const cs=AT;var MT=cs.Symbol;const ks=MT;var om=Object.prototype,OT=om.hasOwnProperty,DT=om.toString,Ha=ks?ks.toStringTag:void 0;function NT(s){var t=OT.call(s,Ha),e=s[Ha];try{s[Ha]=void 0;var r=!0}catch(n){}var i=DT.call(s);return r&&(t?s[Ha]=e:delete s[Ha]),i}var VT=Object.prototype,LT=VT.toString;function xT(s){return LT.call(s)}var UT="[object Null]",$T="[object Undefined]",cm=ks?ks.toStringTag:void 0;function ui(s){return s==null?s===void 0?$T:UT:cm&&cm in Object(s)?NT(s):xT(s)}function Cs(s){return s!=null&&typeof s=="object"}var BT="[object Symbol]";function od(s){return typeof s=="symbol"||Cs(s)&&ui(s)==BT}function FT(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var HT=Array.isArray;const Mt=HT;var qT=1/0,dm=ks?ks.prototype:void 0,lm=dm?dm.toString:void 0;function um(s){if(typeof s=="string")return s;if(Mt(s))return FT(s,um)+"";if(od(s))return lm?lm.call(s):"";var t=s+"";return t=="0"&&1/s==-qT?"-0":t}var jT=/\s/;function GT(s){for(var t=s.length;t--&&jT.test(s.charAt(t)););return t}var WT=/^\s+/;function JT(s){return s&&s.slice(0,GT(s)+1).replace(WT,"")}function Kt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var hm=0/0,KT=/^[-+]0x[0-9a-f]+$/i,zT=/^0b[01]+$/i,YT=/^0o[0-7]+$/i,QT=parseInt;function pm(s){if(typeof s=="number")return s;if(od(s))return hm;if(Kt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Kt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=JT(s);var e=zT.test(s);return e||YT.test(s)?QT(s.slice(2),e?2:8):KT.test(s)?hm:+s}function fu(s){return s}var XT="[object AsyncFunction]",ZT="[object Function]",ey="[object GeneratorFunction]",ty="[object Proxy]";function vu(s){if(!Kt(s))return!1;var t=ui(s);return t==ZT||t==ey||t==XT||t==ty}var sy=cs["__core-js_shared__"];const Su=sy;var mm=function(){var s=/[^.]+$/.exec(Su&&Su.keys&&Su.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function ry(s){return!!mm&&mm in s}var iy=Function.prototype,ny=iy.toString;function hi(s){if(s!=null){try{return ny.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var ay=/[\\^$.*+?()[\]{}|]/g,oy=/^\[object .+?Constructor\]$/,cy=Function.prototype,dy=Object.prototype,ly=cy.toString,uy=dy.hasOwnProperty,hy=RegExp("^"+ly.call(uy).replace(ay,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function py(s){if(!Kt(s)||ry(s))return!1;var t=vu(s)?hy:oy;return t.test(hi(s))}function my(s,t){return s==null?void 0:s[t]}function pi(s,t){var e=my(s,t);return py(e)?e:void 0}var gy=pi(cs,"WeakMap");const Tu=gy;var gm=Object.create,fy=function(){function s(){}return function(t){if(!Kt(t))return{};if(gm)return gm(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const vy=fy;function Sy(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function Ty(){}function fm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var yy=800,Ey=16,by=Date.now;function wy(s){var t=0,e=0;return function(){var r=by(),i=Ey-(r-e);if(e=r,i>0){if(++t>=yy)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function Py(s){return function(){return s}}var _y=function(){try{var s=pi(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const cd=_y;var ky=cd?function(s,t){return cd(s,"toString",{configurable:!0,enumerable:!1,value:Py(t),writable:!0})}:fu,Cy=wy(ky);const Ry=Cy;function Iy(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function Ay(s,t,e,r){for(var i=s.length,n=e+(r?1:-1);r?n--:++n<i;)if(t(s[n],n,s))return n;return-1}function My(s){return s!==s}function Oy(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function Dy(s,t,e){return t===t?Oy(s,t,e):Ay(s,My,e)}function Ny(s,t){var e=s==null?0:s.length;return!!e&&Dy(s,t,0)>-1}var Vy=9007199254740991,Ly=/^(?:0|[1-9]\d*)$/;function yu(s,t){var e=typeof s;return t=t==null?Vy:t,!!t&&(e=="number"||e!="symbol"&&Ly.test(s))&&s>-1&&s%1==0&&s<t}function Eu(s,t,e){t=="__proto__"&&cd?cd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function qa(s,t){return s===t||s!==s&&t!==t}var xy=Object.prototype,Uy=xy.hasOwnProperty;function vm(s,t,e){var r=s[t];(!(Uy.call(s,t)&&qa(r,e))||e===void 0&&!(t in s))&&Eu(s,t,e)}function ja(s,t,e,r){var i=!e;e||(e={});for(var n=-1,o=t.length;++n<o;){var c=t[n],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?Eu(e,c,d):vm(e,c,d)}return e}var Sm=Math.max;function $y(s,t,e){return t=Sm(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=Sm(r.length-t,0),o=Array(n);++i<n;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),Sy(s,this,c)}}function By(s,t){return Ry($y(s,t,fu),s+"")}var Fy=9007199254740991;function bu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=Fy}function Ga(s){return s!=null&&bu(s.length)&&!vu(s)}function Hy(s,t,e){if(!Kt(e))return!1;var r=typeof t;return(r=="number"?Ga(e)&&yu(t,e.length):r=="string"&&t in e)?qa(e[t],s):!1}function qy(s){return By(function(t,e){var r=-1,i=e.length,n=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(n=s.length>3&&typeof n=="function"?(i--,n):void 0,o&&Hy(e[0],e[1],o)&&(n=i<3?void 0:n,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,n)}return t})}var jy=Object.prototype;function dd(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||jy;return s===e}function Gy(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var Wy="[object Arguments]";function Tm(s){return Cs(s)&&ui(s)==Wy}var ym=Object.prototype,Jy=ym.hasOwnProperty,Ky=ym.propertyIsEnumerable,zy=Tm(function(){return arguments}())?Tm:function(s){return Cs(s)&&Jy.call(s,"callee")&&!Ky.call(s,"callee")};const Wa=zy;function Yy(){return!1}var Em=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bm=Em&&typeof module=="object"&&module&&!module.nodeType&&module,Qy=bm&&bm.exports===Em,wm=Qy?cs.Buffer:void 0,Xy=wm?wm.isBuffer:void 0,Zy=Xy||Yy;const yn=Zy;var eE="[object Arguments]",tE="[object Array]",sE="[object Boolean]",rE="[object Date]",iE="[object Error]",nE="[object Function]",aE="[object Map]",oE="[object Number]",cE="[object Object]",dE="[object RegExp]",lE="[object Set]",uE="[object String]",hE="[object WeakMap]",pE="[object ArrayBuffer]",mE="[object DataView]",gE="[object Float32Array]",fE="[object Float64Array]",vE="[object Int8Array]",SE="[object Int16Array]",TE="[object Int32Array]",yE="[object Uint8Array]",EE="[object Uint8ClampedArray]",bE="[object Uint16Array]",wE="[object Uint32Array]",ye={};ye[gE]=ye[fE]=ye[vE]=ye[SE]=ye[TE]=ye[yE]=ye[EE]=ye[bE]=ye[wE]=!0,ye[eE]=ye[tE]=ye[pE]=ye[sE]=ye[mE]=ye[rE]=ye[iE]=ye[nE]=ye[aE]=ye[oE]=ye[cE]=ye[dE]=ye[lE]=ye[uE]=ye[hE]=!1;function PE(s){return Cs(s)&&bu(s.length)&&!!ye[ui(s)]}function wu(s){return function(t){return s(t)}}var Pm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ja=Pm&&typeof module=="object"&&module&&!module.nodeType&&module,_E=Ja&&Ja.exports===Pm,Pu=_E&&am.process,kE=function(){try{var s=Ja&&Ja.require&&Ja.require("util").types;return s||Pu&&Pu.binding&&Pu.binding("util")}catch(t){}}();const En=kE;var _m=En&&En.isTypedArray,CE=_m?wu(_m):PE;const ld=CE;var RE=Object.prototype,IE=RE.hasOwnProperty;function km(s,t){var e=Mt(s),r=!e&&Wa(s),i=!e&&!r&&yn(s),n=!e&&!r&&!i&&ld(s),o=e||r||i||n,c=o?Gy(s.length,String):[],d=c.length;for(var l in s)(t||IE.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||yu(l,d)))&&c.push(l);return c}function Cm(s,t){return function(e){return s(t(e))}}var AE=Cm(Object.keys,Object);const ME=AE;var OE=Object.prototype,DE=OE.hasOwnProperty;function Rm(s){if(!dd(s))return ME(s);var t=[];for(var e in Object(s))DE.call(s,e)&&e!="constructor"&&t.push(e);return t}function ud(s){return Ga(s)?km(s):Rm(s)}function NE(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var VE=Object.prototype,LE=VE.hasOwnProperty;function xE(s){if(!Kt(s))return NE(s);var t=dd(s),e=[];for(var r in s)r=="constructor"&&(t||!LE.call(s,r))||e.push(r);return e}function Ka(s){return Ga(s)?km(s,!0):xE(s)}var UE=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$E=/^\w*$/;function _u(s,t){if(Mt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||od(s)?!0:$E.test(s)||!UE.test(s)||t!=null&&s in Object(t)}var BE=pi(Object,"create");const za=BE;function FE(){this.__data__=za?za(null):{},this.size=0}function HE(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var qE="__lodash_hash_undefined__",jE=Object.prototype,GE=jE.hasOwnProperty;function WE(s){var t=this.__data__;if(za){var e=t[s];return e===qE?void 0:e}return GE.call(t,s)?t[s]:void 0}var JE=Object.prototype,KE=JE.hasOwnProperty;function zE(s){var t=this.__data__;return za?t[s]!==void 0:KE.call(t,s)}var YE="__lodash_hash_undefined__";function QE(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=za&&t===void 0?YE:t,this}function mi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}mi.prototype.clear=FE,mi.prototype.delete=HE,mi.prototype.get=WE,mi.prototype.has=zE,mi.prototype.set=QE;function XE(){this.__data__=[],this.size=0}function hd(s,t){for(var e=s.length;e--;)if(qa(s[e][0],t))return e;return-1}var ZE=Array.prototype,eb=ZE.splice;function tb(s){var t=this.__data__,e=hd(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():eb.call(t,e,1),--this.size,!0}function sb(s){var t=this.__data__,e=hd(t,s);return e<0?void 0:t[e][1]}function rb(s){return hd(this.__data__,s)>-1}function ib(s,t){var e=this.__data__,r=hd(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function js(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}js.prototype.clear=XE,js.prototype.delete=tb,js.prototype.get=sb,js.prototype.has=rb,js.prototype.set=ib;var nb=pi(cs,"Map");const Ya=nb;function ab(){this.size=0,this.__data__={hash:new mi,map:new(Ya||js),string:new mi}}function ob(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function pd(s,t){var e=s.__data__;return ob(t)?e[typeof t=="string"?"string":"hash"]:e.map}function cb(s){var t=pd(this,s).delete(s);return this.size-=t?1:0,t}function db(s){return pd(this,s).get(s)}function lb(s){return pd(this,s).has(s)}function ub(s,t){var e=pd(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function Gs(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}Gs.prototype.clear=ab,Gs.prototype.delete=cb,Gs.prototype.get=db,Gs.prototype.has=lb,Gs.prototype.set=ub;var hb="Expected a function";function ku(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(hb);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],n=e.cache;if(n.has(i))return n.get(i);var o=s.apply(this,r);return e.cache=n.set(i,o)||n,o};return e.cache=new(ku.Cache||Gs),e}ku.Cache=Gs;var pb=500;function mb(s){var t=ku(s,function(r){return e.size===pb&&e.clear(),r}),e=t.cache;return t}var gb=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fb=/\\(\\)?/g,vb=mb(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(gb,function(e,r,i,n){t.push(i?n.replace(fb,"$1"):r||e)}),t});const Sb=vb;function Tb(s){return s==null?"":um(s)}function Im(s,t){return Mt(s)?s:_u(s,t)?[s]:Sb(Tb(s))}var yb=1/0;function md(s){if(typeof s=="string"||od(s))return s;var t=s+"";return t=="0"&&1/s==-yb?"-0":t}function Am(s,t){t=Im(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[md(t[e++])];return e&&e==r?s:void 0}function Eb(s,t,e){var r=s==null?void 0:Am(s,t);return r===void 0?e:r}function Mm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var bb=Cm(Object.getPrototypeOf,Object);const Cu=bb;var wb="[object Object]",Pb=Function.prototype,_b=Object.prototype,Om=Pb.toString,kb=_b.hasOwnProperty,Cb=Om.call(Object);function Rb(s){if(!Cs(s)||ui(s)!=wb)return!1;var t=Cu(s);if(t===null)return!0;var e=kb.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Om.call(e)==Cb}function Ib(){this.__data__=new js,this.size=0}function Ab(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function Mb(s){return this.__data__.get(s)}function Ob(s){return this.__data__.has(s)}var Db=200;function Nb(s,t){var e=this.__data__;if(e instanceof js){var r=e.__data__;if(!Ya||r.length<Db-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new Gs(r)}return e.set(s,t),this.size=e.size,this}function ds(s){var t=this.__data__=new js(s);this.size=t.size}ds.prototype.clear=Ib,ds.prototype.delete=Ab,ds.prototype.get=Mb,ds.prototype.has=Ob,ds.prototype.set=Nb;function Vb(s,t){return s&&ja(t,ud(t),s)}function Lb(s,t){return s&&ja(t,Ka(t),s)}var Dm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Nm=Dm&&typeof module=="object"&&module&&!module.nodeType&&module,xb=Nm&&Nm.exports===Dm,Vm=xb?cs.Buffer:void 0,Lm=Vm?Vm.allocUnsafe:void 0;function xm(s,t){if(t)return s.slice();var e=s.length,r=Lm?Lm(e):new s.constructor(e);return s.copy(r),r}function Ub(s,t){for(var e=-1,r=s==null?0:s.length,i=0,n=[];++e<r;){var o=s[e];t(o,e,s)&&(n[i++]=o)}return n}function Um(){return[]}var $b=Object.prototype,Bb=$b.propertyIsEnumerable,$m=Object.getOwnPropertySymbols,Fb=$m?function(s){return s==null?[]:(s=Object(s),Ub($m(s),function(t){return Bb.call(s,t)}))}:Um;const Ru=Fb;function Hb(s,t){return ja(s,Ru(s),t)}var qb=Object.getOwnPropertySymbols,jb=qb?function(s){for(var t=[];s;)Mm(t,Ru(s)),s=Cu(s);return t}:Um;const Bm=jb;function Gb(s,t){return ja(s,Bm(s),t)}function Fm(s,t,e){var r=t(s);return Mt(s)?r:Mm(r,e(s))}function Iu(s){return Fm(s,ud,Ru)}function Wb(s){return Fm(s,Ka,Bm)}var Jb=pi(cs,"DataView");const Au=Jb;var Kb=pi(cs,"Promise");const Mu=Kb;var zb=pi(cs,"Set");const bn=zb;var Hm="[object Map]",Yb="[object Object]",qm="[object Promise]",jm="[object Set]",Gm="[object WeakMap]",Wm="[object DataView]",Qb=hi(Au),Xb=hi(Ya),Zb=hi(Mu),ew=hi(bn),tw=hi(Tu),gi=ui;(Au&&gi(new Au(new ArrayBuffer(1)))!=Wm||Ya&&gi(new Ya)!=Hm||Mu&&gi(Mu.resolve())!=qm||bn&&gi(new bn)!=jm||Tu&&gi(new Tu)!=Gm)&&(gi=function(s){var t=ui(s),e=t==Yb?s.constructor:void 0,r=e?hi(e):"";if(r)switch(r){case Qb:return Wm;case Xb:return Hm;case Zb:return qm;case ew:return jm;case tw:return Gm}return t});const wn=gi;var sw=Object.prototype,rw=sw.hasOwnProperty;function iw(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&rw.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var nw=cs.Uint8Array;const gd=nw;function Ou(s){var t=new s.constructor(s.byteLength);return new gd(t).set(new gd(s)),t}function aw(s,t){var e=t?Ou(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var ow=/\w*$/;function cw(s){var t=new s.constructor(s.source,ow.exec(s));return t.lastIndex=s.lastIndex,t}var Jm=ks?ks.prototype:void 0,Km=Jm?Jm.valueOf:void 0;function dw(s){return Km?Object(Km.call(s)):{}}function zm(s,t){var e=t?Ou(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var lw="[object Boolean]",uw="[object Date]",hw="[object Map]",pw="[object Number]",mw="[object RegExp]",gw="[object Set]",fw="[object String]",vw="[object Symbol]",Sw="[object ArrayBuffer]",Tw="[object DataView]",yw="[object Float32Array]",Ew="[object Float64Array]",bw="[object Int8Array]",ww="[object Int16Array]",Pw="[object Int32Array]",_w="[object Uint8Array]",kw="[object Uint8ClampedArray]",Cw="[object Uint16Array]",Rw="[object Uint32Array]";function Iw(s,t,e){var r=s.constructor;switch(t){case Sw:return Ou(s);case lw:case uw:return new r(+s);case Tw:return aw(s,e);case yw:case Ew:case bw:case ww:case Pw:case _w:case kw:case Cw:case Rw:return zm(s,e);case hw:return new r;case pw:case fw:return new r(s);case mw:return cw(s);case gw:return new r;case vw:return dw(s)}}function Ym(s){return typeof s.constructor=="function"&&!dd(s)?vy(Cu(s)):{}}var Aw="[object Map]";function Mw(s){return Cs(s)&&wn(s)==Aw}var Qm=En&&En.isMap,Ow=Qm?wu(Qm):Mw;const Dw=Ow;var Nw="[object Set]";function Vw(s){return Cs(s)&&wn(s)==Nw}var Xm=En&&En.isSet,Lw=Xm?wu(Xm):Vw;const xw=Lw;var Uw=1,$w=2,Bw=4,Zm="[object Arguments]",Fw="[object Array]",Hw="[object Boolean]",qw="[object Date]",jw="[object Error]",eg="[object Function]",Gw="[object GeneratorFunction]",Ww="[object Map]",Jw="[object Number]",tg="[object Object]",Kw="[object RegExp]",zw="[object Set]",Yw="[object String]",Qw="[object Symbol]",Xw="[object WeakMap]",Zw="[object ArrayBuffer]",eP="[object DataView]",tP="[object Float32Array]",sP="[object Float64Array]",rP="[object Int8Array]",iP="[object Int16Array]",nP="[object Int32Array]",aP="[object Uint8Array]",oP="[object Uint8ClampedArray]",cP="[object Uint16Array]",dP="[object Uint32Array]",ge={};ge[Zm]=ge[Fw]=ge[Zw]=ge[eP]=ge[Hw]=ge[qw]=ge[tP]=ge[sP]=ge[rP]=ge[iP]=ge[nP]=ge[Ww]=ge[Jw]=ge[tg]=ge[Kw]=ge[zw]=ge[Yw]=ge[Qw]=ge[aP]=ge[oP]=ge[cP]=ge[dP]=!0,ge[jw]=ge[eg]=ge[Xw]=!1;function Qa(s,t,e,r,i,n){var o,c=t&Uw,d=t&$w,l=t&Bw;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!Kt(s))return s;var u=Mt(s);if(u){if(o=iw(s),!c)return fm(s,o)}else{var h=wn(s),m=h==eg||h==Gw;if(yn(s))return xm(s,c);if(h==tg||h==Zm||m&&!i){if(o=d||m?{}:Ym(s),!c)return d?Gb(s,Lb(o,s)):Hb(s,Vb(o,s))}else{if(!ge[h])return i?s:{};o=Iw(s,h,c)}}n||(n=new ds);var v=n.get(s);if(v)return v;n.set(s,o),xw(s)?s.forEach(function(R){o.add(Qa(R,t,e,R,s,n))}):Dw(s)&&s.forEach(function(R,P){o.set(P,Qa(R,t,e,P,s,n))});var y=l?d?Wb:Iu:d?Ka:ud,w=u?void 0:y(s);return Iy(w||s,function(R,P){w&&(P=R,R=s[P]),vm(o,P,Qa(R,t,e,P,s,n))}),o}var lP=4;function uP(s){return Qa(s,lP)}var hP=1,pP=4;function Du(s){return Qa(s,hP|pP)}var mP="__lodash_hash_undefined__";function gP(s){return this.__data__.set(s,mP),this}function fP(s){return this.__data__.has(s)}function Xa(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new Gs;++t<e;)this.add(s[t])}Xa.prototype.add=Xa.prototype.push=gP,Xa.prototype.has=fP;function vP(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function sg(s,t){return s.has(t)}var SP=1,TP=2;function rg(s,t,e,r,i,n){var o=e&SP,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var h=-1,m=!0,v=e&TP?new Xa:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var y=s[h],w=t[h];if(r)var R=o?r(w,y,h,t,s,n):r(y,w,h,s,t,n);if(R!==void 0){if(R)continue;m=!1;break}if(v){if(!vP(t,function(P,N){if(!sg(v,N)&&(y===P||i(y,P,e,r,n)))return v.push(N)})){m=!1;break}}else if(!(y===w||i(y,w,e,r,n))){m=!1;break}}return n.delete(s),n.delete(t),m}function yP(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function Nu(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var EP=1,bP=2,wP="[object Boolean]",PP="[object Date]",_P="[object Error]",kP="[object Map]",CP="[object Number]",RP="[object RegExp]",IP="[object Set]",AP="[object String]",MP="[object Symbol]",OP="[object ArrayBuffer]",DP="[object DataView]",ig=ks?ks.prototype:void 0,Vu=ig?ig.valueOf:void 0;function NP(s,t,e,r,i,n,o){switch(e){case DP:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case OP:return!(s.byteLength!=t.byteLength||!n(new gd(s),new gd(t)));case wP:case PP:case CP:return qa(+s,+t);case _P:return s.name==t.name&&s.message==t.message;case RP:case AP:return s==t+"";case kP:var c=yP;case IP:var d=r&EP;if(c||(c=Nu),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=bP,o.set(s,t);var u=rg(c(s),c(t),r,i,n,o);return o.delete(s),u;case MP:if(Vu)return Vu.call(s)==Vu.call(t)}return!1}var VP=1,LP=Object.prototype,xP=LP.hasOwnProperty;function UP(s,t,e,r,i,n){var o=e&VP,c=Iu(s),d=c.length,l=Iu(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var m=c[h];if(!(o?m in t:xP.call(t,m)))return!1}var v=n.get(s),y=n.get(t);if(v&&y)return v==t&&y==s;var w=!0;n.set(s,t),n.set(t,s);for(var R=o;++h<d;){m=c[h];var P=s[m],N=t[m];if(r)var $=o?r(N,P,m,t,s,n):r(P,N,m,s,t,n);if(!($===void 0?P===N||i(P,N,e,r,n):$)){w=!1;break}R||(R=m=="constructor")}if(w&&!R){var x=s.constructor,H=t.constructor;x!=H&&"constructor"in s&&"constructor"in t&&!(typeof x=="function"&&x instanceof x&&typeof H=="function"&&H instanceof H)&&(w=!1)}return n.delete(s),n.delete(t),w}var $P=1,ng="[object Arguments]",ag="[object Array]",fd="[object Object]",BP=Object.prototype,og=BP.hasOwnProperty;function FP(s,t,e,r,i,n){var o=Mt(s),c=Mt(t),d=o?ag:wn(s),l=c?ag:wn(t);d=d==ng?fd:d,l=l==ng?fd:l;var u=d==fd,h=l==fd,m=d==l;if(m&&yn(s)){if(!yn(t))return!1;o=!0,u=!1}if(m&&!u)return n||(n=new ds),o||ld(s)?rg(s,t,e,r,i,n):NP(s,t,d,e,r,i,n);if(!(e&$P)){var v=u&&og.call(s,"__wrapped__"),y=h&&og.call(t,"__wrapped__");if(v||y){var w=v?s.value():s,R=y?t.value():t;return n||(n=new ds),i(w,R,e,r,n)}}return m?(n||(n=new ds),UP(s,t,e,r,i,n)):!1}function vd(s,t,e,r,i){return s===t?!0:s==null||t==null||!Cs(s)&&!Cs(t)?s!==s&&t!==t:FP(s,t,e,r,vd,i)}var HP=1,qP=2;function jP(s,t,e,r){var i=e.length,n=i,o=!r;if(s==null)return!n;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<n;){c=e[i];var d=c[0],l=s[d],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var h=new ds;if(r)var m=r(l,u,d,s,t,h);if(!(m===void 0?vd(u,l,HP|qP,r,h):m))return!1}}return!0}function cg(s){return s===s&&!Kt(s)}function GP(s){for(var t=ud(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,cg(i)]}return t}function dg(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function WP(s){var t=GP(s);return t.length==1&&t[0][2]?dg(t[0][0],t[0][1]):function(e){return e===s||jP(e,s,t)}}function JP(s,t){return s!=null&&t in Object(s)}function KP(s,t,e){t=Im(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=md(t[r]);if(!(n=s!=null&&e(s,o)))break;s=s[o]}return n||++r!=i?n:(i=s==null?0:s.length,!!i&&bu(i)&&yu(o,i)&&(Mt(s)||Wa(s)))}function zP(s,t){return s!=null&&KP(s,t,JP)}var YP=1,QP=2;function XP(s,t){return _u(s)&&cg(t)?dg(md(s),t):function(e){var r=Eb(e,s);return r===void 0&&r===t?zP(e,s):vd(t,r,YP|QP)}}function ZP(s){return function(t){return t==null?void 0:t[s]}}function e_(s){return function(t){return Am(t,s)}}function t_(s){return _u(s)?ZP(md(s)):e_(s)}function s_(s){return typeof s=="function"?s:s==null?fu:typeof s=="object"?Mt(s)?XP(s[0],s[1]):WP(s):t_(s)}function r_(s){return function(t,e,r){for(var i=-1,n=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(n[d],d,n)===!1)break}return t}}var i_=r_();const n_=i_;var a_=function(){return cs.Date.now()};const Lu=a_;var o_="Expected a function",c_=Math.max,d_=Math.min;function xu(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,m=!0;if(typeof s!="function")throw new TypeError(o_);t=pm(t)||0,Kt(e)&&(u=!!e.leading,h="maxWait"in e,n=h?c_(pm(e.maxWait)||0,t):n,m="trailing"in e?!!e.trailing:m);function v(F){var Z=r,je=i;return r=i=void 0,l=F,o=s.apply(je,Z),o}function y(F){return l=F,c=setTimeout(P,t),u?v(F):o}function w(F){var Z=F-d,je=F-l,jt=t-Z;return h?d_(jt,n-je):jt}function R(F){var Z=F-d,je=F-l;return d===void 0||Z>=t||Z<0||h&&je>=n}function P(){var F=Lu();if(R(F))return N(F);c=setTimeout(P,w(F))}function N(F){return c=void 0,m&&r?v(F):(r=i=void 0,o)}function $(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function x(){return c===void 0?o:N(Lu())}function H(){var F=Lu(),Z=R(F);if(r=arguments,i=this,d=F,Z){if(c===void 0)return y(d);if(h)return clearTimeout(c),c=setTimeout(P,t),v(d)}return c===void 0&&(c=setTimeout(P,t)),o}return H.cancel=$,H.flush=x,H}function Uu(s,t,e){(e!==void 0&&!qa(s[t],e)||e===void 0&&!(t in s))&&Eu(s,t,e)}function l_(s){return Cs(s)&&Ga(s)}function $u(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function u_(s){return ja(s,Ka(s))}function h_(s,t,e,r,i,n,o){var c=$u(s,e),d=$u(t,e),l=o.get(d);if(l){Uu(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var m=Mt(d),v=!m&&yn(d),y=!m&&!v&&ld(d);u=d,m||v||y?Mt(c)?u=c:l_(c)?u=fm(c):v?(h=!1,u=xm(d,!0)):y?(h=!1,u=zm(d,!0)):u=[]:Rb(d)||Wa(d)?(u=c,Wa(c)?u=u_(c):(!Kt(c)||vu(c))&&(u=Ym(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),Uu(s,e,u)}function lg(s,t,e,r,i){s!==t&&n_(t,function(n,o){if(i||(i=new ds),Kt(n))h_(s,t,o,e,lg,r,i);else{var c=r?r($u(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),Uu(s,o,c)}},Ka)}function p_(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var m_="[object Map]",g_="[object Set]",f_=Object.prototype,v_=f_.hasOwnProperty;function S_(s){if(s==null)return!0;if(Ga(s)&&(Mt(s)||typeof s=="string"||typeof s.splice=="function"||yn(s)||ld(s)||Wa(s)))return!s.length;var t=wn(s);if(t==m_||t==g_)return!s.size;if(dd(s))return!Rm(s).length;for(var e in s)if(v_.call(s,e))return!1;return!0}function T_(s,t){return vd(s,t)}var y_=qy(function(s,t,e){lg(s,t,e)});const Cr=y_;var E_=1/0,b_=bn&&1/Nu(new bn([,-0]))[1]==E_?function(s){return new bn(s)}:Ty;const w_=b_;var P_=200;function ug(s,t,e){var r=-1,i=Ny,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=p_;else if(n>=P_){var l=t?null:w_(s);if(l)return Nu(l);o=!1,i=sg,d=new Xa}else d=t?[]:c;e:for(;++r<n;){var u=s[r],h=t?t(u):u;if(u=e||u!==0?u:0,o&&h===h){for(var m=d.length;m--;)if(d[m]===h)continue e;t&&d.push(h),c.push(u)}else i(d,h,e)||(d!==c&&d.push(h),c.push(u))}return c}function __(s){return s&&s.length?ug(s):[]}function k_(s,t){return s&&s.length?ug(s,s_(t)):[]}function Sd(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const C_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},hg={STAGING:"staging",PROD:"prod"},R_={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function Pn(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function I_({baseURI:s}){return s.includes("staging.realtime")?hg.STAGING:hg.PROD}function _n({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function A_(s){const t=s.getValue("baseURI");return{location:_n({servicePrefix:"location",baseURI:t}),locationLegacy:_n({servicePrefix:"location-legacy",baseURI:t}),daCollector:_n({servicePrefix:"da-collector",baseURI:t})}}const M_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',O_='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Td=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(n=>{n(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((n,o)=>{r.onload=()=>{n(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},fi={logs:"https://api.realtime.cloudflare.com/logs/otel/logs",mock:{url:"https://api.realtime.cloudflare.com/mock",domain:"mock.realtime.cloudflare.com",app:"https://examples.realtime.cloudflare.com/meeting",stagingApp:"https://examples.staging.realtime.cloudflare.com/meeting"},apiBase:{prod:"https://api.realtime.cloudflare.com",staging:"https://api.staging.realtime.cloudflare.com",prodAlternate:"https://api.realtime.cloudflare.com"},baseURI:{prod:"realtime.cloudflare.com",staging:"staging.realtime.cloudflare.com"}},D_=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,Bu="__rtk_plugins__",N_=[Bu];function pg(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(fi.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function V_(s,t){var r;const e=(r=s==null?void 0:s.getValue("telemetry"))==null?void 0:r.logLevel;if(e==="off")return!1;if(e!=="all"){const i=["debug","log","info","warn","error"],n=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(n<o)return!1}return!0}function mg(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var n;if([null,void 0,NaN].includes(s[r])||t&&(((n=t.match(/\./g))==null?void 0:n.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?mg(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function gg(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=mg(o,r),d=JSON.stringify(c);if(!(t==null?void 0:t.startsWith("[SDP]"))&&d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size
10
- ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw pg(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(n){const o=Sd(n);i[`${r}.error.message`]=o.message||"",i[`${r}.error.stack`]=o.stack||"",i[`${r}.error.reason`]=o.reason||"",i[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}class E{constructor(){p(this,"logsCache",[]);p(this,"logsProcessorTimer");p(this,"compressionSupported",null);p(this,"tracingEnabled",!0);p(this,"initialized",!1);p(this,"logLevel","log");p(this,"logsProcessingInterval",7e3);p(this,"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"]);p(this,"meetingMetadata",{})}isCompressionSupported(){if(this.compressionSupported===null)try{this.compressionSupported=typeof CompressionStream!="undefined"&&typeof Blob!="undefined"&&typeof Blob.prototype.stream=="function"&&typeof Response!="undefined"}catch(t){this.compressionSupported=!1,this.addLogInCurrentSpan("warn","Compression feature detection failed, using uncompressed logs",{error:t})}return this.compressionSupported}get logsEndpoint(){const t=Rr.getContext(this.meetingMetadata.peerId);return`https://${_n({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}get logsBatchSize(){return this.isCompressionSupported()?50:25}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r,i){this.tracingEnabled=!0,this.initialized=!1,i&&(this.logLevel=i),this.logsCache=[];const n=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=n,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:o}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?o==null?void 0:o.getDeviceInfo():Te.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(()=>this.processCachedLogs().catch(()=>{}),this.logsProcessingInterval),r&&(this.initialized=!0)}static trace(t,e=void 0){return(r,i,n)=>{const o=n.value;return n.value=function(...d){const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled)return o.apply(this,d);l.addLogInCurrentSpan("info",t,e);const u=performance.now(),h=o.apply(this,d);return Promise.resolve(h).then(()=>{const m=performance.now();m-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:m-u})}).catch(()=>{const m=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:m-u})}),h},n}}injectContext(t){var i;const e=Sn().replace(/-/g,"").substring(0,16),r=(i=this.meetingMetadata.peerId)==null?void 0:i.replace(/-/g,"");t.TRACEPARENT=`00-${r}-${e}-01`}addLogInCurrentSpan(t,e,r={},i=!1){r!=null&&r.error&&Object.assign(r,{error:Sd(r.error)});const n=Rr.getContext(this.meetingMetadata.peerId);if(pg(n)&&(S_(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!V_(n,t))try{const c=gg(n,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l],{isInDestructionMode:!1}).catch(()=>{}):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:Sd(c)})}}async sendOtelLogsToNewRelic(t,{isInDestructionMode:e=!1}={isInDestructionMode:!1}){const r=new AbortController,i=setTimeout(()=>r.abort("Logs request timed out after 8 seconds"),8e3);try{const n=Rr.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:gg(n,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:n.getValue("sdkName"),logs:t});let c;const d={Authorization:`Bearer ${n.getValue("authToken")}`};if(this.isCompressionSupported()){const l=new Blob([o]).stream().pipeThrough(new CompressionStream("gzip"));c=await new Response(l).arrayBuffer(),d["Content-Type"]="application/gzip",d["Content-Encoding"]="gzip"}else c=o,d["Content-Type"]="application/json";await fetch(this.logsEndpoint,{method:"POST",headers:d,body:c,signal:r.signal,keepalive:!!e})}catch(n){e||(this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:Sd(n)}),this.logsCache.push(...t))}finally{clearTimeout(i)}}async processCachedLogs({isInDestructionMode:t=!1}={isInDestructionMode:!1}){const e=this.logsCache.splice(0,this.logsBatchSize);e!=null&&e.length&&await this.sendOtelLogsToNewRelic(e,{isInDestructionMode:t})}async destruct(){for(clearInterval(this.logsProcessorTimer);this.logsCache.length;)await this.processCachedLogs({isInDestructionMode:!0})}}function L_(s){const t={...s},e=new Map,r=(l,u)=>(e.has(l)||e.set(l,new Set),e.get(l).add(u),()=>{var h;return(h=e.get(l))==null?void 0:h.delete(u)}),i=(l,u)=>{var h;(h=e.get(l))==null||h.delete(u)},n=l=>{var u;(u=e.get(l))==null||u.forEach(h=>{try{h(t[l])}catch(m){}})};return{subscribe:r,unsubscribe:i,notify:n,setValue:(l,u,h=!0)=>{t[l]=u,h&&n(l)},getValue:l=>t[l],getAllValues:()=>t}}class x_{constructor(){p(this,"contexts",new Map);p(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new E,i=new kT;this.contexts.set(t,L_(e)),this.contexts.get(t).setValue("peerSessionStore",new CT(i));const n=new nm;return n.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",n),this.mostRecentPeerId=t,this.contexts.get(t)}remapContext(t,e){const r=e.getValue("peerId");r!==t&&(e.setValue("peerId",t),this.mostRecentPeerId=t,this.contexts.set(t,e),this.contexts.delete(r))}getContext(t){return this.contexts.get(t)}getMostRecentPeerId(){return this.mostRecentPeerId}}const Rr=new x_,U_={"00":"Client","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption",18:"AI",19:"Livestream",20:"Stage"},yd={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0014":"Failed to establish media connection.","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0604":"Active plugins store is not available yet","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(yd).forEach(s=>{yd[s]=`{${U_[s.slice(0,2)]}} ${yd[s]}`});class C extends Error{constructor(e,r,i=void 0,n=!1){super(e);p(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?yd[this.code]:"";this.message=`${o}: ${c}
11
- ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=Rr.getContext(Rr.getMostRecentPeerId());if(l){const u=l.getValue("onError");try{u(this)}catch(h){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function Ed(s,t,e,r){if(r instanceof C)throw r;if(r instanceof t){const i=new C(r.message,e);throw i.stack=r.stack,i}else throw r}function fg(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Ed(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Ed(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Ed(this,t,e,o)}):n}catch(n){Ed(this,t,e,n)}},s}function $_(s,t){return(e,r,i)=>{if(i)return fg(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,fg(o,s,t))}}}const dt=s=>$_(Error,s);var Ws=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Ws||{}),G=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(G||{});typeof process!="undefined"&&(Nv=process==null?void 0:process.env)!=null&&Nv.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var vg=[-2,-1,0,1,2],B_=[0,1,2,3,4];function F_(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var H_=(s,t,e)=>{let r,i,n;if(t==0)r=i=n=e;else{const o=(l,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?l+(u-l)*6*h:h<.5?u:h<.6666666666666666?l+(u-l)*(.6666666666666666-h)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),n=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(n*255)]},q_=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let n,o;const c=(r+i)/2;if(r==i)n=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:n=(t-e)/d+(t<e?6:0);break;case t:n=(e-s)/d+2;break;case e:n=(s-t)/d+4;break}n/=6}return[n,o,c]},j_=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},Sg=(s,t=vg,e=.4)=>{const r=[],[i,n,o]=F_(s),[c,d,l]=q_(i,n,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const h=t.findIndex(R=>R===0);if(h===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const m=5-h,v=h+1,y=(100-u)/m,w=u/v;for(const R of t){let P;R<0?P=u+R*w*e:R>0?P=u+R*y*e:P=u;const[N,$,x]=H_(c,d,P/100);r.push(j_(N,$,x))}return r},Tg={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"}},G_=s=>{const[t,e,r,i,n]=Sg(s,vg);return{300:t,400:e,500:r,600:i,700:n}},W_=s=>{if(s==="#FFFFFF")return Tg.light.background;if(s==="#000000")return Tg.dark.background;const[t,e,r,i,n]=Sg(s,B_);return{1e3:t,900:e,800:r,700:i,600:n}},J_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:G_("#2160FD"),background:W_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function yg(){return Du(J_)}var K_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:yg(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function z_(){return Du(K_)}var Y_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:yg(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function Fu(){return Du(Y_)}function Q_(){Te.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(n=>{var o;return(o=n.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var k=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(k||{});class kn extends ct.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::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 Ot extends ct.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::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)}}function X_(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const Eg=1080,bg=1920,Z_=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,m=l*u,v,y,w,R,P=1;return h<e&&(P=e/h),Math.abs(P-1)<1e-14&&m<r&&(P=r/m),h*=P,m*=P,w=d/(h/e),R=l/(m/r),v=(d-w)*o,y=(l-R)*c,v<0&&(v=0),y<0&&(y=0),w>d&&(w=d),R>l&&(R=l),[v,y,w,R,s,t,e,r]},zh=class extends Ot{constructor(e,r,i,n){const o=e.getValue("logger");super(o);g(this,Xt,void 0);g(this,Ii,void 0);g(this,ut,void 0);g(this,Zt,void 0);g(this,Oe,{height:Eg,width:bg});g(this,gs,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,cr,void 0);g(this,ft,{});g(this,xe,void 0);g(this,$n,void 0);g(this,Bn,void 0);g(this,dr,void 0);g(this,Fn,!1);p(this,"cleanupEventListeners",()=>{a(this,Ii).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,xe).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,xe).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,xe).removeListener("roomLeft",()=>this.disable())});p(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});p(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});p(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});p(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});p(this,"eventCallback",e=>{e==="CAMERA"&&(a(this,xe).videoEnabled?a(this,xe).disableVideo():a(this,xe).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,xe).audioEnabled?a(this,xe).disableAudio():a(this,xe).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,Ii).getValue("peerSessionStore").emit(k.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});p(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});p(this,"animate",()=>{if(!this.isActive&&a(this,dr)==="active"){this.disable(!0);return}a(this,ft)!==void 0&&this.paintCanvas(),a(this,cr)!==void 0&&f(this,cr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,dr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,cr)),e!==!0&&document.body.removeChild(a(this,ut)),f(this,cr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,Ii,e),f(this,dr,"idle"),f(this,xe,r),f(this,gs,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),n&&this.setupIcon("handRaise",n)}static async _init(e,r){let i,n;try{i=await Td(M_),n=await Td(O_)}catch(o){}return new zh(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,Bn,r);break;case"pin":f(this,$n,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,Bn,await Td(r));break;case"pin":f(this,$n,await Td(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,ut,document.createElement("div")),a(this,ut).style.width="0.1px",a(this,ut).style.height="0.1px",a(this,ut).style.overflow="hidden",a(this,ut).style.position="absolute",a(this,ut).style.bottom="0",a(this,ut).style.right="0",a(this,ut).style.opacity="0",a(this,ut).appendChild(a(this,Zt))}setupEventListeners(){a(this,Ii).subscribe("stageStatus",this.handlePipMediaControls),a(this,xe).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,xe).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,xe).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,Oe).height,e.width=a(this,Oe).width,f(this,Xt,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||a(this,xe).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,xe).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,ft)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,Xt)===void 0)return;const o=a(this,Xt).getContext("2d"),c=a(this,Xt).width,d=0,l=0,u=r-d*2,h=i-d*2,m=Math.floor(c/u),v=Math.floor(e/m),w=e%m*(u+d)+d,R=v*(h+d)+d,{displayText:P,image:N}=n!=null?n:{};o.fillStyle=P||N?a(this,gs).videoBackground:a(this,gs).background,o.strokeStyle=a(this,gs).brand,o.beginPath(),o.moveTo(w+l,R),o.arcTo(w+u,R,w+u,R+l,l),o.arcTo(w+u,R+h,w+u-l,R+h,l),o.arcTo(w,R+h,w,R+h-l,l),o.arcTo(w,R,w+l,R,l),o.closePath(),o.fill(),o.stroke();const $=u/6,x=u/2+w,H=h/2+R;o.save(),(P||N)&&(o.beginPath(),o.arc(x,H,$,0,Math.PI*2),o.fillStyle=a(this,gs).brand,o.fill(),N?(o.clip(),o.drawImage(N,x-$,H-$,$*2,$*2),o.restore()):P&&(o.fillStyle=a(this,gs).textOnBrand,o.font=`${$/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(P,x,H)),this.drawIcons(n,w,R,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=m=>{const v=a(this,Xt).getContext("2d");v.save(),v.fillStyle=a(this,gs).background,v.beginPath(),v.moveTo(l+d,u),v.arcTo(l+o,u,l+o,u+d,d),v.arcTo(l+o,u+o,l+o-d,u+o,d),v.arcTo(l,u+o,l,u+o-d,d),v.arcTo(l,u,l+d,u,d),v.closePath(),v.fill(),typeof m=="string"?(v.font=`${o/1.5}px sans-serif`,v.fillStyle=a(this,gs).text,v.textAlign="center",v.textBaseline="top",v.fillText(m,o/2+l,u+c)):v.drawImage(m,l+c,u+c,o-c*2,o-c*2),l+=o+c,v.restore()};e.pinned&&h(a(this,$n)),e.handRaised&&h(a(this,Bn)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,Xt)===void 0)return;const n=a(this,Xt).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Oe).height-5;){let h=0;for(;h<a(this,Oe).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const m=o[d].element,[v,y,w,R,P,N,$,x]=Z_(h,c,e,r,m.videoWidth,m.videoHeight);((u=m==null?void 0:m.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(m,v,y,w,R,-1*P,N,-1*$,x),n.restore()):n.drawImage(m,v,y,w,R,P,N,$,x),this.drawIcons(o[d],P,N,Math.max($,x))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,h+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,Oe).width,a(this,Oe).height];case 2:return[Math.floor(a(this,Oe).width/2),a(this,Oe).height];case 3:case 4:return[Math.floor(a(this,Oe).width/2),Math.floor(a(this,Oe).height/2)];case 5:case 6:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).height/3)];default:return[Math.floor(a(this,Oe).width/3),Math.floor(a(this,Oe).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=a(this,xe).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,Fn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,ut))try{document.body.removeChild(a(this,ut))}catch(e){}this.removeAllSources(),f(this,Xt,void 0),f(this,Zt,void 0),f(this,cr,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(a(this,Fn))return;f(this,Fn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,Oe,{height:e!=null?e:Eg,width:r!=null?r:bg}),i.height=a(this,Oe).height,i.width=a(this,Oe).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,Xt).captureStream(24),f(this,Zt,i),a(this,Zt).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,Zt).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){a(this,ft)[e]!==void 0&&(a(this,ft)[e].enabled=!0)}disableSource(e){a(this,ft)[e]!==void 0&&(a(this,ft)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,ft)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?X_(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=a(this,ft)[e];i&&(a(this,ft)[e]={...i,...r})}removeSource(e){delete a(this,ft)[e]}removePinnedSource(){Object.values(a(this,ft)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,ft,{})}enable(){f(this,dr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,xe).videoEnabled),this.updateMediaSession("MIC",a(this,xe).audioEnabled),document.body.appendChild(a(this,ut)),f(this,cr,requestAnimationFrame(()=>this.animate())),a(this,Zt).onloadedmetadata=()=>{a(this,Zt).requestPictureInPicture().then(()=>{f(this,dr,"active")})},a(this,Zt).readyState===4&&a(this,Zt).requestPictureInPicture().then(()=>{f(this,dr,"active")})}};let Hu=zh;Xt=new WeakMap,Ii=new WeakMap,ut=new WeakMap,Zt=new WeakMap,Oe=new WeakMap,gs=new WeakMap,cr=new WeakMap,ft=new WeakMap,xe=new WeakMap,$n=new WeakMap,Bn=new WeakMap,dr=new WeakMap,Fn=new WeakMap;function qu(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function ek(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let Js="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),bd=[];for(let s=0;s<Js.length;s++)bd[Js[s].charCodeAt(0)]=s;bd["-".charCodeAt(0)]=Js.indexOf("+"),bd["_".charCodeAt(0)]=Js.indexOf("/");function tk(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,i=0,n,o=0;for(let c=0;c<s.length;c++){if(n=bd[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
12
- `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=n,i=1;break;case 1:e[r++]=o<<2|(n&48)>>4,o=n,i=2;break;case 2:e[r++]=(o&15)<<4|(n&60)>>2,o=n,i=3;break;case 3:e[r++]=(o&3)<<6|n,i=0;break}}if(i==1)throw Error("invalid base64 string.");return e.subarray(0,r)}function sk(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=Js[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=Js[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=Js[i|r>>6],t+=Js[r&63],e=0;break}return e&&(t+=Js[i],t+="=",e==1&&(t+="=")),t}var wd;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(e,r,i,n,o)=>{(t(r)?r[s.symbol]:r[s.symbol]=[]).push({no:i,wireType:n,data:o})},s.onWrite=(e,r,i)=>{for(let{no:n,wireType:o,data:c}of s.list(r))i.tag(n,o).raw(c)},s.list=(e,r)=>{if(t(e)){let i=e[s.symbol];return r?i.filter(n=>n.no==r):i}return[]},s.last=(e,r)=>s.list(e,r).slice(-1)[0];const t=e=>e&&Array.isArray(e[s.symbol])})(wd||(wd={}));var Le;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})(Le||(Le={}));function rk(){let s=0,t=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(s|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}let e=this.buf[this.pos++];if(s|=(e&15)<<28,t=(e&112)>>4,!(e&128))return this.assertBounds(),[s,t];for(let r=3;r<=31;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}throw new Error("invalid varint")}function ju(s,t,e){for(let n=0;n<28;n=n+7){const o=s>>>n,c=!(!(o>>>7)&&t==0),d=(c?o|128:o)&255;if(e.push(d),!c)return}const r=s>>>28&15|(t&7)<<4,i=!!(t>>3);if(e.push((i?r|128:r)&255),!!i){for(let n=3;n<31;n=n+7){const o=t>>>n,c=!!(o>>>7),d=(c?o|128:o)&255;if(e.push(d),!c)return}e.push(t>>>31&1)}}const Pd=(1<<16)*(1<<16);function wg(s){let t=s[0]=="-";t&&(s=s.slice(1));const e=1e6;let r=0,i=0;function n(o,c){const d=Number(s.slice(o,c));i*=e,r=r*e+d,r>=Pd&&(i=i+(r/Pd|0),r=r%Pd)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function Gu(s,t){if(t>>>0<=2097151)return""+(Pd*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,i=t>>16&65535,n=e+r*6777216+i*6710656,o=r+i*8147497,c=i*2,d=1e7;n>=d&&(o+=Math.floor(n/d),n%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(u,h){let m=u?String(u):"";return h?"0000000".slice(m.length)+m:m}return l(c,0)+l(o,c)+l(n,1)}function Pg(s,t){if(s>=0){for(;s>127;)t.push(s&127|128),s=s>>>7;t.push(s)}else{for(let e=0;e<9;e++)t.push(s&127|128),s=s>>7;t.push(1)}}function ik(){let s=this.buf[this.pos++],t=s&127;if(!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<7,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<14,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<21,!(s&128))return this.assertBounds(),t;s=this.buf[this.pos++],t|=(s&15)<<28;for(let e=5;s&128&&e<10;e++)s=this.buf[this.pos++];if(s&128)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let pe;function nk(){const s=new DataView(new ArrayBuffer(8));pe=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}nk();function _g(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const kg=/^-?[0-9]+$/,_d=4294967296,kd=2147483648;class Cg{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*_d+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class lt extends Cg{static from(t){if(pe)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=pe.C(t);case"number":if(t===0)return this.ZERO;t=pe.C(t);case"bigint":if(!t)return this.ZERO;if(t<pe.UMIN)throw new Error("signed value for ulong");if(t>pe.UMAX)throw new Error("ulong too large");return pe.V.setBigUint64(0,t,!0),new lt(pe.V.getInt32(0,!0),pe.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!kg.test(t))throw new Error("string is no integer");let[e,r,i]=wg(t);if(e)throw new Error("signed value for ulong");return new lt(r,i);case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");if(t<0)throw new Error("signed value for ulong");return new lt(t,t/_d)}throw new Error("unknown value "+typeof t)}toString(){return pe?this.toBigInt().toString():Gu(this.lo,this.hi)}toBigInt(){return _g(pe),pe.V.setInt32(0,this.lo,!0),pe.V.setInt32(4,this.hi,!0),pe.V.getBigUint64(0,!0)}}lt.ZERO=new lt(0,0);class fe extends Cg{static from(t){if(pe)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=pe.C(t);case"number":if(t===0)return this.ZERO;t=pe.C(t);case"bigint":if(!t)return this.ZERO;if(t<pe.MIN)throw new Error("signed long too small");if(t>pe.MAX)throw new Error("signed long too large");return pe.V.setBigInt64(0,t,!0),new fe(pe.V.getInt32(0,!0),pe.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!kg.test(t))throw new Error("string is no integer");let[e,r,i]=wg(t);if(e){if(i>kd||i==kd&&r!=0)throw new Error("signed long too small")}else if(i>=kd)throw new Error("signed long too large");let n=new fe(r,i);return e?n.negate():n;case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");return t>0?new fe(t,t/_d):new fe(-t,-t/_d).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&kd)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new fe(e,t)}toString(){if(pe)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+Gu(t.lo,t.hi)}return Gu(this.lo,this.hi)}toBigInt(){return _g(pe),pe.V.setInt32(0,this.lo,!0),pe.V.setInt32(4,this.hi,!0),pe.V.getBigInt64(0,!0)}}fe.ZERO=new fe(0,0);const Rg={readUnknownField:!0,readerFactory:s=>new ok(s)};function ak(s){return s?Object.assign(Object.assign({},Rg),s):Rg}class ok{constructor(t,e){this.varint64=rk,this.uint32=ik,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=e!=null?e:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let t=this.uint32(),e=t>>>3,r=t&7;if(e<=0||r<0||r>5)throw new Error("illegal tag: field no "+e+" wire type "+r);return[e,r]}skip(t){let e=this.pos;switch(t){case Le.Varint:for(;this.buf[this.pos++]&128;);break;case Le.Bit64:this.pos+=4;case Le.Bit32:this.pos+=4;break;case Le.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Le.StartGroup:let i;for(;(i=this.tag()[1])!==Le.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(e,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return new fe(...this.varint64())}uint64(){return new lt(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new fe(t,e)}bool(){let[t,e]=this.varint64();return t!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new lt(this.sfixed32(),this.sfixed32())}sfixed64(){return new fe(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 t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function re(s,t){if(!s)throw new Error(t)}const ck=34028234663852886e22,dk=-34028234663852886e22,lk=4294967295,uk=2147483647,hk=-2147483648;function Za(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>uk||s<hk)throw new Error("invalid int 32: "+s)}function Cd(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>lk||s<0)throw new Error("invalid uint 32: "+s)}function Wu(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>ck||s<dk))throw new Error("invalid float 32: "+s)}const Ig={writeUnknownFields:!0,writerFactory:()=>new mk};function pk(s){return s?Object.assign(Object.assign({},Ig),s):Ig}class mk{constructor(t){this.stack=[],this.textEncoder=t!=null?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let i=0;i<this.chunks.length;i++)t+=this.chunks[i].length;let e=new Uint8Array(t),r=0;for(let i=0;i<this.chunks.length;i++)e.set(this.chunks[i],r),r+=this.chunks[i].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),e=this.stack.pop();if(!e)throw new Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,e){return this.uint32((t<<3|e)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(Cd(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return Za(t),Pg(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){Wu(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){Cd(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){Za(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return Za(t),t=(t<<1^t>>31)>>>0,Pg(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=fe.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=lt.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=fe.from(t);return ju(e.lo,e.hi,this.buf),this}sint64(t){let e=fe.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return ju(i,n,this.buf),this}uint64(t){let e=lt.from(t);return ju(e.lo,e.hi,this.buf),this}}const Ag={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Mg={ignoreUnknownFields:!1};function gk(s){return s?Object.assign(Object.assign({},Mg),s):Mg}function fk(s){return s?Object.assign(Object.assign({},Ag),s):Ag}const Og=Symbol.for("protobuf-ts/message-type");function Dg(s){let t=!1;const e=[];for(let r=0;r<s.length;r++){let i=s.charAt(r);i=="_"?t=!0:/\d/.test(i)?(e.push(i),t=!0):t?(e.push(i.toUpperCase()),t=!1):r==0?e.push(i.toLowerCase()):e.push(i)}return e.join("")}var O;(function(s){s[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64"})(O||(O={}));var Rs;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(Rs||(Rs={}));var Rd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(Rd||(Rd={}));function vk(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Dg(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Dg(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:Rd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function Sk(s){if(typeof s!="object"||s===null||!s.hasOwnProperty("oneofKind"))return!1;switch(typeof s.oneofKind){case"string":return s[s.oneofKind]===void 0?!1:Object.keys(s).length==2;case"undefined":return Object.keys(s).length==1;default:return!1}}class Tk{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}prepare(){if(this.data)return;const t=[],e=[],r=[];for(let i of this.fields)if(i.oneof)r.includes(i.oneof)||(r.push(i.oneof),t.push(i.oneof),e.push(i.oneof));else switch(e.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&t.push(i.localName);break;case"message":i.repeat&&t.push(i.localName);break;case"map":t.push(i.localName);break}this.data={req:t,known:e,oneofs:Object.values(r)}}is(t,e,r=!1){if(e<0)return!0;if(t==null||typeof t!="object")return!1;this.prepare();let i=Object.keys(t),n=this.data;if(i.length<n.req.length||n.req.some(o=>!i.includes(o))||!r&&i.some(o=>!n.known.includes(o)))return!1;if(e<1)return!0;for(const o of n.oneofs){const c=t[o];if(!Sk(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(l=>l.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,r,e))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(t[o.localName],o,r,e))return!1;return!0}field(t,e,r,i){let n=e.repeat;switch(e.kind){case"scalar":return t===void 0?e.opt:n?this.scalars(t,e.T,i,e.L):this.scalar(t,e.T,e.L);case"enum":return t===void 0?e.opt:n?this.scalars(t,O.INT32,i):this.scalar(t,O.INT32);case"message":return t===void 0?!0:n?this.messages(t,e.T(),r,i):this.message(t,e.T(),r,i);case"map":if(typeof t!="object"||t===null)return!1;if(i<2)return!0;if(!this.mapKeys(t,e.K,i))return!1;switch(e.V.kind){case"scalar":return this.scalars(Object.values(t),e.V.T,i,e.V.L);case"enum":return this.scalars(Object.values(t),O.INT32,i);case"message":return this.messages(Object.values(t),e.V.T(),r,i)}break}return!0}message(t,e,r,i){return r?e.isAssignable(t,i):e.is(t,i)}messages(t,e,r,i){if(!Array.isArray(t))return!1;if(i<2)return!0;if(r){for(let n=0;n<t.length&&n<i;n++)if(!e.isAssignable(t[n],i-1))return!1}else for(let n=0;n<t.length&&n<i;n++)if(!e.is(t[n],i-1))return!1;return!0}scalar(t,e,r){let i=typeof t;switch(e){case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:switch(r){case Rs.BIGINT:return i=="bigint";case Rs.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case O.BOOL:return i=="boolean";case O.STRING:return i=="string";case O.BYTES:return t instanceof Uint8Array;case O.DOUBLE:case O.FLOAT:return i=="number"&&!isNaN(t);default:return i=="number"&&Number.isInteger(t)}}scalars(t,e,r,i){if(!Array.isArray(t))return!1;if(r<2)return!0;if(Array.isArray(t)){for(let n=0;n<t.length&&n<r;n++)if(!this.scalar(t[n],e,i))return!1}return!0}mapKeys(t,e,r){let i=Object.keys(t);switch(e){case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case O.BOOL:return this.scalars(i.slice(0,r).map(n=>n=="true"?!0:n=="false"?!1:n),e,r);default:return this.scalars(i,e,r,Rs.STRING)}}}function ls(s,t){switch(t){case Rs.BIGINT:return s.toBigInt();case Rs.NUMBER:return s.toNumber();default:return s.toString()}}class yk{constructor(t){this.info=t}prepare(){var t;if(this.fMap===void 0){this.fMap={};const e=(t=this.info.fields)!==null&&t!==void 0?t:[];for(const r of e)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(t,e,r){if(!t){let i=qu(r);throw(i=="number"||i=="boolean")&&(i=r.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${e}`)}}read(t,e,r){this.prepare();const i=[];for(const[n,o]of Object.entries(t)){const c=this.fMap[n];if(!c){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${n}`);continue}const d=c.localName;let l;if(c.oneof){if(o===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(c.oneof),l=e[c.oneof]={oneofKind:d}}else l=e;if(c.kind=="map"){if(o===null)continue;this.assert(ek(o),c.name,o);const u=l[d];for(const[h,m]of Object.entries(o)){this.assert(m!==null,c.name+" map value",null);let v;switch(c.V.kind){case"message":v=c.V.T().internalJsonRead(m,r);break;case"enum":if(v=this.enum(c.V.T(),m,c.name,r.ignoreUnknownFields),v===!1)continue;break;case"scalar":v=this.scalar(m,c.V.T,c.V.L,c.name);break}this.assert(v!==void 0,c.name+" map value",m);let y=h;c.K==O.BOOL&&(y=y=="true"?!0:y=="false"?!1:y),y=this.scalar(y,c.K,Rs.STRING,c.name).toString(),u[y]=v}}else if(c.repeat){if(o===null)continue;this.assert(Array.isArray(o),c.name,o);const u=l[d];for(const h of o){this.assert(h!==null,c.name,null);let m;switch(c.kind){case"message":m=c.T().internalJsonRead(h,r);break;case"enum":if(m=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),m===!1)continue;break;case"scalar":m=this.scalar(h,c.T,c.L,c.name);break}this.assert(m!==void 0,c.name,o),u.push(m)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,r,l[d]);break;case"enum":if(o===null)continue;let u=this.enum(c.T(),o,c.name,r.ignoreUnknownFields);if(u===!1)continue;l[d]=u;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(t,e,r,i){if(t[0]=="google.protobuf.NullValue"&&re(e===null||e==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} only accepts null.`),e===null)return 0;switch(typeof e){case"number":return re(Number.isInteger(e),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${e}.`),e;case"string":let n=e;t[2]&&e.substring(0,t[2].length)===t[2]&&(n=e.substring(t[2].length));let o=t[1][n];return typeof o=="undefined"&&i?!1:(re(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}re(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof e}".`)}scalar(t,e,r,i){let n;try{switch(e){case O.DOUBLE:case O.FLOAT:if(t===null)return 0;if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""){n="empty string";break}if(typeof t=="string"&&t.trim().length!==t.length){n="extra whitespace";break}if(typeof t!="string"&&typeof t!="number")break;let o=Number(t);if(Number.isNaN(o)){n="not a number";break}if(!Number.isFinite(o)){n="too large or small";break}return e==O.FLOAT&&Wu(o),o;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:if(t===null)return 0;let c;if(typeof t=="number"?c=t:t===""?n="empty string":typeof t=="string"&&(t.trim().length!==t.length?n="extra whitespace":c=Number(t)),c===void 0)break;return e==O.UINT32?Cd(c):Za(c),c;case O.INT64:case O.SFIXED64:case O.SINT64:if(t===null)return ls(fe.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ls(fe.from(t),r);case O.FIXED64:case O.UINT64:if(t===null)return ls(lt.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ls(lt.from(t),r);case O.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case O.STRING:if(t===null)return"";if(typeof t!="string"){n="extra whitespace";break}try{encodeURIComponent(t)}catch(d){d="invalid UTF8";break}return t;case O.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return tk(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class Ek{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}write(t,e){const r={},i=t;for(const n of this.fields){if(!n.oneof){let l=this.field(n,i[n.localName],e);l!==void 0&&(r[e.useProtoFieldName?n.name:n.jsonName]=l);continue}const o=i[n.oneof];if(o.oneofKind!==n.localName)continue;const c=n.kind=="scalar"||n.kind=="enum"?Object.assign(Object.assign({},e),{emitDefaultValues:!0}):e;let d=this.field(n,o[n.localName],c);re(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){re(typeof e=="object"&&e!==null);const n={};switch(t.V.kind){case"scalar":for(const[d,l]of Object.entries(e)){const u=this.scalar(t.V.T,l,t.name,!1,!0);re(u!==void 0),n[d.toString()]=u}break;case"message":const o=t.V.T();for(const[d,l]of Object.entries(e)){const u=this.message(o,l,t.name,r);re(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){re(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);re(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){re(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let d=0;d<e.length;d++){const l=this.scalar(t.T,e[d],t.name,t.opt,!0);re(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){re(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);re(l!==void 0),n.push(l)}break;case"message":const c=t.T();for(let d=0;d<e.length;d++){const l=this.message(c,e[d],t.name,r);re(l!==void 0),n.push(l)}break}(r.emitDefaultValues||n.length>0||r.emitDefaultValues)&&(i=n)}else switch(t.kind){case"scalar":i=this.scalar(t.T,e,t.name,t.opt,r.emitDefaultValues);break;case"enum":i=this.enum(t.T(),e,t.name,t.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":i=this.message(t.T(),e,t.name,r);break}return i}enum(t,e,r,i,n,o){if(t[0]=="google.protobuf.NullValue")return!n&&!i?void 0:null;if(e===void 0){re(i);return}if(!(e===0&&!n&&!i))return re(typeof e=="number"),re(Number.isInteger(e)),o||!t[1].hasOwnProperty(e)?e:t[2]?t[2]+t[1][e]:t[1][e]}message(t,e,r,i){return e===void 0?i.emitDefaultValues?null:void 0:t.internalJsonWrite(e,i)}scalar(t,e,r,i,n){if(e===void 0){re(i);return}const o=n||i;switch(t){case O.INT32:case O.SFIXED32:case O.SINT32:return e===0?o?0:void 0:(Za(e),e);case O.FIXED32:case O.UINT32:return e===0?o?0:void 0:(Cd(e),e);case O.FLOAT:Wu(e);case O.DOUBLE:return e===0?o?0:void 0:(re(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case O.STRING:return e===""?o?"":void 0:(re(typeof e=="string"),e);case O.BOOL:return e===!1?o?!1:void 0:(re(typeof e=="boolean"),e);case O.UINT64:case O.FIXED64:re(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=lt.from(e);return c.isZero()&&!o?void 0:c.toString();case O.INT64:case O.SFIXED64:case O.SINT64:re(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=fe.from(e);return d.isZero()&&!o?void 0:d.toString();case O.BYTES:return re(e instanceof Uint8Array),e.byteLength?sk(e):o?"":void 0}}}function Ju(s,t=Rs.STRING){switch(s){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:return ls(lt.ZERO,t);case O.INT64:case O.SFIXED64:case O.SINT64:return ls(fe.ZERO,t);case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array(0);case O.STRING:return"";default:return 0}}class bk{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,i){this.prepare();const n=i===void 0?t.len:t.pos+i;for(;t.pos<n;){const[o,c]=t.tag(),d=this.fieldNoToField.get(o);if(!d){let m=r.readUnknownField;if(m=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let v=t.skip(c);m!==!1&&(m===!0?wd.onRead:m)(this.info.typeName,e,o,c,v);continue}let l=e,u=d.repeat,h=d.localName;switch(d.oneof&&(l=l[d.oneof],l.oneofKind!==h&&(l=e[d.oneof]={oneofKind:h})),d.kind){case"scalar":case"enum":let m=d.kind=="enum"?O.INT32:d.T,v=d.kind=="scalar"?d.L:void 0;if(u){let R=l[h];if(c==Le.LengthDelimited&&m!=O.STRING&&m!=O.BYTES){let P=t.uint32()+t.pos;for(;t.pos<P;)R.push(this.scalar(t,m,v))}else R.push(this.scalar(t,m,v))}else l[h]=this.scalar(t,m,v);break;case"message":if(u){let R=l[h],P=d.T().internalBinaryRead(t,t.uint32(),r);R.push(P)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[y,w]=this.mapEntry(d,t,r);l[h][y]=w;break}}}mapEntry(t,e,r){let i=e.uint32(),n=e.pos+i,o,c;for(;e.pos<n;){let[d,l]=e.tag();switch(d){case 1:t.K==O.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,Rs.STRING);break;case 2:switch(t.V.kind){case"scalar":c=this.scalar(e,t.V.T,t.V.L);break;case"enum":c=e.int32();break;case"message":c=t.V.T().internalBinaryRead(e,e.uint32(),r);break}break;default:throw new Error(`Unknown field ${d} (wire type ${l}) in map entry for ${this.info.typeName}#${t.name}`)}}if(o===void 0){let d=Ju(t.K);o=t.K==O.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=Ju(t.V.T,t.V.L);break;case"enum":c=0;break;case"message":c=t.V.T().create();break}return[o,c]}scalar(t,e,r){switch(e){case O.INT32:return t.int32();case O.STRING:return t.string();case O.BOOL:return t.bool();case O.DOUBLE:return t.double();case O.FLOAT:return t.float();case O.INT64:return ls(t.int64(),r);case O.UINT64:return ls(t.uint64(),r);case O.FIXED64:return ls(t.fixed64(),r);case O.FIXED32:return t.fixed32();case O.BYTES:return t.bytes();case O.UINT32:return t.uint32();case O.SFIXED32:return t.sfixed32();case O.SFIXED64:return ls(t.sfixed64(),r);case O.SINT32:return t.sint32();case O.SINT64:return ls(t.sint64(),r)}}}class wk{constructor(t){this.info=t}prepare(){if(!this.fields){const t=this.info.fields?this.info.fields.concat():[];this.fields=t.sort((e,r)=>e.no-r.no)}}write(t,e,r){this.prepare();for(const n of this.fields){let o,c,d=n.repeat,l=n.localName;if(n.oneof){const u=t[n.oneof];if(u.oneofKind!==l)continue;o=u[l],c=!0}else o=t[l],c=!1;switch(n.kind){case"scalar":case"enum":let u=n.kind=="enum"?O.INT32:n.T;if(d)if(re(Array.isArray(o)),d==Rd.PACKED)this.packed(e,u,n.no,o);else for(const h of o)this.scalar(e,u,n.no,h,!0);else o===void 0?re(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){re(Array.isArray(o));for(const h of o)this.message(e,r,n.T(),n.no,h)}else this.message(e,r,n.T(),n.no,o);break;case"map":re(typeof o=="object"&&o!==null);for(const[h,m]of Object.entries(o))this.mapEntry(e,r,n,h,m);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?wd.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,Le.LengthDelimited),t.fork();let o=i;switch(r.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:o=Number.parseInt(i);break;case O.BOOL:re(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(t,r.K,1,o,!0),r.V.kind){case"scalar":this.scalar(t,r.V.T,2,n,!0);break;case"enum":this.scalar(t,O.INT32,2,n,!0);break;case"message":this.message(t,e,r.V.T(),2,n);break}t.join()}message(t,e,r,i,n){n!==void 0&&(r.internalBinaryWrite(n,t.tag(i,Le.LengthDelimited).fork(),e),t.join())}scalar(t,e,r,i,n){let[o,c,d]=this.scalarInfo(e,i);(!d||n)&&(t.tag(r,o),t[c](i))}packed(t,e,r,i){if(!i.length)return;re(e!==O.BYTES&&e!==O.STRING),t.tag(r,Le.LengthDelimited),t.fork();let[,n]=this.scalarInfo(e);for(let o=0;o<i.length;o++)t[n](i[o]);t.join()}scalarInfo(t,e){let r=Le.Varint,i,n=e===void 0,o=e===0;switch(t){case O.INT32:i="int32";break;case O.STRING:o=n||!e.length,r=Le.LengthDelimited,i="string";break;case O.BOOL:o=e===!1,i="bool";break;case O.UINT32:i="uint32";break;case O.DOUBLE:r=Le.Bit64,i="double";break;case O.FLOAT:r=Le.Bit32,i="float";break;case O.INT64:o=n||fe.from(e).isZero(),i="int64";break;case O.UINT64:o=n||lt.from(e).isZero(),i="uint64";break;case O.FIXED64:o=n||lt.from(e).isZero(),r=Le.Bit64,i="fixed64";break;case O.BYTES:o=n||!e.byteLength,r=Le.LengthDelimited,i="bytes";break;case O.FIXED32:r=Le.Bit32,i="fixed32";break;case O.SFIXED32:r=Le.Bit32,i="sfixed32";break;case O.SFIXED64:o=n||fe.from(e).isZero(),r=Le.Bit64,i="sfixed64";break;case O.SINT32:i="sint32";break;case O.SINT64:o=n||fe.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function Pk(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Og,{value:s});for(let e of s.fields){let r=e.localName;if(!e.opt)if(e.oneof)t[e.oneof]={oneofKind:void 0};else if(e.repeat)t[r]=[];else switch(e.kind){case"scalar":t[r]=Ju(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function Ku(s,t,e){let r,i=e,n;for(let o of s.fields){let c=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(r=d[c],n=t[o.oneof],n.oneofKind=d.oneofKind,r==null){delete n[c];continue}}else if(r=i[c],n=t,r==null)continue;switch(o.repeat&&(n[c].length=r.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=r[l];else n[c]=r;break;case"message":let d=o.T();if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=d.create(r[l]);else n[c]===void 0?n[c]=d.create(r):d.mergePartial(n[c],r);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(n[c],r);break;case"message":let l=o.V.T();for(let u of Object.keys(r))n[c][u]=l.create(r[u]);break}break}}}function _k(s,t,e){if(t===e)return!0;if(!t||!e)return!1;for(let r of s.fields){let i=r.localName,n=r.oneof?t[r.oneof][i]:t[i],o=r.oneof?e[r.oneof][i]:e[i];switch(r.kind){case"enum":case"scalar":let c=r.kind=="enum"?O.INT32:r.T;if(!(r.repeat?Vg(c,n,o):Ng(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Lg(r.V.T(),Id(n),Id(o)):Vg(r.V.kind=="enum"?O.INT32:r.V.T,Id(n),Id(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Lg(d,n,o):d.equals(n,o)))return!1;break}}return!0}const Id=Object.values;function Ng(s,t,e){if(t===e)return!0;if(s!==O.BYTES)return!1;let r=t,i=e;if(r.length!==i.length)return!1;for(let n=0;n<r.length;n++)if(r[n]!=i[n])return!1;return!0}function Vg(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Ng(s,t[r],e[r]))return!1;return!0}function Lg(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!s.equals(t[r],e[r]))return!1;return!0}const xg=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),kk=xg[Og]={};class S{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(vk),this.options=r!=null?r:{},kk.value=this,this.messagePrototype=Object.create(null,xg),this.refTypeCheck=new Tk(this),this.refJsonReader=new yk(this),this.refJsonWriter=new Ek(this),this.refBinReader=new bk(this),this.refBinWriter=new wk(this)}create(t){let e=Pk(this);return t!==void 0&&Ku(this,e,t),e}clone(t){let e=this.create();return Ku(this,e,t),e}equals(t,e){return _k(this,t,e)}is(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!1)}isAssignable(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!0)}mergePartial(t,e){Ku(this,t,e)}fromBinary(t,e){let r=ak(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,gk(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,fk(e))}toJsonString(t,e){var r;let i=this.toJson(t,e);return JSON.stringify(i,null,(r=e==null?void 0:e.prettySpaces)!==null&&r!==void 0?r:0)}toBinary(t,e){let r=pk(e);return this.internalBinaryWrite(t,r.writerFactory(),r).finish()}internalJsonRead(t,e,r){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let i=r!=null?r:this.create();return this.refJsonReader.read(t,i,e),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${qu(t)}.`)}internalJsonWrite(t,e){return this.refJsonWriter.write(t,e)}internalBinaryWrite(t,e,r){return this.refBinWriter.write(t,e,r),e}internalBinaryRead(t,e,r,i){let n=i!=null?i:this.create();return this.refBinReader.read(t,n,r,e),n}}var Ks;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(Ks||(Ks={}));var zs;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(zs||(zs={}));class Ck extends S{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Ug=new Ck;class Rk extends S{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const Ik=new Rk;class Ak extends S{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new Ak;class Mk extends S{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Ks]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const us=new Mk;class Ok extends S{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const Dk=new Ok;class Nk extends S{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:()=>us},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>Dk}])}}const Vk=new Nk;class Lk extends S{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const xk=new Lk;class Uk extends S{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>us},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const $g=new Uk;class $k extends S{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>us}])}}const Bk=new $k;class Fk extends S{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>us}])}}new Fk;class Hk extends S{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 qk=new Hk;class jk extends S{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 Gk=new jk;class Wk extends S{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new Wk;class Jk extends S{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new Jk;class Kk extends S{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",zs]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>Ug}])}}const eo=new Kk;class zk extends S{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>eo},{no:3,name:"producer_track",kind:"message",T:()=>Gk},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const Yk=new zk;class Qk extends S{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>Yk}}])}}const Bg=new Qk;class Xk extends S{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>qg},{no:2,name:"receiver",kind:"message",T:()=>qg}])}}const Fg=new Xk;class Zk extends S{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Ug},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>Ik}])}}const Hg=new Zk;class eC extends S{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Hg},{no:2,name:"video",kind:"message",T:()=>Hg}])}}const qg=new eC;class tC extends S{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const sC=new tC;class rC extends S{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const jg=new rC;class iC extends S{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 nC=new iC;class aC extends S{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:()=>nC},{no:9,name:"capabilities",kind:"message",T:()=>Fg}])}}const oC=new aC;class cC extends S{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const dC=new cC;class lC extends S{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const uC=new lC;class hC extends S{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 hC;class pC extends S{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>sC},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>jg}])}}const mC=new pC;class gC extends S{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>mC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const fC=new gC;class vC extends S{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>jg},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const SC=new vC;class TC extends S{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>SC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const yC=new TC;class EC extends S{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:()=>us},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const bC=new EC;class wC extends S{constructor(){super("media.edge.SelectedPeersRequest",[])}}new wC;class PC extends S{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const _C=new PC;class kC extends S{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Ad=new kC;class CC extends S{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new CC;class RC extends S{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>us},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const IC=new RC;class AC extends S{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>us},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const MC=new AC;class OC extends S{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new OC;class DC extends S{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Gg=new DC;class NC extends S{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const VC=new NC;class LC extends S{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 xC=new LC;class UC extends S{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 $C=new UC;class BC extends S{constructor(){super("media.edge.GetRoomStateResponse",[{no:1,name:"display_title",kind:"scalar",T:9},{no:2,name:"locked_mode",kind:"scalar",T:8},{no:3,name:"room_uuid",kind:"scalar",T:9},{no:4,name:"room_name",kind:"scalar",T:9},{no:5,name:"current_peer_id",kind:"scalar",T:9},{no:6,name:"is_recording",kind:"scalar",opt:!0,T:8},{no:7,name:"recorder_participant_id",kind:"scalar",opt:!0,T:9},{no:8,name:"pinned_peer_ids",kind:"scalar",repeat:2,T:9}])}}const FC=new BC;class HC extends S{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const qC=new HC;class jC extends S{constructor(){super("media.edge.EmptyResponse",[])}}new jC;class GC extends S{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>eo},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>Fg}])}}const Wg=new GC;class WC extends S{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 zu=new WC;class JC extends S{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const KC=new JC;class zC extends S{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>KC}])}}const Jg=new zC;class YC extends S{constructor(){super("media.edge.PeerJoinResponse",[])}}new YC;class QC extends S{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>FC},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Wg},{no:3,name:"selected_peers",kind:"message",T:()=>zu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Yu=new QC;class XC extends S{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const ZC=new XC;class eR extends S{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Bg}])}}new eR;class tR extends S{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Bg},{no:3,name:"description",kind:"message",T:()=>us}])}}const sR=new tR;class rR extends S{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:()=>us}])}}const iR=new rR;class nR extends S{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>qk}])}}new nR;class aR extends S{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new aR;class oR extends S{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new oR;class cR extends S{constructor(){super("media.edge.ProducerToggleResponse",[])}}new cR;class dR extends S{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new dR;class lR extends S{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>us}])}}const uR=new lR;class hR extends S{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>us}])}}const pR=new hR;class mR extends S{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new mR;class gR extends S{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new gR;class fR extends S{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new fR;class vR extends S{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const SR=new vR;class TR extends S{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const yR=new TR;class ER extends S{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const bR=new ER;class wR extends S{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Wg}])}}const Kg=new wR;class PR extends S{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const zg=new PR;class _R extends S{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>zg},{no:3,name:"screenshare",kind:"message",T:()=>zg}])}}const kR=new _R;class CR extends S{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>$g},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>kR}])}}new CR;class RR extends S{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>eo}])}}const IR=new RR;class AR extends S{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>eo},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Yg=new AR;class MR extends S{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>eo}])}}const OR=new MR;class DR extends S{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Qu=new DR;class NR extends S{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Qg=new NR;class VR extends S{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new VR;class LR extends S{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new LR;class xR extends S{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new xR;class UR extends S{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new UR;class $R extends S{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new $R;class BR extends S{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new BR;class FR extends S{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 Xu=new FR;class HR extends S{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 HR;class qR extends S{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const jR=new qR;var vi;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(vi||(vi={}));var Ys;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(Ys||(Ys={}));var Zu;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Zu||(Zu={}));var eh;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(eh||(eh={}));var Md;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Md||(Md={}));class GR extends S{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 WR=new GR;class JR extends S{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",Ys,"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:()=>WR}])}}const Od=new JR;class KR extends S{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Od}])}}const Cn=new KR;class zR extends S{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",Ys,"STAGE_TYPE_"]}])}}const Xg=new zR;class YR extends S{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 QR=new YR;class XR extends S{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Od}])}}const th=new XR;class ZR extends S{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Zg=new ZR;class eI extends S{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:()=>sI},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const ef=new eI;class tI extends S{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",vi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const sI=new tI;class rI extends S{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>ef}])}}const tf=new rI;class iI extends S{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const sf=new iI;class nI extends S{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 nI;class aI extends S{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Od},{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",Md,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const oI=new aI;class cI extends S{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Od},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const dI=new cI;class lI extends S{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>ef}])}}new lI;class uI extends S{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new uI;class hI extends S{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 sh=new hI;class pI extends S{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 mI=new pI;class gI extends S{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:()=>mI}])}}const rf=new gI;class fI extends S{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>rf},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>rf}])}}const vI=new fI;class SI extends S{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const TI=new SI;class yI extends S{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>TI}])}}const EI=new yI;class bI extends S{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:()=>sh}])}}const wI=new bI;class PI extends S{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>wI}])}}const nf=new PI;class _I extends S{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 kI=new _I;class CI extends S{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>kI}])}}new CI;class RI extends S{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const II=new RI;class AI extends S{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>II}])}}const MI=new AI;class OI extends S{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>VI}])}}const DI=new OI;class NI extends S{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:()=>sh}])}}const VI=new NI;class LI extends S{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 xI=new LI;class UI extends S{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:()=>xI}])}}const $I=new UI;class BI extends S{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:()=>sh}])}}const af=new BI;class FI extends S{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>af}])}}new FI;class HI extends S{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 qI=new HI;class jI extends S{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>JI}])}}const GI=new jI;class WI extends S{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 JI=new WI;class KI extends S{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const of=new KI;class zI extends S{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",eh,"BROADCAST_TYPE_"]}])}}const to=new zI;class YI extends S{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const QI=new YI;class XI extends S{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ZI=new XI;class e0 extends S{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const t0=new e0;class s0 extends S{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>t0}])}}const cf=new s0;class r0 extends S{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 df=new r0;var rh;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(rh||(rh={}));var Ir;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(Ir||(Ir={}));class i0 extends S{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 n0=new i0;class a0 extends S{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 o0=new a0;class c0 extends S{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 d0=new c0;class l0 extends S{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 u0=new l0;class h0 extends S{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>d0},{no:2,name:"private",kind:"message",T:()=>u0}])}}const p0=new h0;class m0 extends S{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 g0=new m0;class f0 extends S{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ir,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ir,"STREAM_PERMISSION_TYPE_"]}])}}const ih=new f0;class v0 extends S{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>ih},{no:2,name:"audio",kind:"message",T:()=>ih},{no:3,name:"screenshare",kind:"message",T:()=>ih}])}}const S0=new v0;class T0 extends S{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>n0},{no:2,name:"plugins",kind:"message",T:()=>o0},{no:3,name:"chat",kind:"message",T:()=>p0},{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",rh,"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",Zu,"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:()=>g0},{no:23,name:"media",kind:"message",T:()=>S0}])}}const nh=new T0;class y0 extends S{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const E0=new y0;class b0 extends S{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 w0=new b0;class P0 extends S{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>w0}])}}const _0=new P0;class k0 extends S{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>nh}])}}const lf=new k0;class C0 extends S{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>lf}])}}const R0=new C0;class I0 extends S{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>lf}])}}const uf=new I0;class A0 extends S{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const M0=new A0;class O0 extends S{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>M0},{no:2,name:"patch",kind:"message",T:()=>nh}])}}new O0;class D0 extends S{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>nh}])}}new D0;class N0 extends S{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 Ar=new N0;class V0 extends S{constructor(){super("socket.chat.GetPaginatedChatMessageFilters",[{no:1,name:"pinned",kind:"scalar",oneof:"filters",T:8},{no:2,name:"user_id",kind:"scalar",oneof:"filters",T:9}])}}const L0=new V0;class x0 extends S{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},{no:6,name:"filters",kind:"message",T:()=>L0}])}}const U0=new x0;class $0 extends S{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ar},{no:2,name:"next",kind:"scalar",T:8}])}}const B0=new $0;class F0 extends S{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ar}])}}const hf=new F0;class H0 extends S{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const q0=new H0;class j0 extends S{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ar}])}}const ah=new j0;class G0 extends S{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 W0=new G0;class J0 extends S{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ar}])}}const oh=new J0;class K0 extends S{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}])}}new K0;class z0 extends S{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ar}])}}new z0;class Y0 extends S{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 Q0=new Y0;class X0 extends S{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 Z0=new X0;class eA extends S{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},{no:4,name:"message",kind:"message",T:()=>Ar}])}}const Dd=new eA;class tA extends S{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ar}])}}const Nd=new tA;class sA extends S{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 rA=new sA;class iA extends S{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 Vd=new iA;class nA extends S{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 aA=new nA;class oA extends S{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}])}}new oA;class cA extends S{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new cA;class dA extends S{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}])}}new dA;class lA extends S{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}])}}new lA;class uA extends S{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new uA;class hA extends S{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new hA;class pA extends S{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ar},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const mA=new pA;class gA extends S{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:()=>mA},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const fA=new gA;class vA extends S{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>fA}])}}new vA;class SA extends S{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 TA=new SA;class yA extends S{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>TA}])}}new yA;class EA extends S{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new EA;class bA extends S{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new bA;class wA extends S{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new wA;class PA extends S{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new PA;class _A extends S{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}])}}new _A;class kA extends S{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}])}}new kA;class CA extends S{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new CA;class RA extends S{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}])}}new RA;class IA extends S{constructor(){super("socket.plugin.StoreKeys",[{no:1,name:"store_key",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",opt:!0,T:12}])}}const ch=new IA;class AA extends S{constructor(){super("socket.plugin.PluginStoreInsertKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"insert_keys",kind:"message",repeat:1,T:()=>ch}])}}const MA=new AA;class OA extends S{constructor(){super("socket.plugin.PluginStoreGetKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"get_keys",kind:"message",repeat:1,T:()=>ch}])}}const DA=new OA;class NA extends S{constructor(){super("socket.plugin.PluginStoreDeleteKeysRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9},{no:3,name:"delete_keys",kind:"message",repeat:1,T:()=>ch}])}}const VA=new NA;class LA extends S{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new LA;class xA extends S{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const UA=new xA;class $A extends S{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>UA}])}}new $A;class BA extends S{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new BA;class FA extends S{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 HA=new FA;class qA extends S{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:()=>HA}])}}const pf=new qA;class jA extends S{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new jA;class GA extends S{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const mf=new GA;class WA extends S{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const gf=new WA;class JA extends S{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 KA=new JA;class zA extends S{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>KA}])}}const dh=new zA;class YA extends S{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const QA=new YA;class XA extends S{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ZA=new XA;class eM extends S{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ff=new eM;class tM extends S{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:()=>rM},{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 vf=new tM;class sM extends S{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:()=>nM}])}}const rM=new sM;class iM extends S{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const nM=new iM;class aM extends S{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 oM=new aM;class cM extends S{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 dM=new cM;class lM extends S{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>vf}])}}const lh=new lM;class uM extends S{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>vf}])}}const hM=new uM;class pM extends S{constructor(){super("socket.recording.RecordingEvent",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",vi]}])}}const Sf=new pM;class mM extends S{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 t=this.create(),e=Date.now();return t.seconds=fe.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(fe.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=fe.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=fe.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>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(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let n=(t.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+qu(t)+".");let i=t.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 n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>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 r||(r=this.create()),r.seconds=fe.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new mM;class gM extends S{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const uh=new gM;class fM extends S{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>uh}])}}new fM;class vM extends S{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>uh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>uh}])}}new vM;const SM=0,TM=1,yM=2,EM=3,bM=5,wM={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToEntity:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43,livestreamingInvoked:44},PM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},_M={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},kM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Tf={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,updateConsumersSimulcastConfig:8,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},CM={getUserPresets:0,updateUserPreset:1};function so(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function yf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const U=so(SM,wM),We=so(TM,PM),Qs=so(yM,_M),Xs=so(EM,kM),Mr=yf(Tf,16777216),hs=yf(Tf,50331648),Ld=so(bM,CM);var RM=Object.defineProperty,IM=Object.getOwnPropertyDescriptor,Or=(s,t,e,r)=>{for(var i=r>1?void 0:r?IM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&RM(t,e,i),i},zt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(zt||{});class Zs{constructor(t,e){g(this,Lt,void 0);g(this,Hn,void 0);f(this,Lt,e),f(this,Hn,t)}get telemetry(){return a(this,Hn).getValue("telemetry")}get logger(){return a(this,Hn).getValue("logger")}getChatMessages(){return a(this,Lt).sendMessagePromise(We.getMessages)}async getChatMessagesPaginated(t,e,r,i){const n={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await a(this,Lt).sendMessagePromise(We.getPaginatedMessages,U0.toBinary(n));return o.payload?B0.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,Lt).sendMessage(We.sendMessageToRoom,q0.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,Lt).sendMessage(We.sendMessageToPeers,W0.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const n={chatId:t,payloadType:r,payload:e};i!==void 0&&(n.pinned=i);const o=await a(this,Lt).sendMessagePromise(We.editMessage,Q0.toBinary(n));return Nd.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,Lt).sendMessagePromise(We.deleteMessage,rA.toBinary(e));return{id:Vd.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,n,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.limit)!=null?n:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await a(this,Lt).sendMessagePromise(We.searchChannelMessages,aA.toBinary(r));return hf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,Lt).sendMessagePromise(We.pinMessage,Z0.toBinary(r));return Dd.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case We.sendMessageToRoom:{r=ah.fromBinary.bind(ah),i=ah.create();break}case We.sendMessageToPeers:{r=oh.fromBinary.bind(oh),i=oh.create();break}case We.editMessage:{r=Nd.fromBinary.bind(Nd),i=Nd.create();break}case We.pinMessage:{r=Dd.fromBinary.bind(Dd),i=Dd.create();break}case We.deleteMessage:{r=Vd.fromBinary.bind(Vd),i=Vd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,Lt).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}Lt=new WeakMap,Hn=new WeakMap,Or([E.trace("SocketService.getChatMessages")],Zs.prototype,"getChatMessages",1),Or([E.trace("SocketService.getChatMessagesPaginated")],Zs.prototype,"getChatMessagesPaginated",1),Or([E.trace("SocketService.sendMessageToRoom")],Zs.prototype,"sendMessageToRoom",1),Or([E.trace("SocketService.sendMessageToPeers")],Zs.prototype,"sendMessageToPeers",1),Or([E.trace("SocketService.sendMessage")],Zs.prototype,"sendMessage",1),Or([E.trace("SocketService.editMessage")],Zs.prototype,"editMessage",1),Or([E.trace("SocketService.deleteMessage")],Zs.prototype,"deleteMessage",1),Or([E.trace("SocketService.searchMessages")],Zs.prototype,"searchMessages",1);function AM(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Is(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Is(e));const t={};return Object.keys(s).forEach(e=>{const r=hu(e)?e:AM(e);t[r]=Is(s[e])}),t}function MM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Ef(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Ef(e));const t={};return Object.keys(s).forEach(e=>{const r=hu(e)?e:MM(e);t[r]=s[e]}),t}class hh extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);p(this,"status");p(this,"response");p(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(this.status=e.status,this.response=e,this.isTimeout=!1),this.name="RequestError"}get isHttpError(){return this.status!==void 0}get isNetworkError(){return this.status===void 0&&!this.isTimeout}}class bf{constructor(t){p(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.toString()}`}return i}async request(t){var h;const e=((h=t.method)==null?void 0:h.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const m=new AbortController,v=setTimeout(()=>m.abort(),d);c.signal=m.signal;const y=await fetch(r,c);clearTimeout(v);let w=null;const R=y.headers.get("content-type");R&&R.includes("application/json")?w=await y.json():w=await y.text();const P={};y.headers.forEach(($,x)=>{P[x]=$});const N={data:w,status:y.status,statusText:y.statusText,headers:P,config:t};if(!y.ok)throw N;return N}catch(m){if(m instanceof Error&&l>0)return await new Promise(v=>setTimeout(v,u)),this.defaults.baseURL===fi.apiBase.prod?this.defaults.baseURL=fi.apiBase.prodAlternate:this.defaults.baseURL===fi.apiBase.prodAlternate&&(this.defaults.baseURL=fi.apiBase.prod),this.request({...t,retry:l-1});throw m}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const OM=3,DM=30,NM=8e3;class VM{constructor(t,e){p(this,"fetchClient");p(this,"requests");p(this,"roomName");p(this,"roomUUID");p(this,"authToken");p(this,"organizationId");p(this,"iceServers");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=NM,retry:i=OM,retryDelay:n=DM,baseURL:o=fi.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new bf({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new bf({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var m,v,y,w,R;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const P=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:P.status,statusText:P.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),P}catch(P){if(!P)throw new C("Unknown network error occurred","0011");if(P instanceof C||P instanceof hh)throw P;((m=P.config)==null?void 0:m.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:P,networkCall:{status:P.status,statusText:P.statusText,baseURL:((v=P.config)==null?void 0:v.baseURL)||this.requests.defaults.baseURL,url:(y=P.config)==null?void 0:y.url,retries:(w=P.config)==null?void 0:w.retry,method:(R=P.config)==null?void 0:R.method,isOnline:navigator.onLine?"online":"offline"}});const N=P instanceof Error&&P.message||"Network request failed";throw new C(N,"0011"),new hh(P)}}}get peerId(){return this.context.getValue("peerId")}get logger(){return this.context.getValue("logger")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var LM=Object.defineProperty,xM=Object.getOwnPropertyDescriptor,er=(s,t,e,r)=>{for(var i=r>1?void 0:r?xM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&LM(t,e,i),i};class As extends VM{constructor(e,r){super(e,r);p(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPresignedUrls(e){const r=Pn(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:n,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:n,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=Is(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=Is((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return Is(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...Ef(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new C("Cant fetch transcript s3 url","1801")}}}er([E.trace("APIClient.getICEServers")],As.prototype,"getICEServers",1),er([E.trace("APIClient.startLivestreaming")],As.prototype,"startLivestreaming",1),er([E.trace("APIClient.stopLivestreaming")],As.prototype,"stopLivestreaming",1),er([E.trace("APIClient.getActiveLivestream")],As.prototype,"getActiveLivestream",1),er([E.trace("APIClient.getUserDetails")],As.prototype,"getUserDetails",1),er([E.trace("APIClient.startRecording")],As.prototype,"startRecording",1),er([E.trace("APIClient.stopRecording")],As.prototype,"updateRecording",1),er([E.trace("APIClient.getActiveRecording")],As.prototype,"getActiveRecording",1),er([E.trace("APIClient.getActiveTranscript")],As.prototype,"getActiveTranscript",1);let ph;function UM(s,t){return ph=new As(s,t),ph}function wt(){return ph}const Rn={maxInvocations:5,period:1};function Dt(s,t){return function(e,r,i){const n=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var $M=Object.defineProperty,BM=Object.getOwnPropertyDescriptor,Ms=(s,t,e,r)=>{for(var i=r>1?void 0:r?BM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$M(t,e,i),i};const FM=["text","image","file","custom","poll"],xd={maxInvocations:180,period:60};let Yt=(Vv=class extends Ot{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,hl);g(this,_o);p(this,"messages");g(this,se,void 0);g(this,Ai,void 0);g(this,it,void 0);g(this,qn,void 0);p(this,"maxTextLimit",2e3);f(this,qn,t),f(this,it,e),f(this,se,r),f(this,Ai,i),this.messages=[]}get telemetry(){return a(this,qn).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,n,o,c,d,l;if(t.length>this.maxTextLimit)throw new C("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,se).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,se).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new C("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,se).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,se).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new C("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new C("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,se).id),r=a(this,Ai).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,se).userId)),a(this,it).sendMessage(t,zt.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,se).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,se).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,se).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,se).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const u=wt(),{getLocation:h,putLocation:m}=await u.getPresignedUrls(t.name);await u.uploadFile(t,m);let v=[];e&&e.length>0&&(e.push(a(this,se).id),v=a(this,Ai).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),v.push(a(this,se).userId)),a(this,it).sendMessage(h,zt.IMAGE,e)}catch(u){throw new C("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,n,o,c,d;if(e&&e.length>0){if(!((r=a(this,se).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,se).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,se).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=wt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let m=[];e&&e.length>0&&(e.push(a(this,se).id),m=a(this,Ai).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),m.push(a(this,se).userId));const v=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,it).sendMessage(v,zt.FILE,e)}catch(l){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return xd}updateRateLimits(t,e){xd.maxInvocations=t,xd.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,m,v,y,w,R,P,N,$;if(e&&e.length>0){if(!((n=a(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,se).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,se).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,se).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,se).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((v=(m=a(this,se).permissions)==null?void 0:m.chatPublic)!=null&&v.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async x=>{try{if(typeof x=="string")return{link:x};const H=wt(),{getLocation:F,putLocation:Z}=await H.getPresignedUrls(x.name);return await H.uploadFile(x,Z),{link:F,type:x.type,name:x.name,size:x.size}}catch(H){throw new C("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((w=(y=t.files)!=null?y:[])==null?void 0:w.map(async x=>r(x))),images:await Promise.all((P=(R=t.images)!=null?R:[])==null?void 0:P.map(async x=>r(x))),videos:await Promise.all(($=(N=t.videos)!=null?N:[])==null?void 0:$.map(async x=>r(x)))};a(this,it).sendMessage(JSON.stringify(i),zt.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,se).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,se).permissions)==null?void 0:n.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,it).editMessage(t,e,zt.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,se).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,se).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=wt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,it).editMessage(t,l,zt.IMAGE)}catch(d){throw new C("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,se).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,se).permissions)==null?void 0:n.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=wt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,it).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),zt.FILE)}catch(c){throw new C("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){a(this,it).deleteMessage(t)}async pin(t){if(!a(this,_o,Xh))throw new C("Can`t pin message without joining room","0505");try{await a(this,it).setPinState(t,!0)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,_o,Xh))throw new C("Can`t unpin message without joining room","0505");try{await a(this,it).setPinState(t,!1)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,it).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>ro.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,it).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>ro.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,it).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>ro.formatSocketPeerMessage(o))}},se=new WeakMap,Ai=new WeakMap,it=new WeakMap,qn=new WeakMap,hl=new WeakSet,eS=function(){return a(this,qn).getValue("connectionHandler")},_o=new WeakSet,Xh=function(){return a(this,hl,eS).socketJoined===!0},Vv);Ms([E.trace("Chat.sendTextMessage"),Dt(xd)],Yt.prototype,"sendTextMessage",1),Ms([E.trace("Chat.sendImageMessage"),Dt({maxInvocations:20,period:60})],Yt.prototype,"sendImageMessage",1),Ms([E.trace("Chat.sendFileMessage"),Dt({maxInvocations:20,period:60})],Yt.prototype,"sendFileMessage",1),Ms([E.trace("Chat.sendMessage"),Dt({maxInvocations:180,period:60})],Yt.prototype,"sendMessage",1),Ms([E.trace("Chat.editTextMessage")],Yt.prototype,"editTextMessage",1),Ms([E.trace("Chat.editImageMessage")],Yt.prototype,"editImageMessage",1),Ms([E.trace("Chat.editFileMessage")],Yt.prototype,"editFileMessage",1),Ms([E.trace("Chat.editMessage")],Yt.prototype,"editMessage",1),Ms([E.trace("Chat.deleteMessage")],Yt.prototype,"deleteMessage",1),Yt=Ms([dt("0500")],Yt);var HM=Object.defineProperty,qM=Object.getOwnPropertyDescriptor,jM=(s,t,e,r)=>{for(var i=r>1?void 0:r?qM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&HM(t,e,i),i};const Dr=(Lv=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");g(this,Mi,void 0);f(this,Mi,s),this.chatSocketHandler=t,this.chat=new Yt(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Mi).getValue("telemetry")}get logger(){return a(this,Mi).getValue("logger")}static async init(s,t,e,r){return new Dr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:FM[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case zt.TEXT:{e.message=s.payload;break}case zt.IMAGE:{e.link=s.payload;break}case zt.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case zt.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Dr.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM")return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=hf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Dr.formatSocketPeerMessage(e))}setupEvents(){a(this,Mi).getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(We.sendMessageToRoom,s=>{if(!s.message)return;const t=Dr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.sendMessageToPeers,s=>{const t=Dr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.editMessage,s=>{if(!s.message)return;const t=Dr.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(We.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(We.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=Dr.formatSocketPeerMessage(s.message);t!==-1&&(this.chat.messages[t]=e),this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}),s.pinned?this.chat.emit("pinMessage",{message:e,messages:this.chat.messages}):this.chat.emit("unpinMessage",{message:e,messages:this.chat.messages})})}},Mi=new WeakMap,Lv);let ro=Dr;jM([E.trace("ChatController.setupEvents")],ro.prototype,"setupEvents",1);var GM=Object.defineProperty,WM=Object.getOwnPropertyDescriptor,JM=(s,t,e,r)=>{for(var i=r>1?void 0:r?WM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GM(t,e,i),i};let mh=(xv=class extends Ot{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,pl);g(this,ml);p(this,"items");g(this,jn,void 0);g(this,Gn,void 0);g(this,ko,void 0);f(this,ko,t),f(this,jn,e),f(this,Gn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,ml,sS))throw new C("Can't create polls without joining room","0705");if(!a(this,jn).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await a(this,Gn).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,jn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,Gn).votePoll(t,e)}},pl=new WeakSet,tS=function(){return a(this,ko).getValue("connectionHandler")},ml=new WeakSet,sS=function(){var t;return((t=a(this,pl,tS))==null?void 0:t.socketJoined)===!0},jn=new WeakMap,Gn=new WeakMap,ko=new WeakMap,xv);mh=JM([dt("0700")],mh);var KM=Object.defineProperty,zM=Object.getOwnPropertyDescriptor,YM=(s,t,e,r)=>{for(var i=r>1?void 0:r?zM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&KM(t,e,i),i};const In=(Uv=class{constructor(s,t,e){p(this,"polls");g(this,qr,void 0);g(this,Wn,void 0);g(this,Oi,void 0);this.polls=new mh(s,t,e),f(this,Wn,t),f(this,qr,s),f(this,Oi,e),this.setupEvents()}get telemetry(){return a(this,qr).getValue("telemetry")}get logger(){return a(this,qr).getValue("logger")}static async init(s,t,e){return new In(s,t,e)}canViewPolls(){return a(this,Wn).permissions.polls.canView}setupEvents(){const s={[Xs.createPoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))},[Xs.updatePoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))},[Xs.votePoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))}},t=()=>{a(this,qr).getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Oi).on(r,s[r])})},e=()=>{a(this,qr).getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Oi).removeListeners(r)})};a(this,Wn).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await a(this,Oi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=hM.fromBinary(s.payload);this.polls.items=t.map(e=>In.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},qr=new WeakMap,Wn=new WeakMap,Oi=new WeakMap,Uv);let wf=In;YM([E.trace("PollController.setupEvents")],wf.prototype,"setupEvents",1);var QM=Object.defineProperty,XM=Object.getOwnPropertyDescriptor,ZM=(s,t,e,r)=>{for(var i=r>1?void 0:r?XM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&QM(t,e,i),i},Pf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Pf||{});let gh=($v=class extends Ot{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);g(this,Co);p(this,"selfActiveTab");p(this,"broadcastTabChanges");g(this,Jn,void 0);g(this,Di,void 0);g(this,Ro,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,Jn,t),f(this,Di,e),this.viewType=r,f(this,Ro,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Co,Zh).socketState}get mediaState(){return a(this,Co,Zh).mediaState}get meetingId(){return a(this,Jn).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Di).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new C("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=a(this,Di).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,Ro).broadcastMessage("spotlight",{userId:a(this,Di).userId,currentTab:this.selfActiveTab})}},Jn=new WeakMap,Co=new WeakSet,Zh=function(){return a(this,Jn).getValue("connectionHandler")},Di=new WeakMap,Ro=new WeakMap,$v);gh=ZM([dt("0800")],gh);function eO(s){let t="",e=[""];const r=[e];let i=0,n=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
13
- `&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var tO=Object.defineProperty,sO=Object.getOwnPropertyDescriptor,_f=(s,t,e,r)=>{for(var i=r>1?void 0:r?sO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&tO(t,e,i),i};let Nr=(Bv=class extends Ot{constructor(t){const e=t.getValue("logger");super(e);p(this,"transcripts");g(this,Io,void 0);f(this,Io,t),this.transcripts=[]}get telemetry(){return a(this,Io).getValue("telemetry")}static async init(t,e){const r=new Nr(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(n){i.error("Error fetching active transcriptions ",n)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,n,o,c,d]]=eO(t);return{id:Sn(),name:c,peerId:i,userId:n,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
14
- `).map(e=>Nr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=wt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Nr.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const i=e.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)}},Io=new WeakMap,Bv);_f([E.trace("Ai.getActiveTranscript")],Nr.prototype,"getActiveTranscript",1),Nr=_f([dt("0000")],Nr);var rO=Object.defineProperty,iO=Object.getOwnPropertyDescriptor,nO=(s,t,e,r)=>{for(var i=r>1?void 0:r?iO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&rO(t,e,i),i};const kf=(Fv=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");g(this,jr,void 0);g(this,Kn,void 0);p(this,"aiSocketHandler");g(this,xt,void 0);f(this,xt,s),this.meta=new gh(s,t,t.config.viewType,e,n),this.ai=r,f(this,jr,t),f(this,Kn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,xt).getValue("telemetry")}get logger(){return a(this,xt).getValue("logger")}static async init(s,t,e,r,i){const n=await Nr.init(s,t.permissions.transcriptionEnabled);return new kf(s,t,e,n,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,Pf.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,xt).getValue("peerSessionStore").on(k.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,xt).getValue("peerSessionStore").on(k.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,xt).getValue("peerSessionStore").on(k.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,xt).getValue("peerSessionStore").on(k.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,jr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Kn).broadcastMessage("spotlight",{userId:a(this,jr).userId,currentTab:this.meta.selfActiveTab})),a(this,xt).getValue("peerSessionStore").on(k.PEER_JOINED_INTERNAL,async s=>{a(this,jr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Kn).broadcastToPeers("spotlight",[s.id],{userId:a(this,jr).userId,currentTab:this.meta.selfActiveTab})}),a(this,xt).getValue("peerSessionStore").on(k.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),a(this,xt).getValue("peerSessionStore").on(k.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on(U.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Nr.parseTranscript(e,r)}catch(d){this.logger.error(`Failed to parse transcript: ${e}`,d)}if(!i){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},jr=new WeakMap,Kn=new WeakMap,xt=new WeakMap,Fv);let Cf=kf;nO([E.trace("MetaController.setupEvents")],Cf.prototype,"setupEvents",1);const io={},tr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var y,w;const l=(w=(this==null?void 0:this.peerId)||((y=d[0])==null?void 0:y.authToken))!=null?w:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(io[u]){const R=new Error(`Unsupported concurrent calls on method: ${s}.`);throw R.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:R.stack},locker:{methodName:s,lockName:u}}),R}io[u]=!0;const m=setTimeout(()=>delete io[u],e),v=o.apply(this,d);return Promise.resolve(v).then(()=>{delete io[u],clearTimeout(m)}).catch(()=>{delete io[u],clearTimeout(m)}),v},n}}};var aO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,Si=(s,t,e,r)=>{for(var i=r>1?void 0:r?oO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&aO(t,e,i),i};class Vr extends Ot{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);g(this,Mo);g(this,zn);g(this,es,void 0);g(this,gl,void 0);g(this,oe,void 0);g(this,Ao,void 0);g(this,Ns,void 0);g(this,ze,void 0);f(this,ze,e),f(this,es,n),f(this,gl,o),f(this,oe,r),f(this,Ao,i),f(this,Ns,[]),this.setupEvents()}get telemetry(){return a(this,ze).getValue("telemetry")}get status(){return a(this,ze).getValue("stageStatus")}setupEvents(){const e={[k.GET_STAGE_REQUESTS]:async n=>{f(this,Ns,n)},[k.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Ns).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([n,o])=>{a(this,ze).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,ze).getValue("peerSessionStore").removeListener(n,o)})};a(this,oe).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,oe).permissions.acceptStageRequests?(r(),a(this,es).getStageRequests()):(i(),f(this,Ns,[]),this.emit("stageAccessRequestUpdate",a(this,Ns))))}),a(this,oe).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,oe).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new C("You do not have permission to perform this action","2001");const e=a(this,Ao).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Ns,e),{stageRequests:a(this,Ns)}}async requestAccess(){if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new C(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,oe).permissions.stageAccess===G.Allowed){V(this,zn,ou).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,es).requestAccess(),V(this,zn,ou).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");a(this,es).cancelRequestAccess(),V(this,zn,ou).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,oe).roomJoined)throw new C("Can`t grant for participant without joining room");if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,oe).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,es).grantAccess(e)}denyAccess(e){if(!a(this,oe).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,oe).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new C("You do not have permission to perform this action","2001");return a(this,es).denyAccess(e)}get peerId(){return a(this,ze).getValue("peerId")}async join(){const e=a(this,ze).getValue("viewType");if(this.status==="ON_STAGE")throw new C("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,oe).permissions.stageAccess===G.NotAllowed)throw new C(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,ze).setValue("stageStatus","ON_STAGE",!1),await a(this,es).joinStage(),e===Ws.Livestream){await a(this,ze).getValue("selfController").joinRoom();return}a(this,ze).notify("stageStatus"),a(this,oe).audioEnabled&&a(this,Mo,ep).shareMic(a(this,oe).audioTrack),a(this,oe).videoEnabled&&a(this,Mo,ep).shareWebcam(a(this,oe).videoTrack)}async leave(){if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new C(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,oe).setIsPinned(!1),a(this,ze).setValue("stageStatus","OFF_STAGE",!1),await a(this,es).leaveStage(a(this,oe).userId);try{await a(this,ze).getValue("peerSessionStore").emitAsync(k.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,ze).notify("stageStatus")}async kick(e){if(!a(this,oe).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,oe).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return a(this,es).kick(e)}}es=new WeakMap,gl=new WeakMap,oe=new WeakMap,Ao=new WeakMap,Ns=new WeakMap,ze=new WeakMap,Mo=new WeakSet,ep=function(){return a(this,ze).getValue("roomNodeClient")},zn=new WeakSet,ou=async function(e){this.status!==e&&a(this,ze).setValue("stageStatus",e)},Si([E.trace("Stage.getStageRequests")],Vr.prototype,"getAccessRequests",1),Si([E.trace("Stage.requestAccess")],Vr.prototype,"requestAccess",1),Si([E.trace("Stage.cancelRequestAccess")],Vr.prototype,"cancelRequestAccess",1),Si([E.trace("Stage.grantAccess")],Vr.prototype,"grantAccess",1),Si([E.trace("Stage.denyAccess")],Vr.prototype,"denyAccess",1),Si([tr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],Vr.prototype,"join",1),Si([E.trace("Stage.leaveStage")],Vr.prototype,"leave",1);function cO(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function fh(s){switch(s){case Ys.UNSPECIFIED:return"OFF_STAGE";case Ys.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Ys.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Ys.OFF_STAGE:return"OFF_STAGE";case Ys.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var dO=Object.defineProperty,lO=Object.getOwnPropertyDescriptor,uO=(s,t,e,r)=>{for(var i=r>1?void 0:r?lO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dO(t,e,i),i};class Rf{constructor(t,e,r,i,n){p(this,"stage");g(this,Gr,void 0);g(this,fs,void 0);g(this,Wr,void 0);g(this,Oo,0);g(this,vt,void 0);f(this,vt,t),this.stage=new Vr(t,i,n,e,r),f(this,Wr,e),f(this,Gr,i),f(this,fs,n),this.setupEvents()}get telemetry(){return a(this,vt).getValue("telemetry")}get logger(){return a(this,vt).getValue("logger")}setupEvents(){a(this,vt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,Wr).on(U.grantStageAccess,()=>{a(this,Gr).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,Wr).on(U.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,Gr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,Wr).on(U.denyStageAccess,()=>{a(this,Gr).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,Wr).on(U.getStageRequests,async t=>{var r;if(a(this,Gr).permissions.stageAccess!==G.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,vt).getValue("peerSessionStore").emitAsync(k.GET_STAGE_REQUESTS,e),a(this,Oo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,Oo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,fs).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&a(this,vt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=fh(t.stageType),r=a(this,vt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,vt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:a(this,vt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,fs).joined.get(t.peerId),r=a(this,fs).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&a(this,vt).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:a(this,fs).viewMode,page:a(this,fs).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&a(this,vt).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:a(this,fs).viewMode,page:a(this,fs).currentPage});break}a(this,vt).getValue("peerSessionStore").emit(k.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Gr=new WeakMap,fs=new WeakMap,Wr=new WeakMap,Oo=new WeakMap,vt=new WeakMap,uO([E.trace("Stage.setupEvents")],Rf.prototype,"setupEvents",1);var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,vh=(s,t,e,r)=>{for(var i=r>1?void 0:r?pO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hO(t,e,i),i};let no=(Hv=class extends kn{constructor(t,e,r,i){const n=t.getValue("logger");super(n);p(this,"name");p(this,"icon");p(this,"id");p(this,"permissions");g(this,Ni,void 0);g(this,lr,void 0);g(this,Do,void 0);g(this,No,void 0);g(this,Vi,void 0);p(this,"active");p(this,"enabledBy");f(this,Do,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,f(this,No,e.component),this.permissions=e.permissions,f(this,Ni,i),f(this,lr,r),this.active=!1,this.enabledBy=""}get component(){return a(this,No)}get telemetry(){return a(this,Do).getValue("telemetry")}set activePluginsStore(t){f(this,lr,t)}activateForSelf(){f(this,Vi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){f(this,Vi,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!a(this,lr))throw new C("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,lr).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,Ni).id}),this.enabledBy=a(this,Ni).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==a(this,Ni).id)return;if(!a(this,lr))throw new C("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,Vi)?new Date().getTime()-a(this,Vi).getTime():0;await a(this,lr).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Ni=new WeakMap,lr=new WeakMap,Do=new WeakMap,No=new WeakMap,Vi=new WeakMap,Hv);vh([E.trace("Plugin.activatePlugin")],no.prototype,"activate",1),vh([E.trace("Plugin.deactivatePlugin")],no.prototype,"deactivate",1),no=vh([dt("0600")],no);class If extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();g(this,Ue,void 0);g(this,Li,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");f(this,Ue,new kn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,Li,new Map)}emit(e,...r){return a(this,Ue).emit(e,...r)}on(e,r){return a(this,Ue).on(e,r)}addListener(e,r){return a(this,Ue).addListener(e,r)}off(e,r){return a(this,Ue).off(e,r)}once(e,r){return a(this,Ue).once(e,r)}prependListener(e,r){return a(this,Ue).prependListener(e,r)}prependOnceListener(e,r){return a(this,Ue).prependOnceListener(e,r)}removeListener(e,r){return a(this,Ue).removeListener(e,r)}removeAllListeners(e){return a(this,Ue).removeAllListeners(e)}listeners(e){return a(this,Ue).listeners(e)}listenerCount(e){return a(this,Ue).listenerCount(e)}getMaxListeners(){return a(this,Ue).getMaxListeners()}setMaxListeners(e){return a(this,Ue).setMaxListeners(e)}eventNames(){return a(this,Ue).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return a(this,Li).set(e,o),r.on("*",o),i&&a(this,Ue).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,Li).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,Ue).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,Li).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,Ue).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}Ue=new WeakMap,Li=new WeakMap;class Af extends If{constructor(t){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},t)}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var mO=Object.defineProperty,gO=Object.getOwnPropertyDescriptor,fO=(s,t,e,r)=>{for(var i=r>1?void 0:r?gO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mO(t,e,i),i};let Sh=class{constructor(s){p(this,"all");p(this,"active");this.all=new Af(s),this.active=new Af(s)}};Sh=fO([dt("0600")],Sh);var vO=Object.defineProperty,SO=Object.getOwnPropertyDescriptor,TO=(s,t,e,r)=>{for(var i=r>1?void 0:r?SO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vO(t,e,i),i};const Mf=(qv=class{constructor(s,t,e,r){g(this,fl);g(this,Vo);g(this,Lo);g(this,xo);p(this,"plugins");g(this,vs,void 0);g(this,Yn,void 0);g(this,Jr,void 0);g(this,xi,null);f(this,Jr,s),this.plugins=t,f(this,Yn,e),f(this,vs,r),this.setupEvents()}get telemetry(){return a(this,Jr).getValue("telemetry")}get logger(){return a(this,Jr).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new Sh(i);let c;n.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(Bu,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(h=>{const m=new no(s,h,c,e);o.all.add(m)});const d=new Mf(s,o,r,c);return c?V(l=d,xo,rp).call(l):V(u=d,fl,rS).call(u),d}cleanup(){V(this,Vo,tp).call(this)}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),a(this,Jr).getValue("peerSessionStore").onAsync(k.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!a(this,vs)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await V(this,Lo,sp).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},vs=new WeakMap,Yn=new WeakMap,Jr=new WeakMap,xi=new WeakMap,fl=new WeakSet,rS=function(){const s=a(this,Jr).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,vs))try{f(this,vs,await a(this,Yn).create(Bu,!0)),V(this,Vo,tp).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,vs)}),V(this,xo,rp).call(this),this.logger.info("Active plugins store created after socket connected"),await V(this,Lo,sp).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(k.SOCKET_STATE_UPDATE,t),f(this,xi,()=>{s.off(k.SOCKET_STATE_UPDATE,t)})},Vo=new WeakSet,tp=function(){a(this,xi)&&(a(this,xi).call(this),f(this,xi,null))},Lo=new WeakSet,sp=async function(){try{await a(this,Yn).refresh(a(this,vs).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,vs).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},xo=new WeakSet,rp=function(){a(this,vs).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},qv);let Of=Mf;TO([E.trace("PluginController.setupEvents")],Of.prototype,"setupEvents",1);class yO{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");g(this,Uo,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},f(this,Uo,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(a(this,Uo).getValue("peerSessionStore").emit(k.SOCKET_STATE_UPDATE,r),this.socketState=r)}}Uo=new WeakMap;var EO=Object.defineProperty,bO=Object.getOwnPropertyDescriptor,ao=(s,t,e,r)=>{for(var i=r>1?void 0:r?bO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&EO(t,e,i),i};let Ti=(jv=class extends Ot{constructor(t,e){const r=t.getValue("logger");super(r);g(this,Zn);g(this,Qn,void 0);g(this,Xn,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,Xn,t),f(this,Qn,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"}get telemetry(){return a(this,Xn).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,Qn).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new C("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new C(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=wt(),{recording:r={}}=a(this,Xn).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::stop::recording_failed_to_start",{error:e}),new C("Error while starting recording","1000",this.logger)}}async stop(t){await V(this,Zn,cu).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await V(this,Zn,cu).call(this,"pause",["RECORDING"],t)}async resume(t){await V(this,Zn,cu).call(this,"resume",["PAUSED"],t)}},Qn=new WeakMap,Xn=new WeakMap,Zn=new WeakSet,cu=async function(t,e,r){if(!a(this,Qn).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new C("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(o=>o.id===r);if(n===void 0)throw new C("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await wt().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new C("Error while stopping recording","1000",this.logger)}})},jv);ao([E.trace("Recording.start")],Ti.prototype,"start",1),ao([E.trace("Recording.stop")],Ti.prototype,"stop",1),ao([E.trace("Recording.stop")],Ti.prototype,"pause",1),ao([E.trace("Recording.stop")],Ti.prototype,"resume",1),Ti=ao([dt("1000")],Ti);var wO=Object.defineProperty,PO=Object.getOwnPropertyDescriptor,_O=(s,t,e,r)=>{for(var i=r>1?void 0:r?PO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&wO(t,e,i),i};class Df{constructor(t,e,r){p(this,"recording");p(this,"room");g(this,Ui,void 0);f(this,Ui,t),this.recording=new Ti(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,Ui).getValue("telemetry")}get logger(){return a(this,Ui).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case vi.BROWSER:e="BROWSER";break;case vi.COMPOSITE:e="COMPOSITE";break;case vi.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,Ui).getValue("peerSessionStore").on(k.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(U.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===t.recordingId&&(e=!0,i.state="RECORDING")}),e===!1){const i=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on(U.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(U.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Ui=new WeakMap,_O([E.trace("RecordingController.setupEvents")],Df.prototype,"setupEvents",1);class kO{constructor(t){g(this,$i,void 0);f(this,$i,t)}hasFeature(t){return a(this,$i).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,$i).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,$i).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}$i=new WeakMap;class Th{constructor(t,e,r,i){p(this,"authToken");p(this,"logger");p(this,"features");p(this,"browserSpecs");p(this,"callStats");this.authToken=t,this.logger=e,this.features=r,this.browserSpecs=Te,this.callStats=i}static init(t){return new Th(t.getValue("authToken"),t.getValue("logger"),new kO(t),t.getValue("callstats"))}}class yh{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=Th.init(t);return new yh(e)}}var CO=Object.defineProperty,RO=Object.getOwnPropertyDescriptor,Nt=(s,t,e,r)=>{for(var i=r>1?void 0:r?RO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CO(t,e,i),i};class Pt extends kn{constructor(e,r,i=$d,n=!0){const o=e.getValue("logger");super(o);g(this,qe,void 0);g(this,Ee,void 0);g(this,ve,void 0);g(this,ur,void 0);g(this,ts,void 0);g(this,$o,void 0);g(this,De,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");f(this,De,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,qe,new Ff(e,r)),f(this,Ee,new rD(e,a(this,qe),void 0,i)),f(this,ve,new lD(e,a(this,qe),void 0,i)),f(this,ts,new oD(a(this,De),a(this,qe))),f(this,ur,new nD(e,a(this,qe))),f(this,$o,n),a(this,Ee).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Ee).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,ve).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,ve).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,ts).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,De).getValue("telemetry")}set context(e){f(this,De,e)}async onVisibilityChange(){a(this,De).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,De).getValue("callstats").browserBackgrounded():(a(this,De).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,De).getValue("callstats").audioOn():a(this,De).getValue("callstats").audioOff(),r?a(this,De).getValue("callstats").videoOn():a(this,De).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,qe).getAudioAndVideoTrack(a(this,Ee).userSelectedDevice,a(this,ve).userSelectedDevice);i=c.audioTrack,n=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await a(this,qe).getAudioTrack(!1,a(this,Ee).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,qe).getVideoTrack(a(this,ve).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,De).getValue("callstats").audioOff(),r&&!n&&a(this,De).getValue("callstats").videoOff(),await a(this,Ee).setMediaTrack(i),await a(this,ve).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,De).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,De).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,ur).currentDevice)!=null&&o.deviceId&&a(this,De).getValue("callstats").selectedDevice("SPEAKER",a(this,ur).currentDevice),a(this,qe).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,Ee).currentDevice,video:a(this,ve).currentDevice,speaker:a(this,ur).currentDevice}}get permissions(){return a(this,qe).permissions}getAllDevices(){return a(this,qe).getAvailableDevices()}getDeviceById(e,r){return a(this,qe).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Ee).mediaTrack}get audioTrack(){return a(this,Ee).transformedMediaTrack}get audioEnabled(){return a(this,Ee).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,Ee).enableTrack(!1,e):await a(this,Ee).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,Ee).mediaTrack&&!a(this,Ee).isCustomTrack?a(this,Ee).muteTrack():a(this,Ee).disableTrack()}getAudioDevices(e){return a(this,qe).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,Ee).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,ur).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await a(this,ur).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,ve).mediaTrack}get videoTrack(){return a(this,ve).transformedMediaTrack}get videoEnabled(){return a(this,ve).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,ve).enableTrack(!1,e):await a(this,ve).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,ve).disableTrack()}getVideoDevices(e){return a(this,qe).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,ve).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,De).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,ve).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,ts).audioMediaTrack,video:a(this,ts).videoMediaTrack}}get screenShareEnabled(){return a(this,ts).trackEnabled}async enableScreenShare(){await a(this,ts).enableScreenShare()}async disableScreenShare(){a(this,ts).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,ts).updateConstraints(e)}getSpeakerDevices(e){return a(this,qe).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Ee).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Ee).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Ee).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,ve).addMiddleware(e)}removeVideoMiddleware(e){return a(this,ve).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,ve).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,ve).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Ee).disableTrack(),a(this,ve).disableTrack(),a(this,ve).terminateMiddlewareWebWorker(),a(this,ts).disableScreenShare(),a(this,qe).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,$o))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!$d(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,Ee).disableTrack()}removeVideoTrack(){a(this,ve).disableTrack(),a(this,ve).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}qe=new WeakMap,Ee=new WeakMap,ve=new WeakMap,ur=new WeakMap,ts=new WeakMap,$o=new WeakMap,De=new WeakMap,Nt([E.trace("MediaHandler.setupStreams")],Pt.prototype,"setupStreams",1),Nt([E.trace("MediaHandler.enableAudio")],Pt.prototype,"enableAudio",1),Nt([E.trace("MediaHandler.disableAudio")],Pt.prototype,"disableAudio",1),Nt([E.trace("MediaHandler.setAudioDevice")],Pt.prototype,"setAudioDevice",1),Nt([E.trace("MediaHandler.enableVideo")],Pt.prototype,"enableVideo",1),Nt([E.trace("MediaHandler.disableVideo")],Pt.prototype,"disableVideo",1),Nt([E.trace("MediaHandler.setVideoDevice")],Pt.prototype,"setVideoDevice",1),Nt([E.trace("MediaHandler.updateVideoConstraints")],Pt.prototype,"updateVideoConstraints",1),Nt([E.trace("MediaHandler.enableScreenShare")],Pt.prototype,"enableScreenShare",1),Nt([E.trace("MediaHandler.disableScreenShare")],Pt.prototype,"disableScreenShare",1),Nt([E.trace("MediaHandler.updateScreenshareConstraints")],Pt.prototype,"updateScreenshareConstraints",1),Nt([E.trace("MediaHandler.destruct")],Pt.prototype,"destruct",1),Nt([E.trace("MediaHandler.onDeviceChange")],Pt.prototype,"onDeviceChange",1);function Ud(s,t,e){switch(!0){case Te.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Te.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Te.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const IO=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function $d(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=Te._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:IO.some(i=>t==null?void 0:t.includes(i))}async function AO(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,n=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}const MO=s=>(t,e)=>(s.set(t,e),e),Nf=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Vf=536870912,Lf=Vf*2,OO=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<Lf?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Vf){for(;e.has(i);)i=Math.floor(Math.random()*Lf);return s(e,i)}if(e.size>Nf)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;e.has(i);)i=Math.floor(Math.random()*Nf);return s(e,i)},xf=new WeakMap,DO=MO(xf),Bd=OO(DO,xf),NO=s=>s.method!==void 0&&s.method==="call",VO=s=>s.error===null&&typeof s.id=="number",Fd=((s,t)=>{let e=null;return()=>{if(e!==null)return e;const r=new Blob([t],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(r);return e=s(i),setTimeout(()=>URL.revokeObjectURL(i)),e}})(s=>{const t=new Map([[0,()=>{}]]),e=new Map([[0,()=>{}]]),r=new Map,i=new Worker(s);return i.addEventListener("message",({data:l})=>{if(NO(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const m=t.get(u);if(typeof m=="number"){const v=r.get(m);if(v===void 0||v.timerId!==u||v.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof m!="undefined")m();else throw new Error("The timer is in an undefined state.")}else if(h==="timeout"){const m=e.get(u);if(typeof m=="number"){const v=r.get(m);if(v===void 0||v.timerId!==u||v.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof m!="undefined")m(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(VO(l)){const{id:u}=l,h=r.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:m,timerType:v}=h;r.delete(u),v==="interval"?t.delete(m):e.delete(m)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=Bd(r);r.set(u,{timerId:l,timerType:"interval"}),t.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"interval"}})},clearTimeout:l=>{const u=Bd(r);r.set(u,{timerId:l,timerType:"timeout"}),e.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"timeout"}})},setInterval:(l,u=0)=>{const h=Bd(t);return t.set(h,()=>{l(),typeof t.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(l,u=0)=>{const h=Bd(e);return e.set(h,l),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"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})}}))})();`),Uf=s=>Fd().clearInterval(s),LO=s=>Fd().clearTimeout(s),$f=(s,t)=>Fd().setInterval(s,t),Bf=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Uf,clearTimeout:LO,setInterval:$f,setTimeout:(s,t)=>Fd().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class xO{constructor(t){g(this,Bi,void 0);g(this,Bo,void 0);f(this,Bo,t)}get logger(){return a(this,Bo).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Bi))try{Uf(a(this,Bi)),f(this,Bi,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),n=await Promise.all(t==null?void 0:t.map(m=>m({canvas:i,WorkerTimers:Bf})));if(r.disablePerFrameCanvasRendering){const v=i.captureStream().getVideoTracks()[0];return Object.defineProperty(v,"originalSettings",{value:e.getSettings()}),v}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let m=0;m<n.length;m+=1)typeof n[m]=="function"&&await n[m](i,d)}catch(m){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:m})}};try{o.play()}catch(m){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,f(this,Bi,$f(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Bi=new WeakMap,Bo=new WeakMap;const UO={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},$O=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],BO=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=$O,n=i.map(([h])=>h).sort((h,m)=>h-m);let o=Number.MAX_VALUE,c=0;return n.forEach((h,m)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=m)}),i[c][1]};var Ie=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Ie||{});const FO=z_(),An=Is(FO.config.media);function HO(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}class qO{constructor(t,e){g(this,Fi,void 0);g(this,vl,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,m,v,y,w,R,P;const t=(l=a(this,Fi))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(v=(m=t==null?void 0:t.height)==null?void 0:m.max)!=null?v:1080,i=(w=(y=t==null?void 0:t.frameRate)==null?void 0:y.max)!=null?w:5,n=(P=(R=t==null?void 0:t.frameRate)==null?void 0:R.ideal)!=null?P:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:n,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});p(this,"getAudioConstraints",t=>{var n,o,c,d,l,u,h;const e={},r=(n=a(this,Fi))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return Te.isFirefox()||Te.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(h=r==null?void 0:r.noiseSupression)!=null?h:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});p(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=a(this,Fi))==null?void 0:o.video,i=uP(UO);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});f(this,vl,t),f(this,Fi,e)}getUpdatedVideoConstraints(t){return t}}Fi=new WeakMap,vl=new WeakMap;class Eh extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class jO{constructor(){p(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var GO=Object.defineProperty,WO=Object.getOwnPropertyDescriptor,ps=(s,t,e,r)=>{for(var i=r>1?void 0:r?WO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&GO(t,e,i),i};let Vt=(Gv=class extends jO{constructor(t,e){super();g(this,ea,void 0);g(this,ss,void 0);g(this,Ye,void 0);f(this,Ye,t),f(this,ss,new qO(t,e)),f(this,ea,new AbortController)}get telemetry(){return a(this,Ye).getValue("telemetry")}get logger(){return a(this,Ye).getValue("logger")}get constraintsBuilder(){return a(this,ss)}async destruct(){var t;(t=a(this,ea))==null||t.abort()}handlePermissionErrors(t,e){const r=Ud(t,e.name,e.message);return this.permissions[t]=r,a(this,Ye).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,n,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(P=>P.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const h=!!(d!=null&&d.find(P=>P.deviceId===e));let m;e&&h?m=e:d&&((n=d[0])!=null&&n.deviceId)&&(m=(o=d[0])==null?void 0:o.deviceId);const v={audio:a(this,ss).getAudioConstraints(u).audio,video:a(this,ss).getVideoConstraints(m).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(v)});const y=await navigator.mediaDevices.getUserMedia(v);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(v)});const w=y.getAudioTracks()[0];let R=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",R.label.includes("OBS Virtual")){const N=(await this.getVideoInputDevices()).find($=>$.label.includes("OBS Virtual"));R=await this.getVideoTrack(N.deviceId)}return a(this,Ye).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Ye).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:w,videoTrack:R}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new C("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",a(this,Ye).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new C("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(m=>m.deviceId!==l),u=a(this,ss).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[h]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),h}catch(h){const m=Ud("audio",h.name,h.message),v=new Eh(h.name,h.message,u);if(m==="COULD_NOT_START"){const y=r.shift();if(!y)throw v;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const w=a(this,ss).getAudioConstraints(y.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(w)}),o(y.deviceId)}throw v}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Ye).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new C(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Ye).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new C("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let n;t&&i?n=t:(d=r[0])!=null&&d.deviceId&&(n=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let h=u;const{video:m}=h;e&&typeof m!="boolean"&&(h={video:{deviceId:m.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(h)});const[v]=(await navigator.mediaDevices.getUserMedia(h)).getVideoTracks();if(e&&typeof m!="boolean"&&typeof m.width=="object"){const{width:y,height:w}=v.getSettings(),{ideal:R}=m.width;v.applyConstraints({width:{ideal:R},height:{ideal:Math.floor(w*R/y)},frameRate:m.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),v}catch(h){const m=Ud("video",h.name,h.message),v=new Eh(h.name,h.message,u);if(m==="COULD_NOT_START"){const y=r.shift();if(!y)throw v;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const w=a(this,ss).getVideoConstraints(y.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(w)}),o({video:w.video})}throw v}};try{const u=a(this,ss).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Ye).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),h}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new C(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,Ye).getValue("callstats").screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=Ud("video",r.name,r.message),n=new Eh(r.name,r.message,e),o={video:!0};if(T_(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,ss).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Ye).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new C(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return $d(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")||n.includes("earbuds")||n.includes("usb")||n.includes("external")?0:i.deviceId==="default"||n.includes("default")?1:n.includes("built-in")||n.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return n.includes("front")||n.includes("user")||n.includes("selfie")?!0:!(n.includes("back")||n.includes("rear")||n.includes("environment"))};return t.sort((i,n)=>{var u,h;const o=e(i),c=e(n);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=n.deviceId==="default"||((h=n.label)==null?void 0:h.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&n.kind==="videoinput"){const m=r(i),v=r(n);if(m&&!v)return-1;if(!m&&v)return 1}return 0})}async getAvailableDevices(){try{return await this.enumerateDevicesWithExternalFirst()||[]}catch(t){return this.logger.error("enumerate_devices_failed",{error:t}),[]}}async getAvailableDevicesByKind(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(({kind:e})=>t===e)}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new C("Failed to get device","1609")}}async onDeviceChange(t){if(Te.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=h=>`${h.kind}-${h.label}-${h.deviceId}-${h.groupId}`,n=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!n.has(i(h))),removed:e.filter(h=>!c.has(i(h))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const h=[...d.added,...d.removed];h.some(m=>m.kind==="audioinput")&&a(this,Ye).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(m=>m.kind==="audioinput")),h.some(m=>m.kind==="videoinput")&&a(this,Ye).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(m=>m.kind==="videoinput")),h.some(m=>m.kind==="audiooutput")&&a(this,Ye).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(m=>m.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,ea).signal})}}},ea=new WeakMap,ss=new WeakMap,Ye=new WeakMap,Gv);ps([E.trace("WebMediaInterface.destruct")],Vt.prototype,"destruct",1),ps([E.trace("WebMediaInterface.handlePermissionErrors")],Vt.prototype,"handlePermissionErrors",1),ps([E.trace("WebMediaInterface.getAudioAndVideoTrack")],Vt.prototype,"getAudioAndVideoTrack",1),ps([E.trace("WebMediaInterface.getAudioTrack")],Vt.prototype,"getAudioTrack",1),ps([E.trace("WebMediaInterface.getVideoTrack")],Vt.prototype,"getVideoTrack",1),ps([E.trace("WebMediaInterface.getScreenShareTracks")],Vt.prototype,"getScreenShareTracks",1),ps([E.trace("WebMediaInterface.getAvailableDevices")],Vt.prototype,"getAvailableDevices",1),ps([E.trace("WebMediaInterface.getAvailableDevicesByKind")],Vt.prototype,"getAvailableDevicesByKind",1),ps([E.trace("WebMediaInterface.getDevice")],Vt.prototype,"getDevice",1),ps([E.trace("WebMediaInterface.onDeviceChange")],Vt.prototype,"onDeviceChange",1),Vt=ps([dt("1600")],Vt);const Ff=Vt,yi={setItem:(s,t,e)=>{try{localStorage.setItem(s,t)}catch(r){e==null||e.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:s,value:t}})}},getItem:(s,t)=>{try{return localStorage.getItem(s)}catch(e){t==null||t.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:s}})}return null}},JO=(s=0)=>new Promise(t=>setTimeout(t,s)),KO=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),n=s.createAnalyser();n.fftSize=2048,i.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):JO().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},zO=typeof AudioContext!="undefined"?AudioContext:null;class bh{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:zO,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:bh}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const Hf=new bh,YO=3,QO=250;function XO(s){const t={},e=Hf.getOrCreate(t);let r=YO;function i(){return r-=1,KO(e,s.srcObject,QO).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Hf.release(t)})}async function qf(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const n=e.play();n&&await n,i=await XO(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{e.pause(),e.remove()}return i}var ZO=Object.defineProperty,eD=Object.getOwnPropertyDescriptor,jf=(s,t,e,r)=>{for(var i=r>1?void 0:r?eD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ZO(t,e,i),i};let Hd=class extends kn{constructor(t,e,r,i){var o;const n=t.getValue("logger");super(n);p(this,"constructorName",this.constructor.name);p(this,"userSelectedDevice");p(this,"mediaInterface");p(this,"isNonPreferredDevice");p(this,"_mediaTrack");p(this,"transformedMediaTrack");p(this,"middlewares",[]);p(this,"currentDevice");p(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);p(this,"setUserPreferredDevice",t=>yi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>yi.getItem(this.userPreferredDeviceKey,this.logger));p(this,"isCustomTrack",!1);p(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(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}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new C("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new C("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(Te.isWebKitBased()&&!(Te.isSafari()&&D_.test(Te.getVersion())))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&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.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."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.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&&(this.logger.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}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};jf([E.trace("BaseMediaHandler.unmuteTrack")],Hd.prototype,"unmuteTrack",1),Hd=jf([dt("1600")],Hd);const Gf=Hd;var tD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,wh=(s,t,e,r)=>{for(var i=r>1?void 0:r?sD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&tD(t,e,i),i};const Ph="[Realtimekit]nonSilentDeviceLabels";class qd extends Gf{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new C("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new C("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new C(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await AO(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(n!=null&&n.length))return r;n.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse(yi.getItem(Ph,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await qf(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return yi.setItem(Ph,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return n.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await qf(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return yi.setItem(Ph,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}wh([E.trace("AudioMediaHandler.setTransformedTrack")],qd.prototype,"setTransformedTrack",1),wh([E.trace("AudioMediaHandler.onTrackEnded")],qd.prototype,"onTrackEnded",1),wh([E.trace("AudioMediaHandler.conditionallyChangeTrack")],qd.prototype,"conditionallyChangeTrack",1);const rD=qd;class iD{constructor(t,e){g(this,Hi,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>yi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>yi.getItem(this.userPreferredDeviceKey,this.logger));f(this,Hi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,Hi).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var n,o;if(!(a(this,Hi)instanceof Ff))return;let r=t;if(t||([r]=(await a(this,Hi).getAvailableDevicesByKind("audiooutput")).filter(d=>!$d(d))),!r)throw new C("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}Hi=new WeakMap;const nD=iD;class aD extends kn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");g(this,Fo,void 0);f(this,Fo,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:n}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,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",a(this,Fo).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}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}async updateConstraints(e){if(!this.videoMediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Te.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}Fo=new WeakMap;const oD=aD;var cD=Object.defineProperty,dD=Object.getOwnPropertyDescriptor,jd=(s,t,e,r)=>{for(var i=r>1?void 0:r?dD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&cD(t,e,i),i};class oo extends Gf{constructor(e,r,i,n){super(e,r,i,n);g(this,ta,void 0);g(this,Ho,{disablePerFrameCanvasRendering:!1});f(this,ta,new xO(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new C("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new C("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new C("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await a(this,ta).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Ho)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,Ho,e)}async updateConstraints(e){if(!this._mediaTrack)throw new C("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new C("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){a(this,ta).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const n=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?n.filter(c=>!this.isNonPreferredDevice(c)):n;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}ta=new WeakMap,Ho=new WeakMap,jd([E.trace("VideoMediaHandler.setTransformedTrack")],oo.prototype,"setTransformedTrack",1),jd([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],oo.prototype,"setVideoMiddlewareGlobalConfig",1),jd([E.trace("VideoMediaHandler.onTrackEnded")],oo.prototype,"onTrackEnded",1),jd([E.trace("VideoMediaHandler.conditionallyChangeTrack")],oo.prototype,"conditionallyChangeTrack",1);const lD=oo,Wf=Is(Fu()),ra=class{constructor(t){g(this,St,void 0);g(this,qi,void 0);g(this,qo,void 0);g(this,sa,void 0);if(!t)throw new C("Could not load preset.","0904");f(this,St,t.config),f(this,qo,t.name),f(this,qi,t.ui||Is(Fu().ui)),f(this,sa,t.permissions.plugins.config)}static fromResponse(t){return new ra(t)}static default(){return new ra(Wf)}static init(t,e=!0){return!t||e?new ra(Wf):new ra(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:a(this,qi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,St).viewType}get livestreamViewerQualities(){return a(this,St).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,St).maxVideoStreams}get maxScreenShareCount(){return a(this,St).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,sa)).filter(t=>a(this,sa)[t].disabled)}get designTokens(){return a(this,qi).designTokens}get configDiff(){return a(this,qi).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,St))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,n,o,c,d,l,u,h,m,v,y,w,R,P,N,$,x,H,F,Z,je;return{audio:{enableStereo:(i=(r=(e=(t=a(this,St))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:An.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,St))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:An.audio.enableHighBitrate},video:{quality:(m=(h=(u=(l=a(this,St))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?m:An.video.quality,frameRate:(R=(w=(y=(v=a(this,St))==null?void 0:v.media)==null?void 0:y.video)==null?void 0:w.frameRate)!=null?R:An.video.frameRate},screenshare:{quality:(x=($=(N=(P=a(this,St))==null?void 0:P.media)==null?void 0:N.screenshare)==null?void 0:$.quality)!=null?x:An.screenshare.quality,frameRate:(je=(Z=(F=(H=a(this,St))==null?void 0:H.media)==null?void 0:F.screenshare)==null?void 0:Z.frameRate)!=null?je:An.screenshare.frameRate}}}get name(){return a(this,qo)}};let _h=ra;St=new WeakMap,qi=new WeakMap,qo=new WeakMap,sa=new WeakMap;var uD=Object.defineProperty,hD=Object.getOwnPropertyDescriptor,Jf=(s,t,e,r)=>{for(var i=r>1?void 0:r?hD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&uD(t,e,i),i};class kh extends Ot{constructor(e,r){const i=e.getValue("logger");super(i);g(this,ia,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");g(this,jo,void 0);f(this,ia,r),f(this,jo,e),this.viewerCount=0}get telemetry(){return a(this,jo).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!a(this,ia).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new C("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=wt(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new C("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,ia).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new C("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new C("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await wt().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new C("Error while stopping livestream","1900",this.logger)}}}ia=new WeakMap,jo=new WeakMap,Jf([E.trace("livestream.start")],kh.prototype,"start",1),Jf([E.trace("livestream.stop")],kh.prototype,"stop",1);var pD=Object.defineProperty,mD=Object.getOwnPropertyDescriptor,gD=(s,t,e,r)=>{for(var i=r>1?void 0:r?mD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pD(t,e,i),i};class Kf{constructor(t,e,r){p(this,"livestream");g(this,na,void 0);g(this,aa,void 0);g(this,hr,void 0);g(this,Vs,void 0);f(this,Vs,t),f(this,aa,e),this.livestream=new kh(t,e),f(this,hr,r),this.setupEvents()}get logger(){return a(this,Vs).getValue("logger")}get telemetry(){return a(this,Vs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=wt(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,hr).on(U.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,aa).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,hr).on(U.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,aa).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,hr).on(U.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,hr).on(U.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,hr).on(U.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Vs).getValue("peerSessionStore").on(k.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,na,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Vs).getValue("peerSessionStore").on(k.PEER_CLOSED,t=>{t.id===a(this,na)&&(f(this,na,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Vs).getValue("peerSessionStore").onAsync(k.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),a(this,Vs).getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}na=new WeakMap,aa=new WeakMap,hr=new WeakMap,Vs=new WeakMap,gD([E.trace("LivestreamController.setupEvents")],Kf.prototype,"setupEvents",1);var fD=Object.defineProperty,vD=Object.getOwnPropertyDescriptor,co=(s,t,e,r)=>{for(var i=r>1?void 0:r?vD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&fD(t,e,i),i};class Mn{constructor({name:t,socketHandler:e,meetingId:r}){g(this,Sl);p(this,"name","");g(this,nt,{});g(this,Kr,"");g(this,zr,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,f(this,zr,e),f(this,Kr,r)}async set(t,e,r=!0,i=!1){a(this,nt)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,nt)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,nt)[t]})))}remoteSet(t,e){a(this,zr).storeInsertKeys(a(this,Kr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,nt)[e]=r}),a(this,zr).storeInsertKeys(a(this,Kr),this.name,t)}async update(t,e,r=!0){V(this,Sl,iS).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,nt)[t]&&delete a(this,nt)[t],e)return a(this,zr).storeDeleteKeys(a(this,Kr),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{a(this,nt)[e]&&delete a(this,nt)[e]}),a(this,zr).storeDeleteKeys(a(this,Kr),this.name,t)}get(t){if(a(this,nt)[t])return a(this,nt)[t]}getAll(){return a(this,nt)}clear(){f(this,nt,{})}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){f(this,nt,t)}}nt=new WeakMap,Kr=new WeakMap,zr=new WeakMap,Sl=new WeakSet,iS=function(t,e,r=!0){let i;const n=a(this,nt)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(n);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...n,...e];break;case"[object Object]":i={...n,...e};break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)},co([Dt(Rn,"rateLimitConfig")],Mn.prototype,"remoteSet",1),co([Dt(Rn,"bulkRateLimitConfig")],Mn.prototype,"bulkSet",1),co([Dt(Rn,"rateLimitConfig")],Mn.prototype,"update",1),co([Dt(Rn,"rateLimitConfig")],Mn.prototype,"delete",1),co([Dt(Rn,"bulkRateLimitConfig")],Mn.prototype,"bulkDelete",1);class SD{constructor(t,e){g(this,Go);g(this,Tl);p(this,"stores",new Map);g(this,Yr,void 0);g(this,Qr,"");g(this,Wo,void 0);g(this,Ss,new Map);f(this,Yr,e),f(this,Qr,t.getValue("meetingId")),f(this,Wo,t),V(this,Tl,nS).call(this)}create(t,e=!1){if(N_.includes(t)&&!e)throw new C(`'${t}' is a reserved store name.`,"0601");const r=new Mn({name:t,socketHandler:a(this,Yr),meetingId:a(this,Qr)});return a(this,Yr).storeGetKeys(a(this,Qr),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,Ss).delete(t),o(Error("Failed"))},3e3);a(this,Ss).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,Yr).storeGetKeys(a(this,Qr),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,Ss).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,Ss).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}Yr=new WeakMap,Qr=new WeakMap,Go=new WeakSet,ip=function(){return a(this,Wo).getValue("peerId")},Wo=new WeakMap,Ss=new WeakMap,Tl=new WeakSet,nS=function(){[Qs.storeInsertKeys,Qs.storeGetKeys,Qs.storeDeleteKeys].forEach(t=>{a(this,Yr).on(t,async e=>{var n,o;if(e.pluginId!==a(this,Qr))return;const r=(n=e.storeItems)==null?void 0:n.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===Qs.storeGetKeys){const c=a(this,Ss).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,Ss).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,Ss).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,Ss).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===Qs.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,Go,ip)&&i.set(c,l,!1,!0)}),t===Qs.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,Go,ip)&&i.delete(c,!1,!0)}))})})};function Ei(s){var t,e,r,i,n,o,c,d,l,u,h,m,v;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(n=s.mediaPermissions)==null?void 0:n.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(h=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:h.enabled,trackId:(v=(m=s.screenShareTracks)==null?void 0:m.video)==null?void 0:v.id}}}}:{}}var TD=Object.defineProperty,yD=Object.getOwnPropertyDescriptor,On=(s,t,e,r)=>{for(var i=r>1?void 0:r?yD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&TD(t,e,i),i};const ED=.8,bD=1.2;let sr=(Wv=class extends Ot{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,ji);g(this,Xr);g(this,Gi);g(this,yl);g(this,Wi);g(this,Ko);g(this,bl);g(this,wl);p(this,"id");p(this,"userId");p(this,"name");p(this,"picture");p(this,"isHost");p(this,"customParticipantId");p(this,"flags");p(this,"device");p(this,"videoTrack");p(this,"audioTrack");p(this,"screenShareTracks");p(this,"videoEnabled");p(this,"audioEnabled");p(this,"screenShareEnabled");p(this,"producers");p(this,"manualProducerConfig");g(this,oa,void 0);p(this,"supportsRemoteControl",!1);g(this,ca,void 0);p(this,"presetName");g(this,Ut,void 0);g(this,pr,void 0);g(this,Jo,void 0);g(this,Zr,new Map);g(this,mr,1);g(this,El,xu(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:n}=this.videoTrack.getSettings();if(!i||!n)return;const o=n/r,c=i/e,d=Math.max(o,c);d>bD&&a(this,mr)===1?(f(this,mr,0),a(this,Ut).getValue("peerSessionStore").emit(k.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,mr)})):d<ED&&a(this,mr)===0&&(f(this,mr,1),a(this,Ut).getValue("peerSessionStore").emit(k.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,mr)}))},2e3));f(this,Ut,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:m,stageStatus:v,customParticipantId:y,audioMuted:w,audioTrack:R,videoEnabled:P=!1,videoTrack:N,producers:$,metadata:x}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=m,this.manualProducerConfig=C_,f(this,ca,v!=null?v:"ON_STAGE"),this.customParticipantId=y,this.audioEnabled=!w,this.audioTrack=R,this.videoEnabled=P,this.videoTrack=N,this.screenShareTracks={audio:void 0,video:void 0},this.producers=$!=null?$:[],this.presetName=x==null?void 0:x.preset_name,f(this,oa,!1),f(this,pr,r),f(this,Jo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),V(this,Ko,np).call(this)}get stageStatus(){return a(this,ca)}get telemetry(){return a(this,Ut).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...Ei(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...Ei(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",V(this,Ko,np)),a(this,Xr,$a)&&(this.on("audioUpdate",V(this,bl,oS)),this.on("screenShareUpdate",V(this,wl,cS)))}async pin(){if(!a(this,Gi,Jc))throw new C("Can`t pin participant without joining room","1205");if(!a(this,pr).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return a(this,ji,Wc).pinPeer(this.id)}async unpin(){if(!a(this,Gi,Jc))throw new C("Can`t unpin participant without joining room","1205");if(!a(this,pr).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return a(this,ji,Wc).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,oa,t);const r=t?"pinned":"unpinned";(i=a(this,Wi,Kc))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info("Participant::disable_audio",{participant:{id:t}}),!a(this,Gi,Jc))throw new C("Can`t disable participant audio without joining room","1205");if(a(this,pr).permissions.canDisableParticipantAudio)return a(this,ji,Wc).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info("Participant::kick",{participant:{id:t}}),!a(this,yl,aS))throw new C("Can`t kick participant without joining room","1205");if(a(this,pr).permissions.kickParticipant){await a(this,Ut).getValue("peerSessionStore").emitAsync(k.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new C("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info("Participant::disable_video",{participant:{id:t}}),!a(this,Gi,Jc))throw new C("Can`t disable participant video without joining room","1205");if(a(this,pr).permissions.canDisableParticipantVideo)return a(this,ji,Wc).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new C("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,Jo).getUserPermissions(this.userId)}setStageStatus(t){f(this,ca,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,oa)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,Zr).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,El).call(this,t)),e.observe(t)),a(this,Zr).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Wi,Kc))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,Wi,Kc))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,Zr).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,Zr).delete(t),(n=a(this,Wi,Kc))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},oa=new WeakMap,ca=new WeakMap,Ut=new WeakMap,ji=new WeakSet,Wc=function(){return a(this,Ut).getValue("roomNodeClient")},Xr=new WeakSet,$a=function(){return a(this,Ut).getValue("audioPlayback")},Gi=new WeakSet,Jc=function(){return a(this,Ut).getValue("connectionHandler").mediaJoined},yl=new WeakSet,aS=function(){return a(this,Ut).getValue("connectionHandler").socketJoined},pr=new WeakMap,Jo=new WeakMap,Zr=new WeakMap,Wi=new WeakSet,Kc=function(){return a(this,Ut).getValue("pip")},mr=new WeakMap,El=new WeakMap,Ko=new WeakSet,np=function(){Array.from(a(this,Zr).keys()).forEach(this.updateVideo)},bl=new WeakSet,oS=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,Xr,$a))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,Xr,$a))==null||e.removeParticipantTrack(this.id)},wl=new WeakSet,cS=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,Xr,$a))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,Xr,$a))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},Wv);On([E.trace("Participant.disableAudio")],sr.prototype,"disableAudio",1),On([E.trace("Participant.kick")],sr.prototype,"kick",1),On([E.trace("Participant.disableVideo")],sr.prototype,"disableVideo",1),On([E.trace("Participant.getPermissions")],sr.prototype,"getPermissions",1),On([E.trace("Participant.setStageStatus")],sr.prototype,"setStageStatus",1),sr=On([dt("1200")],sr);class lo extends If{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:n="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:n},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}class wD extends kn{constructor(e){super(e);g(this,ei,void 0);f(this,ei,new Map)}__set(e,r){return a(this,ei).set(e,r)}__clear(){return a(this,ei).clear()}get(e){return a(this,ei).get(e)}toArray(){return Array.from(a(this,ei).values())}}ei=new WeakMap;class PD{constructor(){p(this,"_orderedArray");p(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const i=this.add(t,e);return r!==i?i:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class _D{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new PD,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}const zf=new _D;var kD=Object.defineProperty,CD=Object.getOwnPropertyDescriptor,Os=(s,t,e,r)=>{for(var i=r>1?void 0:r?CD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&kD(t,e,i),i};const RD=["ACTIVE_GRID","PAGINATED","MANUAL"];let Qt=(Jv=class extends Ot{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,zo);g(this,Ji);g(this,da);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");g(this,Ne,void 0);g(this,Ki,void 0);g(this,kt,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",zf);f(this,Ne,t),f(this,Ki,e),f(this,kt,r),this.waitlisted=new lo(i),this.joined=new lo(i),this.videoSubscribed=new lo(i),this.audioSubscribed=new lo(i),this.active=this.videoSubscribed,this.pinned=new lo(i),this.all=new wD(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Ne).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Ne).getValue("telemetry")}setupEvents(){a(this,Ne).getValue("peerSessionStore").on(k.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Ne).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=a(this,Ne).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,Ne))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new C("0 <= Max active participants count limit <= 24","1203");a(this,Ne).setValue("maxPreferredStreams",t),a(this,da,du)&&a(this,Ne).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!a(this,Ji,zc))throw new C("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return a(this,kt).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,kt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,Ji,zc))throw new C("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;a(this,kt).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>RD.includes(r))(t))throw this.logger.error("Participants::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.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,Ne).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Ne).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Ne).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),a(this,Ne).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new C("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),a(this,Ne).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),n=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(n,o))}async setPage(t){if(this.logger.info("Participants::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 this.logger.error("Participants::invalid_page_number"),new C(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,a(this,Ne).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,da,du))throw new C("Can`t disable all audio without joining room","1205");if(a(this,Ki).permissions.canAllowParticipantAudio)return a(this,zo,ap).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new C("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,da,du))throw new C("Can`t disable all video without joining room","1205");if(a(this,Ki).permissions.canAllowParticipantVideo)return a(this,zo,ap).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Ne).getValue("viewType")!=="LIVESTREAM"&&!a(this,Ji,zc))throw new C("Can`t kick all without joining room","1205");if(!a(this,Ki).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new C("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,kt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,Ji,zc))throw new C("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new C("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,kt).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,kt).broadcastToPeers(t,i,e)}else await a(this,kt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,kt).getRoomPeers(t,e,r)).peers.map(rr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new C("Cannot update permissions, no valid userIDs found","1204");a(this,kt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,kt).getRoomPeersNonPaginated()}},Ne=new WeakMap,zo=new WeakSet,ap=function(){return a(this,Ne).getValue("roomNodeClient")},Ji=new WeakSet,zc=function(){var t;return((t=a(this,Ne).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},da=new WeakSet,du=function(){var t;return((t=a(this,Ne).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ki=new WeakMap,kt=new WeakMap,Jv);Os([E.trace("Participants.setViewMode")],Qt.prototype,"setViewMode",1),Os([E.trace("Participants.setPage")],Qt.prototype,"setPage",1),Os([E.trace("Participants.disableAllAudio")],Qt.prototype,"disableAllAudio",1),Os([E.trace("Participants.disableAllVideo")],Qt.prototype,"disableAllVideo",1),Os([E.trace("Participants.kickAll")],Qt.prototype,"kickAll",1),Os([E.trace("Participants.broadcastMessage"),Dt(Rn,"rateLimitConfig")],Qt.prototype,"broadcastMessage",1),Os([E.trace("Participants.getAllJoinedPeers"),Dt({maxInvocations:10,period:60})],Qt.prototype,"getAllJoinedPeers",1),Os([E.trace("Participant.updatePermissions"),Dt({maxInvocations:1e3,period:60})],Qt.prototype,"updatePermissions",1),Os([E.trace("Participants.getParticipantsInMeetingPreJoin")],Qt.prototype,"getParticipantsInMeetingPreJoin",1),Qt=Os([dt("1200")],Qt);var ID=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,bi=(s,t,e,r)=>{for(var i=r>1?void 0:r?AD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&ID(t,e,i),i};const Yf=(Kv=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",zf);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);g(this,rs,{mode:"ACTIVE_GRID",page:0});g(this,Ts,!1);g(this,la,!1);p(this,"updateConsumerSpatialLayers",xu(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));p(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, ConsumersSyncing: ${a(this,Ts)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new Qt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=hs,t.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on(U.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(k.SOCKET_PEERS,s=>{const t=this.participants.joined.size>0;this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.joined.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",t&&this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))})}),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:s})=>{this.logger.info("PEER_INFO:::MEDIA_JOIN",{participant:{id:s.peerId,maskedName:[...(s==null?void 0:s.displayName)||""].map((t,e)=>e%2?"*":t).join("")}}),this.onParticipantMediaJoined(s.peerId,s.producerStates)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{s.forEach(({peerId:n,producerStates:o})=>this.onParticipantMediaJoined(n,o));const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};e.pinnedPeerIds.length!==0&&this.onParticipantPinned(e.pinnedPeerIds[0]),this.computeActivateParticipants(r!=null?r:[],i),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(k.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(k.NEW_PRODUCER,({peerId:s,producer:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:t==null?void 0:t.producerId,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}},participant:{id:s}});return}e.producers.push(t),this.logger.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}}}),(t==null?void 0:t.kind)==="audio"&&this.participants.audioSubscribed.get(s)||(t==null?void 0:t.kind)==="video"&&this.participants.videoSubscribed.get(s)||t!=null&&t.screenShare?(this.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${t.producerId}, Peer: ${s}, Kind: ${t.kind}, ScreenShare: ${t.screenShare}, ConsumersSyncing: ${a(this,Ts)}, VideoSub: ${t.kind==="video"?this.participants.videoSubscribed.has(s):"N/A"}, AudioSub: ${t.kind==="audio"?this.participants.audioSubscribed.has(s):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"UNKNOWN",appData:{screenShare:t==null?void 0:t.screenShare}}})}),this.context.getValue("peerSessionStore").on(k.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{participant:{id:s}});return}e.producers=e.producers.filter(r=>r.producerId!==t)}),this.context.getValue("peerSessionStore").on(k.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){r==="audio"&&i.setAudioEnabled(!e);const n=i.producers.find(o=>o.producerId===t);n&&(n.pause=e),r==="video"&&this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${a(this,Ts)}, ProducerIds: [${r.producers.map(i=>i.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:s,compulsoryPeers:t})=>{this.mediaJoined&&this.onSelectedPeers(t.concat(s))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:s})=>{if(!this.mediaJoined)return;const t=s.map(e=>({peerId:e.peerId,priority:e.priority}));this.updateActiveParticipantsWithPriorities(t,!0)})}waitingRoomRequestHandler(s){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(i=>i.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(i=>i.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new sr(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),i=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),n=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(n,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):u.push(h.id),u),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=s-n,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(h=>!c.has(h)&&h!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&a(this,rs).mode!==s&&(a(this,rs).mode=s),e&&a(this,rs).page!==e&&(a(this,rs).page=e);const{mode:r,page:i}=a(this,rs);switch(r){case"PAGINATED":{if(!i)return;const n=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:n});break}case"ACTIVE_GRID":{const n=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":break;default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=a(this,rs))==null?void 0:e.mode)==="PAGINATED"&&!a(this,Ts)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,rs))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,Ts)}, Delay: ${t}, Page: ${(i=a(this,rs))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var c,d,l,u,h;if(((l=(d=(c=this.context.getValue("connectionHandler"))==null?void 0:c.mediaState)==null?void 0:d.recv)==null?void 0:l.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,Ts)){f(this,la,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,Ts,!0),f(this,la,!1);let s=[];this.participants.videoSubscribed.forEach(m=>{var w,R;const v=this.participants.joined.get(m.id),y=(R=(w=m.producers)==null?void 0:w.filter(P=>P.kind==="video"))!=null?R:[];v&&(y!=null&&y.length)&&y.forEach(P=>{var x,H,F,Z;const N=((H=(x=v.manualProducerConfig)==null?void 0:x.video)!=null?H:!0)&&P.kind==="video"&&!P.screenShare,$=((Z=(F=v.manualProducerConfig)==null?void 0:F.screenshareVideo)!=null?Z:!0)&&P.kind==="video"&&P.screenShare;(N||$)&&(P.pause||s.push(P))})}),this.participants.audioSubscribed.forEach(m=>{var w,R;const v=this.participants.joined.get(m.id),y=(R=(w=m.producers)==null?void 0:w.filter(P=>P.kind==="audio"))!=null?R:[];v&&(y!=null&&y.length)&&y.forEach(P=>{var x,H,F,Z;const N=((H=(x=v.manualProducerConfig)==null?void 0:x.audio)!=null?H:!0)&&P.kind==="audio"&&!P.screenShare,$=((Z=(F=v.manualProducerConfig)==null?void 0:F.screenshareAudio)!=null?Z:!0)&&P.kind==="audio"&&P.screenShare;(N||$)&&s.push(P)})}),s=k_(s,m=>m.producerId);const t=new Map;s.forEach(m=>{t.set(m.producerId,m)});const e=(u=this.roomNodeClient)==null?void 0:u.getConsumers(),r=s.filter(m=>!(e!=null&&e.has(m.producerId)));s.filter(m=>!m.consumer&&(e==null?void 0:e.has(m.producerId))).forEach(m=>{const v=e.get(m.producerId);v&&(this.logger.info(`syncConsumers: remapping existing consumer ${v.id} to producer ${m.producerId}`),this.context.getValue("peerSessionStore").emit(k.NEW_CONSUMER,{id:v.id,appData:v.appData,peerId:v.peerId}))});const n=[];let o=Array.from((h=e==null?void 0:e.values())!=null?h:[]).map(m=>m.peerId);o=__(o),o==null||o.forEach(m=>{var y;const v=this.participants.joined.get(m);if(!v){this.logger.warn(`Peer with ${m} doesn't exist in joined list but producers of it are being consumed.`);return}(y=v.producers)!=null&&y.length&&v.producers.forEach(w=>{const R=w.consumer&&e.has(w.consumer.id);!t.has(w.producerId)&&(e.has(w.producerId)||R)&&n.push(w)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(m=>m.producerId).join(", ")}], RemoveProducers: ${n.length} [${n.map(m=>m.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||n.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${n.length}.`),await this.updateConsumers(r,n),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(m){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:m})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,Ts,!1)}a(this,la)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,n)=>({peerId:i,priority:n+1})),r=t==null?void 0:t.map((i,n)=>({peerId:i,priority:-(n+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=Yf.formatSocketPeerMessage(s);return new sr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:e.id,maskedName:[...(e==null?void 0:e.name)||""].map((r,i)=>i%2?"*":r).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(r=>{r.kind===zs.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===zs.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===zs.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),n=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&n.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=n.shift();e[c]=o}),n.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{participant:{id:o}});return}s.add(this.participants.joined.get(o),!r.get(o))}),s.emit("participantsUpdate")}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{s.get(r)||s.add(this.participants.joined.get(r),!0)}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on(U.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info("Processed socket join",{peers:s.peerId}))}),this.roomSocketHandler.on(U.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,()=>{this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(k.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(k.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(k.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(k.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(k.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(k.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(k.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(k.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const n=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(k.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(k.UPDATE_ACTIVE,async({viewMode:s,page:t,createAllConsumers:e}={viewMode:"ACTIVE_GRID",page:0,createAllConsumers:!1})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,rs).mode}, page: ${t}, CreateAllConsumers: ${e}`),e&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${s}, Page: ${t}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),this.updateMediaSubscribedMaps(s,{page:t}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"})})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantSocketJoined(s){var t,e,r;this.logger.info(`onParticipantSocketJoined: peer ${s.id} has joined socket edge. Processing.`),this.self.id!==s.id&&!((t=s.flags)!=null&&t.recorder)&&!((e=s.flags)!=null&&e.hidden_participant)&&!((r=s.flags)!=null&&r.hiddenParticipant)&&(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(k.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(k.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),this.roomNodeClient&&this.roomNodeClient.closeConsumers(t==null?void 0:t.producers),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(k.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),i=this.participants.videoSubscribed.get(s);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e}):r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):i&&this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:n,producerId:o,rtpReceiver:c,paused:d,localId:l}=(h=t.get(s))!=null?h:{};if(!e)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:!!(i!=null&&i.supportsRemoteControl),screenShare:!!(i!=null&&i.screenShare)},remotelyPaused:d,producerId:o}}),{};const u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n}=this.consumerPeerMap.get(s)||{},o=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:n}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===n);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,rtpReceiver:void 0,localId:void 0});const d=[];r&&r.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}),o.audioTrack=void 0):e==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1}),o.videoTrack=void 0),r.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(k.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:l})})}processConsumerResumed(s){var m;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const h=u.producers.find(v=>v.producerId===c);if(h&&(h.consumer={id:s,peerId:e,kind:r,appData:i,paused:o,producerId:c,rtpReceiver:d,localId:l}),i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:n}),i.screenShare){r==="video"?u.screenShareTracks.video=n:r==="audio"&&(u.screenShareTracks.audio=n),u.setScreenShareEnabled(!0),(m=this.context)==null||m.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:n,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:n,paused:r,producerId:o,rtpReceiver:c,localId:d}),n.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),n.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&n.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=fh(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(n=s.flags)==null?void 0:n.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},rs=new WeakMap,Ts=new WeakMap,la=new WeakMap,Kv);let rr=Yf;bi([E.trace("ParticipantController.setupEvents")],rr.prototype,"setupEvents",1),bi([E.trace("ParticipantController.setupEvents")],rr.prototype,"setupEventsGlobal",1),bi([E.trace("ParticipantController.processMedia")],rr.prototype,"processMedia",1),bi([E.trace("ParticipantController.processConsumerClosed")],rr.prototype,"processConsumerClosed",1),bi([E.trace("ParticipantController.processConsumerResumed")],rr.prototype,"processConsumerResumed",1),bi([E.trace("ParticipantController.processConsumerPaused")],rr.prototype,"processConsumerPaused",1),bi([E.trace("ParticipantController.processNewConsumer")],rr.prototype,"processNewConsumer",1);const Ae=Is(Fu().permissions),_l=class extends Ot{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);g(this,Tt);g(this,Y,void 0);g(this,ua,void 0);g(this,ha,void 0);g(this,Pl,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Cr(a(this,Y).chat.private,r.private),r.public&&Cr(a(this,Y).chat.public,r.public),this.emit("chatUpdate")),i&&Cr(a(this,Y).connectedMeetings,i),c){const m=y=>{switch(y){case Ir.NONE:return G.Allowed;case Ir.ALLOWED:return G.Allowed;case Ir.NOT_ALLOWED:return G.NotAllowed;case Ir.CAN_REQUEST:return G.CanRequest;default:return}},v={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(v.audio={canProduce:m(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(v.video={canProduce:m(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(v.screenshare={canProduce:m(c.screenshare.canProduce)}),Cr(a(this,Y).media,v)}n&&(Cr(a(this,Y).plugins,n),this.emit("pluginsUpdate")),o&&(Cr(a(this,Y).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Cr(a(this,Y),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new C("Could not load preset permissions.","0904");f(this,ha,e),f(this,ua,i),f(this,Y,r),n&&this.setupEvents()}setupEvents(){a(this,ha).getValue("peerSessionStore").on(k.UPDATE_PERMISSIONS,a(this,Pl))}static init(e,r,i){let n;return i?n=new _l(e,i,r,!0):n=new _l(e,Ae,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,Y))==null?void 0:e.stageEnabled)||a(this,ua)===Ws.Webinar||a(this,ua)===Ws.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,Y))==null?void 0:e.acceptStageRequests)||((r=a(this,Y))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,Y))==null?void 0:e.stageAccess)===G.NotAllowed?G.NotAllowed:((r=a(this,Y))==null?void 0:r.stageAccess)===G.CanRequest?G.CanRequest:((i=a(this,Y))==null?void 0:i.stageAccess)===G.Allowed||a(this,Y).media.audio.canProduce===G.Allowed||a(this,Y).media.video.canProduce===G.Allowed||a(this,Y).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,Y).media.audio.canProduce===G.CanRequest||a(this,Y).media.video.canProduce===G.CanRequest||a(this,Y).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.acceptWaitingRequests)!=null?r:Ae.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===G.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.disableParticipantAudio)!=null?r:Ae.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canAcceptProductionRequests)!=null?r:Ae.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.disableParticipantVideo)!=null?r:Ae.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.kickParticipant)!=null?r:Ae.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.pinParticipant)!=null?r:Ae.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canRecord)!=null?r:Ae.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.waitingRoomType)!=null?r:Ae.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.plugins)!=null?r:Ae.plugins}get polls(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.polls)!=null?r:Ae.polls}get canProduceVideo(){var r;const e=(r=a(this,Y).media.video.canProduce)!=null?r:Ae.media.video.canProduce;return this.stageEnabled&&(a(this,Tt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Tt,Gt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Tt,Gt)==="OFF_STAGE"||a(this,Tt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,Y).media.screenshare.canProduce)!=null?r:Ae.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Tt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Tt,Gt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Tt,Gt)==="OFF_STAGE"||a(this,Tt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,Y).media.audio.canProduce)!=null?r:Ae.media.audio.canProduce;return this.stageEnabled&&(a(this,Tt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Tt,Gt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,Tt,Gt)==="OFF_STAGE"||a(this,Tt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Ae.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Ae.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.connectedMeetings)!=null?r:Ae==null?void 0:Ae.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.hiddenParticipant)!=null?r:Ae.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,Y).showParticipantList)!=null?e:Ae.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Ae.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,Y).canEditDisplayName)!=null?e:!1}get isRecorder(){return a(this,Y).isRecorder}get canSpotlight(){return a(this,Y).canSpotlight}get canLivestream(){return a(this,Y).canLivestream}get transcriptionEnabled(){return a(this,Y).transcriptionEnabled}};let Ch=_l;Y=new WeakMap,ua=new WeakMap,ha=new WeakMap,Pl=new WeakMap,Tt=new WeakSet,Gt=function(){return a(this,ha).getValue("stageStatus")};class Qf extends Ot{constructor(e,r){super(r);p(this,"localMediaHandler");g(this,$t,void 0);f(this,$t,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const m={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,$t).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_ERROR,m):a(this,$t).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,m)};if(Te.getName()==="firefox")return;const r="microphone",i="camera",n=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,h)=>{switch(h){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};n&&(n.onchange=()=>c("audio",n.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,n,o,c;switch(r){case"audio":{(i=a(this,$t))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,$t))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,$t))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,$t))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,$t))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(Te.init(),i&&f(this,$t,i),!this.localMediaHandler)try{let m=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)m=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:v}=navigator;this.localMediaHandler=await v.init(e)}else this.localMediaHandler=new Pt(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(k.MEDIA_PERMISSION_UPDATE,async v=>{if(this.populateMediaPermissionsInCallstats({message:v.message,kind:v.kind}),v.message==="NOT_REQUESTED")switch(v==null?void 0:v.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",v)}),i==null||i.getValue("peerSessionStore").on(k.MEDIA_PERMISSION_ERROR,async v=>{const{kind:y,message:w,constraints:R}=v;this.populateMediaPermissionsInCallstats({message:w,kind:y}),y==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:w},constraints:R,mediaPermissionsErrors:{kind:y,message:w}}),this.emit("mediaPermissionError",v),this.emit("mediaPermissionUpdate",{message:w,kind:y})}),m){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const v=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});r||await v}}catch(m){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:m.name,message:m.message}})}}set context(e){f(this,$t,e),this.localMediaHandler.context=e}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}async removeAllAudioMiddlewares(){return this.localMediaHandler.removeAllAudioMiddlewares()}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}async removeAllVideoMiddlewares(){return this.localMediaHandler.removeAllVideoMiddlewares()}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}async enableAudio(){await this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}$t=new WeakMap;var MD=Object.defineProperty,OD=Object.getOwnPropertyDescriptor,gt=(s,t,e,r)=>{for(var i=r>1?void 0:r?OD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&MD(t,e,i),i};let Je=(zv=class extends Qf{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);g(this,gr);g(this,Xe);g(this,ga);g(this,$e);g(this,Yo);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");g(this,pa,void 0);g(this,yt,void 0);g(this,ma,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");g(this,Qe,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");g(this,fa,new Set);g(this,va,new Set);f(this,Qe,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",f(this,yt,r),f(this,pa,i),this.hidden=!1,f(this,ma,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Te.isElectron(),this.device=Te.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),V(this,Yo,op).call(this)}get telemetry(){return a(this,Qe).getValue("telemetry")}get stageStatus(){return a(this,Qe).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,Xe,mt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,Qe).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var m,v,y,w,R,P;let c=(v=(m=t.getValue("defaults"))==null?void 0:m.audio)!=null?v:!0,d=(w=(y=t.getValue("defaults"))==null?void 0:y.video)!=null?w:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Je(t,e,r,i,n),u=HO(i.mediaConstraints);Cr(u,(R=t.getValue("defaults"))==null?void 0:R.mediaConfiguration);const h=(P=t.getValue("defaults"))==null?void 0:P.mediaHandler;return h&&(h.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),a(this,yt).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",V(this,Yo,op));const t=a(this,ga,lu);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...Ei(this)}),a(this,$e,Ge)&&this.audioEnabled)try{await a(this,Xe,mt).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...Ei(this)}),a(this,$e,Ge)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,Ge))try{await a(this,Xe,mt).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:e})=>{var r;this.emit("deviceUpdate",{device:e}),e.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((r=a(this,ga,lu))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!a(this,$e,Ge)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,Xe,mt).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...Ei(this)}),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),this.logger.info("Self::setupEvents::SCREENSHARE_ENDED",{...Ei(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,Qe))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;a(this,$e,Ge)&&await a(this,Xe,mt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,Qe))==null||e.getValue("callstats").videoOff()}),a(this,yt).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,yt).canProduceAudio!==G.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&a(this,yt).canProduceVideo!==G.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,yt).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,yt)}get config(){return a(this,pa)}get roomJoined(){var t;return a(this,pa).viewType===Ws.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Qe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,Ge)}setName(t){if(!t)throw new C("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==G.NotAllowed&&!(a(this,yt).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,Qe))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,$e,Ge)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,Xe,mt).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(a(this,yt).canProduceVideo!==G.NotAllowed&&!(a(this,yt).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,Qe))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,$e,Ge)&&this.stageStatus==="ON_STAGE")try{await a(this,Xe,mt).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...Ei(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,$e,Ge))throw new C("Can`t enable screenshare without joining room","1105");if(a(this,yt).canProduceScreenshare!==G.NotAllowed&&!(a(this,yt).canProduceScreenshare===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await a(this,Xe,mt).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,$e,Ge)&&a(this,Xe,mt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,Qe))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,$e,Ge)&&await a(this,Xe,mt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,Qe))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,$e,Ge)&&await a(this,Xe,mt).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,ma,t);const r=t?"pinned":"unpinned";(i=a(this,gr,fn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,ma)}async pin(){if(!a(this,$e,Ge))throw new C("Can`t pin participants without joining room","1105");return this.show(),a(this,Xe,mt).pinPeer(this.id)}async unpin(){if(!a(this,$e,Ge))throw new C("Can`t unpin participants without joining room","1105");return a(this,Xe,mt).pinPeer(null)}async hide(){if(!a(this,$e,Ge))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,$e,Ge))throw new C("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,n;if(!t)throw new C("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((n=e==null?void 0:e.speaker)==null?void 0:n.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){a(this,$e,Ge)&&await a(this,Xe,mt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t,{saveDevicePreference:!0})}catch(o){a(this,$e,Ge)&&await a(this,Xe,mt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=a(this,ga,lu))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,fa).add(t):a(this,va).add(t),this.updateVideo(t),e||(i=a(this,gr,fn))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){a(this,gr,fn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,fa).delete(t):(a(this,va).delete(t),a(this,gr,fn).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=a(this,gr,fn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,gr,fn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},pa=new WeakMap,yt=new WeakMap,ma=new WeakMap,Qe=new WeakMap,gr=new WeakSet,fn=function(){return a(this,Qe).getValue("pip")},Xe=new WeakSet,mt=function(){return a(this,Qe).getValue("roomNodeClient")},ga=new WeakSet,lu=function(){return a(this,Qe).getValue("audioPlayback")},$e=new WeakSet,Ge=function(){var t;return((t=a(this,Qe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},fa=new WeakMap,va=new WeakMap,Yo=new WeakSet,op=function(){Array.from(a(this,va)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,fa)).forEach(t=>this.updateVideo(t,!0))},zv);gt([E.trace("Self.cleanupEvents")],Je.prototype,"cleanupEvents",1),gt([E.trace("Self.setupEvents")],Je.prototype,"setupEvents",1),gt([E.trace("Self.setupTracks")],Je.prototype,"setupTracks",1),gt([E.trace("Self.destructMediaHandler")],Je.prototype,"destructMediaHandler",1),gt([E.trace("Self.removeDocumentEventListeners")],Je.prototype,"removeDocumentEventListeners",1),gt([tr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],Je.prototype,"enableAudio",1),gt([tr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],Je.prototype,"enableVideo",1),gt([E.trace("Self.updateVideoConstraints")],Je.prototype,"updateVideoConstraints",1),gt([E.trace("Self.enableScreenShare"),tr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Je.prototype,"enableScreenShare",1),gt([E.trace("Self.updateScreenshareConstraints")],Je.prototype,"updateScreenshareConstraints",1),gt([tr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],Je.prototype,"disableAudio",1),gt([tr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],Je.prototype,"disableVideo",1),gt([tr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],Je.prototype,"disableScreenShare",1),gt([E.trace("Self.setDevice")],Je.prototype,"setDevice",1),Je=gt([dt("1100")],Je);class Rh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Rh)}}class Ih extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ih)}}class Ah{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);g(this,Qo,void 0);this.log=e,f(this,Qo,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,n)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),n(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new Rh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Ih)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();a(this,Qo).info(`AwaitQueue.push(${t.name})_timings`,{awaitQueueTask:{id:t.id,metadata:t.metadata,queueSizeAtStart:e,execTime:(i-t.executedAt)/1e3,taskStartTime:(t.executedAt-t.enqueuedAt)/1e3}}),t.resolve(r)}catch(e){t.reject(e)}}}Qo=new WeakMap;function DD(s,t){const e=new Error(t);return e.name=s,e}class uo extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,uo):this.stack=new Error(t).stack}}class _t extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,_t):this.stack=new Error(t).stack}}class Lr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,_t):this.stack=new Error(t).stack}}const Xf=s=>new Promise(t=>setTimeout(t,s));async function Zf(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:n,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=h=>{l=!0,r(h)};for(;c<n;){try{const h=await s(c,u);return e(h)}catch(h){if(d=h,l)break;if(c<n)i==="linear"?await Xf(o*(c+1)):i==="exponential"&&await Xf(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function ND(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function VD(s){return s.map(t=>({uri:t.uri}))}function Gd(s){return{codecs:ND(s.codecs),headerExtensions:VD(s.headerExtensions?s.headerExtensions:[])}}function LD(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const n={audio:Gd(t),video:Gd(e)};return{sender:{audio:Gd(r),video:Gd(i)},receiver:n}}class xD{constructor(t){g(this,Ze,void 0);p(this,"events");f(this,Ze,t),this.events=hs}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,Ze).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:oC.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,Ze).sendMessagePromise(this.events.createWebRTCTransport,Vk.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=$g.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:n}}async produce(t){var n,o;const e=(await a(this,Ze).sendMessagePromise(this.events.produce,bC.toBinary(t))).payload,r=iR.fromBinary(e);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await a(this,Ze).sendMessagePromise(this.events.consume,fC.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=sR.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,Ze).sendMessagePromise(this.events.closeProducer,IC.toBinary(t))).payload,{description:r}=uR.fromBinary(e);return r}async closeConsumer(t){return(await a(this,Ze).sendMessagePromise(this.events.closeConsumer,MC.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,Ze).sendMessagePromise(this.events.updateConsumersSimulcastConfig,yC.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,Ze).sendMessagePromise(this.events.hostControlPeer,xC.toBinary(r))).payload;if(!i)return!1;const{status:n}=SR.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,Ze).sendMessagePromise(this.events.hostControlAllPeers,$C.toBinary(e))).payload;if(!r)return!1;const{status:i}=yR.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,Ze).sendMessagePromise(U.kickAll,Gg.toBinary(t))}async kickPeer(t){a(this,Ze).sendMessagePromise(U.kick,of.toBinary(t))}async changeDisplayName(t){const e=(await a(this,Ze).sendMessagePromise(this.events.changeDisplayName,VC.toBinary(t))).payload;if(!e)return!1;const{status:r}=bR.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,Ze).sendMessagePromise(this.events.selfJoinComplete,dC.toBinary(t))).payload;return Yu.fromBinary(e)}async audioActivity(t){a(this,Ze).sendMessage(this.events.audioActivity,xk.toBinary(t))}}Ze=new WeakMap;var Ds=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Ds||{});class Wd extends ct.EventEmitter{constructor(e){super();g(this,Xo,void 0);f(this,Xo,e),this.setMaxListeners(1/0)}get logger(){return a(this,Xo).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((n,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,n,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}Xo=new WeakMap;class Mh extends Wd{constructor(){super(...arguments);p(this,"_sendWebStream",new MediaStream);p(this,"_sendScreenShareStream",new MediaStream);p(this,"_direction");p(this,"pc");p(this,"_transportReady",!1);p(this,"_mapMidTransceiver",new Map);p(this,"enableHighBitrate",!1);p(this,"enableStereo",!1);p(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...n},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.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 i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(n)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{n.encodings[c]={...o,...r}}),await i.sender.setParameters(n)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class Oh extends Mh{static createFactory(t){return()=>new Oh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:n,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var m;const h=d.codecs.find(v=>v.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const v=((m=h.sdpFmtpLine)==null?void 0:m.split(";"))||[];v.push(...u.parameters);const y=Array.from(new Set(v).values());h.sdpFmtpLine=y.join(";")}l.push(h)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),n.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
15
- `}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}var ev={},Jd={},UD={get exports(){return Jd},set exports(s){Jd=s}},tv=UD.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{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(tv).forEach(function(s){var t=tv[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(c){return String(Number(c))===c?Number(c):c},e=function(c,d,l,u){if(u&&!l)d[u]=t(c[1]);else for(var h=0;h<l.length;h+=1)c[h+1]!=null&&(d[l[h]]=t(c[h+1]))},r=function(c,d,l){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var h=c.push?{}:u?d[c.name]:d;e(l.match(c.reg),h,c.names,c.name),c.push&&d[c.push].push(h)},i=Jd,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var m=h[0],v=h.slice(2);m==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var y=0;y<(i[m]||[]).length;y+=1){var w=i[m][y];if(w.reg.test(v))return r(w,u,v)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=t(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};s.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(c){return c.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(t),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},s.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},s.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}}(ev);var Dh=Jd,$D=/%[sdv%]/g,BD=function(s){var t=1,e=arguments,r=e.length;return s.replace($D,function(i){if(t>=r)return i;var n=e[t];switch(t+=1,i){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},ho=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,i=[s+"="+r];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?i.push(e[t.name][o]):i.push(e[t.names[n]])}else i.push(e[t.name]);return BD.apply(null,i)},FD=["v","o","s","i","u","e","p","c","b","t","r","z","a"],HD=["i","c","b","a"],qD=function(s,t){t=t||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=t.outerOrder||FD,r=t.innerOrder||HD,i=[];return e.forEach(function(n){Dh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(ho(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(ho(n,o,c))})})}),s.media.forEach(function(n){i.push(ho("m",Dh.m[0],n)),r.forEach(function(o){Dh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(ho(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(ho(o,c,d))})})})}),i.join(`\r
9
+ `)),this.pc2.setLocalDescription(t),this.pc1.setRemoteDescription(t)}establishConnection(){this.pc1.createOffer().then(this.gotOffer.bind(this),this.reportFatal.bind(this))}reportFatal(t){console.error("Error:",t)}async getRoundTripTime(){const[t,e]=await Promise.all([this.pc1.getStats(),this.pc2.getStats()]);let r,i;if(t.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesSent>0&&(r=n)}),e.forEach(n=>{n.type==="candidate-pair"&&n.nominated===!0&&n.bytesReceived>0&&(i=n)}),r&&i)try{if(r.currentRoundTripTime&&i.currentRoundTripTime)return{rtt:r.currentRoundTripTime,backendRTT:i.currentRoundTripTime};const n=(i.lastPacketReceivedTimestamp-r.lastPacketSentTimestamp)/1e3;return{rtt:n,backendRTT:n}}catch(n){return}}close(){this.pc1.close(),this.pc2.close()}}class Qp extends dt{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new qs(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 fT=8,ST=1/1e3;class vT extends Qp{constructor(e){super(e);p(this,"senderChannel");p(this,"recieveChannel");p(this,"startTime");p(this,"lastBitrateMeasureTime");p(this,"sentPayloadBytes",0);p(this,"recievedPayloadBytes",0);p(this,"lastReceivedPayloadBytes",0);p(this,"stopSending",!1);p(this,"testProgress",0);p(this,"samplePacket","");p(this,"finalBitrateSum",0);p(this,"bitRateSampels",0);p(this,"maxNumberOfPacketsToSend",0);p(this,"bytesToKeepBuffered",0);p(this,"testDurationSeconds",5);this.call.setIceCandidateFilter(qs.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 i=0;i!==this.maxNumberOfPacketsToSend&&!(this.senderChannel.bufferedAmount>=this.bytesToKeepBuffered);i+=1){this.sentPayloadBytes+=this.samplePacket.length;try{this.senderChannel.send(this.samplePacket)}catch(n){}}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,i=r.getTime()-this.lastBitrateMeasureTime.getTime();if(i>=1e3){const o=(this.recievedPayloadBytes-this.lastReceivedPayloadBytes)*fT/(i/1e3);this.finalBitrateSum+=o,this.bitRateSampels+=1,this.lastReceivedPayloadBytes=this.recievedPayloadBytes,this.lastBitrateMeasureTime=r}if(this.stopSending&&this.sentPayloadBytes===this.recievedPayloadBytes){const n=this.finalBitrateSum/this.bitRateSampels;this.testComplete({throughput:Math.round(n*ST)})}}testComplete(e){this.call.getRoundTripTime().then(({rtt:r,backendRTT:i})=>super.testComplete({RTT:r,backendRTT:i,throughput:e.throughput}))}onRecieverChannel(e){this.recieveChannel=e.channel,this.recieveChannel.addEventListener("message",this.onMessageRecieved.bind(this))}}class fu extends Qp{constructor(e,r=qs.noFilter){super(e);p(this,"ch1");p(this,"ch2");this.call.setIceCandidateFilter(r);const i=this.call.pc1.createDataChannel(null);this.ch1=i,i.addEventListener("open",()=>{i.send("hello")}),i.addEventListener("message",this.onCh1Recieve.bind(this)),this.call.pc2.addEventListener("datachannel",this.dataChannelHandler.bind(this))}onCh1Recieve(e){e.data!=="world"?this.hangup("Invalid data transmitted."):this.testComplete({connectivity:!0})}onCh2Recieve(e){if(e.data!=="hello")this.hangup("Invalid data transmitted.");else try{this.ch2.send("world")}catch(r){}}dataChannelHandler(e){const r=e.channel;this.ch2=r,r.addEventListener("message",this.onCh2Recieve.bind(this))}hangup(e){this.testFailed(e)}}class TT extends fu{constructor(t){super(t,qs.isHost)}}class yT extends fu{constructor(t){super(t,qs.isRelay)}}class ET extends fu{constructor(t){super(t,qs.isReflexive)}}class bT{constructor(){p(this,"ipInformation",null)}async getIPDetails({peerId:t,apiHostnames:e,logger:r}){var i,n,o;if(!this.ipInformation){try{const c=`https://${e.location}`,l=await(await fetch(c)).json();if(((i=l.loc)==null?void 0:i.length)>5)return this.ipInformation=l,(n=this.ipInformation)!=null&&n.ip&&(this.ipInformation.ip=kr(this.ipInformation.ip)),l;throw Error("Insufficient data")}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using location service",{error:c})}try{const c=await fetch(`https://${e.locationLegacy}/?token=3c493932b0624c&peerId=${t}`,{method:"POST"});this.ipInformation=await c.json(),(o=this.ipInformation)!=null&&o.ip&&(this.ipInformation.ip=kr(this.ipInformation.ip))}catch(c){r.error("callstats::ipDetails:: failed to fetch ip using legacy location service",{error:c})}}return this.ipInformation}resetCache(){this.ipInformation=null}}const Xp=new bT,Zp=[{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 em(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class tm{constructor(){p(this,"transport");p(this,"candidatePair");p(this,"outboundVideoRtp",new Map);p(this,"inboundVideoRtp",new Map);p(this,"outboundAudioRtp",new Map);p(this,"inboundAudioRtp",new Map);p(this,"remoteInboundRtp",new Map);p(this,"producerStreamMap",new Map);p(this,"consumerStreamMap",new Map);p(this,"staleProducerStreamMap",!1);p(this,"staleConsumerStreamMap",!1)}}class sm extends dt{constructor(){super();p(this,"observer");p(this,"outboundProducerMap",new Map);p(this,"inboundConsumerMap",new Map);p(this,"consumerPeerIdMap",new Map);p(this,"pausedConsumerMap",new Map);p(this,"pausedProducerMap",new Map);p(this,"overallProducingTransportsStatsMap",{});p(this,"overallConsumingTransportsStatsMap",{});p(this,"overallConsumersStatsMap",{});p(this,"overallProducersStatsMap",{});p(this,"videoProducerToStatsMap",new Map);p(this,"audioProducerToStatsMap",new Map);p(this,"videoConsumerToStatsMap",new Map);p(this,"audioConsumerToStatsMap",new Map);p(this,"consumerIdsWithFreezedVideo",new Set);p(this,"consumerIdsWithFreezedAudio",new Set);p(this,"producerIdsWithFreezedVideo",new Set);p(this,"producerIdsWithFreezedAudio",new Set);p(this,"freezedProducingTransportIds",new Set);p(this,"freezedConsumingTransportIds",new Set);p(this,"screenShareProducers",new Set);p(this,"screenShareConsumers",new Set);p(this,"ipDetails");p(this,"callStatsInstance");this.observer=new dt}async registerProducer(e){await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}pauseProducer(e){this.pausedProducerMap.set(e,{lastReportCalculated:!1})}resumeProducer(e){this.pausedProducerMap.delete(e)}processInboundConsumerVideoStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalVideoPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","pause",e))):(r.totalVideoPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedVideo.has(e)&&(this.consumerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callstats::measurements::consumerVideoDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_video_status","resume",e))))}processInboundConsumerAudioStats(e,r,i){var o,c;const n=((c=(o=this==null?void 0:this.callStatsInstance)==null?void 0:o.consumerSharedMediaStatesMap)==null?void 0:c.get(e))||{};r.totalAudioPacketsReceived===i.packetsReceived?(this.consumerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioFreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","pause",e))):(r.totalAudioPacketsReceived=i.packetsReceived,this.consumerIdsWithFreezedAudio.has(e)&&(this.consumerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::consumerAudioDefreezed",{consumerId:e}),this.callStatsInstance.eventHandler.emit("consumer_audio_status","resume",e))))}processOutboundProducerVideoStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalVideoPacketsSent===i.packetsSent?(this.producerIdsWithFreezedVideo.add(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","pause",e))):(r.totalVideoPacketsSent=i.packetsSent,this.producerIdsWithFreezedVideo.has(e)&&(this.producerIdsWithFreezedVideo.delete(e),this.callStatsInstance&&n.video&&(this.callStatsInstance.logger.debug("callStats::measurements::producerVideoDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_video_status","resume",e))))}processOutboundProducerAudioStats(e,r,i){var o;const n=((o=this==null?void 0:this.callStatsInstance)==null?void 0:o.currentUserMediaStates)||{};r.totalAudioPacketsSent===i.packetsSent?(this.producerIdsWithFreezedAudio.add(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioFreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","pause",e))):(r.totalAudioPacketsSent=i.packetsSent,this.producerIdsWithFreezedAudio.has(e)&&(this.producerIdsWithFreezedAudio.delete(e),this.callStatsInstance&&n.audio&&(this.callStatsInstance.logger.debug("callStats::measurements::producerAudioDefreezed",{producerId:e}),this.callStatsInstance.eventHandler.emit("producer_audio_status","resume",e))))}processProducingTransportStats(e,r,i){var u;const n=((u=this==null?void 0:this.callStatsInstance)==null?void 0:u.currentUserMediaStates)||{},{audio:o,video:c,screen:d}=n,l=o||c||d;r.totalPacketsSent===i.packetsSent?(this.freezedProducingTransportIds.add(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportFreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","pause",e))):(r.totalPacketsSent=i.packetsSent,this.freezedProducingTransportIds.has(e)&&(this.freezedProducingTransportIds.delete(e),this.callStatsInstance&&l&&(this.callStatsInstance.logger.debug("callStats::measurements::producingTransportDefreezed",{transportId:e}),this.callStatsInstance.eventHandler.emit("producing_transport_status","resume",e))))}processConsumingTransportStats(e,r,i){var c,d;const o=!!Array.from(((d=(c=this==null?void 0:this.callStatsInstance)==null?void 0:c.consumerSharedMediaStatesMap)==null?void 0:d.values())||[]).reduce((l,u)=>l||u.audio||u.video||u.screen,!1);r.totalPacketsReceived===i.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=i.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))))}async registerConsumer(e){await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}pauseConsumer(e){this.pausedConsumerMap.set(e,{lastReportCalculated:!1})}resumeConsumer(e){this.pausedConsumerMap.delete(e)}async generateProducerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getProducerStatsFromReport(this.parseRTCReport(i,["outbound-rtp","remote-inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"outbound-rtp":{this.outboundProducerMap.set(o.id,e.id);break}}return n}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=r?this.getConsumerStatsFromReport(this.parseRTCReport(i,["inbound-rtp"],!1,e.id))[0]:void 0;for(const o of i.values())switch(o.type){case"inbound-rtp":{this.inboundConsumerMap.set(o.id,e.id);break}}return n}deregisterProducer(e){this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),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(i=>{const n=i.framesEncoded>0,o=i.packetsSent>0,c=i.frameWidth&&i.frameHeight;return n&&o&&!!c})||e[e.length-1]}parseRTCReport(e,r=[],i=!1,n=void 0,o=void 0){var w,_,C,D,V,$,H,F,Z,be,Ge,Ps,gn;const c=e,d=new tm,l=r.length?new Set(r):void 0,u=[],h=[],m=[],S=new Map,y=new Map;for(const A of c.values()){if(l){if(l.size===0)break;if(l.has(A.type))i&&l.delete(A.type);else continue}switch(A.type){case"local-candidate":{u.push(this.getIceCandidateStats(A));break}case"remote-candidate":{h.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:T}=A,{selected:P}=A,B=A,Pe={nominated:T!=null?T:P,currentRoundTripTime:B.currentRoundTripTime,totalRoundTripTime:B.totalRoundTripTime,bytesReceived:B.bytesReceived,bytesSent:B.bytesSent,availableOutgoingBitrate:B.availableOutgoingBitrate,availableIncomingBitrate:B.availableIncomingBitrate,lastPacketReceivedTimestamp:B.lastPacketReceivedTimestamp,lastPacketSentTimestamp:B.lastPacketSentTimestamp,localCandidateId:B.localCandidateId,remoteCandidateId:B.remoteCandidateId,bytesDiscardedOnSend:B.bytesDiscardedOnSend,packetsSent:B.packetsSent,packetsReceived:B.packetsReceived,packetsDiscardedOnSend:B.packetsDiscardedOnSend};m.push(Pe),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=Pe);break}case"transport":{const T=A;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=P,o){if(o.producing){const B=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,B,P)}if(o.consuming){const B=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,B,P)}}break}case"remote-inbound-rtp":{const T=A,P={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const T=A,P=n||this.outboundProducerMap.get(A.id),B=this.pausedProducerMap.get(P);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Pe=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(P);if(((w=Le==null?void 0:Le.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const x={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const I=T,Fe={frameHeight:I.frameHeight,frameWidth:I.frameWidth,framesEncoded:I.framesEncoded,framesDropped:I.framesDropped,framesPerSecond:I.framesPerSecond,framesSent:I.framesSent,keyFramesEncoded:I.keyFramesEncoded,firCount:I.firCount,encoderImplementation:I.encoderImplementation,hugeFramesSent:I.hugeFramesSent,pliCount:I.pliCount,qpSum:I.qpSum,qualityLimitationDurations:I.qualityLimitationDurations,qualityLimitationReason:I.qualityLimitationReason,qualityLimitationResolutionChanges:I.qualityLimitationResolutionChanges,totalEncodeTime:I.targetBitrate,totalPacketSendDelay:I.totalPacketSendDelay,retransmittedBytesSent:I.retransmittedBytesSent,retransmittedPacketsSent:I.retransmittedPacketsSent,scalabilityMode:I.scalabilityMode,powerEfficientEncoder:I.powerEfficientEncoder,...x};d.outboundVideoRtp.set(A.id,Fe),d.producerStreamMap.get(P).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(P,Pe,Fe)}else if(T.mediaType==="audio"||T.kind==="audio"){const I=T,Fe={retransmittedBytesSent:I.retransmittedBytesSent,retransmittedPacketsSent:I.retransmittedPacketsSent,...x};d.outboundAudioRtp.set(A.id,Fe),d.producerStreamMap.get(P).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(P,Pe,Fe)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const T=A,P=n||this.inboundConsumerMap.get(A.id),B=this.pausedConsumerMap.get(P);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Pe=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const x=T,I={frameHeight:x.frameHeight,frameWidth:x.frameWidth,framesDecoded:x.framesDecoded,framesDropped:x.framesDropped,framesPerSecond:x.framesPerSecond,framesReceived:x.framesReceived,keyFramesDecoded:x.keyFramesDecoded,firCount:x.firCount,decoderImplementation:x.decoderImplementation,pliCount:x.pliCount,totalProcessingDelay:x.totalProcessingDelay,qpSum:x.qpSum||0,totalAssemblyTime:x.totalAssemblyTime||0,totalDecodeTime:x.totalDecodeTime||0,totalFreezesDuration:x.totalFreezesDuration||0,totalInterFrameDelay:x.totalInterFrameDelay||0,totalPausesDuration:x.totalPausesDuration||0,totalSquaredInterFrameDelay:x.totalSquaredInterFrameDelay||0,freezeCount:x.freezeCount||0,pauseCount:x.pauseCount||0,powerEfficientDecoder:x.powerEfficientDecoder,...Le};I.score=Yp({frameWidth:I.frameWidth||0,framesDecoded:(I.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:I.framesPerSecond||0,packetsLost:(I.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(P))==null?void 0:C.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsReceived)||0),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),y.set(P,{score:+(I.score*10).toFixed(),frameWidth:I.frameWidth||0,frameHeight:I.frameHeight||0,framesPerSecond:I.framesPerSecond||0,packetsLostPercentage:sd({packetsLost:(I.packetsLost||0)-(((V=this.videoConsumerToStatsMap.get(P))==null?void 0:V.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.packetsReceived)||0)}),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((I.bytesReceived||0)-(((H=this.videoConsumerToStatsMap.get(P))==null?void 0:H.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,I),d.inboundVideoRtp.set(A.id,I),d.consumerStreamMap.get(P).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(P,Pe,I)}else if(T.mediaType==="audio"||T.kind==="audio"){const x=T,I={audioLevel:x.audioLevel,concealedSamples:x.concealedSamples,concealmentEvents:x.concealmentEvents,totalAudioEnergy:x.totalAudioEnergy,totalSamplesDuration:x.totalSamplesDuration,totalSamplesReceived:x.totalSamplesReceived,fecPacketsDiscarded:x.fecPacketsDiscarded||0,fecPacketsReceived:x.fecPacketsReceived||0,insertedSamplesForDeceleration:x.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:x.removedSamplesForAcceleration||0,silentConcealedSamples:x.silentConcealedSamples||0,playoutId:x.playoutId,...Le};I.score=zp({concealmentEvents:(I.concealmentEvents||0)-(((F=this.audioConsumerToStatsMap.get(P))==null?void 0:F.concealmentEvents)||0),packetsLost:(I.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(P))==null?void 0:Z.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((be=this.audioConsumerToStatsMap.get(P))==null?void 0:be.packetsReceived)||0),jitter:I.jitter||0}),y.set(P,{score:+(I.score*10).toFixed(),packetsLostPercentage:sd({packetsLost:(I.packetsLost||0)-(((Ge=this.audioConsumerToStatsMap.get(P))==null?void 0:Ge.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((Ps=this.audioConsumerToStatsMap.get(P))==null?void 0:Ps.packetsReceived)||0)}),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((I.bytesReceived||0)-(((gn=this.audioConsumerToStatsMap.get(P))==null?void 0:gn.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,I),d.inboundAudioRtp.set(A.id,I),d.consumerStreamMap.get(P).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(P,Pe,I)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((A,T)=>{var P,B,Pe,Le,x,I,Fe,Ac,Mc,Oc,Dc,Nc,Vc,Lc,xc,Uc,$c,Bc,Fc,Hc,qc,jc,Gc;if(A.outboundVideoRtpId.length>0){const me=[];A.outboundVideoRtpId.forEach(Yh=>{me.push(d.outboundVideoRtp.get(Yh))});const te=this.getWorkingSimulcastVideoStats(me);te.score=Jp({frameWidth:te.frameWidth||0,framesPerSecond:te.framesPerSecond||0,jitter:((P=te.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(te.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(T))==null?void 0:B.packetsSent)||0),packetsLost:(((Pe=te.remoteData)==null?void 0:Pe.packetsLost)||0)-(((x=(Le=this.videoProducerToStatsMap.get(T))==null?void 0:Le.remoteData)==null?void 0:x.packetsLost)||0),framesEncoded:(te.framesEncoded||0)-(((I=this.videoProducerToStatsMap.get(T))==null?void 0:I.framesEncoded)||0)}),S.set(T,{score:+(te.score*10).toFixed(),frameWidth:te.frameWidth||0,frameHeight:te.frameHeight||0,framesPerSecond:te.framesPerSecond||0,jitter:((Fe=te.remoteData)==null?void 0:Fe.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:td({packetsSent:(te.packetsSent||0)-(((Ac=this.videoProducerToStatsMap.get(T))==null?void 0:Ac.packetsSent)||0),packetsLost:(((Mc=te.remoteData)==null?void 0:Mc.packetsLost)||0)-(((Dc=(Oc=this.videoProducerToStatsMap.get(T))==null?void 0:Oc.remoteData)==null?void 0:Dc.packetsLost)||0)}),bitrate:((te.bytesSent||0)-(((Nc=this.videoProducerToStatsMap.get(T))==null?void 0:Nc.bytesSent)||0))*8/7,cpuLimitations:te.qualityLimitationReason==="cpu",bandwidthLimitations:te.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,te)}else if(A.outboundAudioRtpId.length>0){const me=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);me.score=Wp({packetsSent:(me.packetsSent||0)-(((Vc=this.audioProducerToStatsMap.get(T))==null?void 0:Vc.packetsSent)||0),packetsLost:(((Lc=me.remoteData)==null?void 0:Lc.packetsLost)||0)-(((Uc=(xc=this.audioProducerToStatsMap.get(T))==null?void 0:xc.remoteData)==null?void 0:Uc.packetsLost)||0),jitter:(($c=me.remoteData)==null?void 0:$c.jitter)||0}),S.set(T,{score:+(me.score*10).toFixed(),bitrate:((me.bytesSent||0)-(((Bc=this.audioProducerToStatsMap.get(T))==null?void 0:Bc.bytesSent)||0))*8/7,packetsLostPercentage:td({packetsSent:(me.packetsSent||0)-(((Fc=this.audioProducerToStatsMap.get(T))==null?void 0:Fc.packetsSent)||0),packetsLost:(((Hc=me.remoteData)==null?void 0:Hc.packetsLost)||0)-(((jc=(qc=this.audioProducerToStatsMap.get(T))==null?void 0:qc.remoteData)==null?void 0:jc.packetsLost)||0)}),jitter:((Gc=me.remoteData)==null?void 0:Gc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,me)}}),m.forEach(A=>{const T=u.find(B=>B.id===A.localCandidateId?(A.localCandidateId=B.id,B):null),P=h.find(B=>B.id===A.remoteCandidateId?(A.remoteCandidateId=B.id,B):null);T&&(A.localCandidateType=T.type,A.localCandidateAddress=kr(T.address),A.localCandidatePort=T.port,A.localCandidateProtocol=T.protocol,A.localCandidateUrl=T.url,A.localCandidateNetworkType=T.networkType,A.localCandidateRelatedAddress=kr(T.relatedAddress),A.localCandidateRelatedPort=T.relatedPort),P&&(A.remoteCandidateType=P.type,A.remoteCandidateAddress=kr(P.address),A.remoteCandidatePort=P.port,A.remoteCandidateProtocol=P.protocol,A.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=m),d.transport&&!d.transport.roundTripTime){let A=0,T=0;d.remoteInboundRtp.forEach((P,B)=>{P.roundTripTime&&P.roundTripTime>A&&(A=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(A){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(A){}return d}async getProducersReport(e){const r=e.map(i=>this.generateProducerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getConsumersReport(e){const r=e.map(i=>this.generateConsumerStreamMap(i,!0));return r.length>0?Promise.all(r):void 0}async getTransportReport(e){return e.getStats()}async getProcessedStats(e,r,i){const n=await this.getTransportReport(e),o={producing:i,consuming:r,id:e.id},c=n,d=this.parseRTCReport(c,["transport","candidate-pair","inbound-rtp","outbound-rtp","remote-inbound-rtp","local-candidate","remote-candidate"],!1,void 0,o);if(!d)return;const l={stats:d.transport,transportId:e.id,consuming:r,producing:i},u=d.staleProducerStreamMap?void 0:this.getProducerStatsFromReport(d),h=d.staleConsumerStreamMap?void 0:this.getConsumerStatsFromReport(d);return{transportReport:l,producerReport:u,consumerReport:h}}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{var o,c;r.push({producerId:n,videoStats:i.outboundVideoRtpId.map(d=>e.outboundVideoRtp.get(d)),audioStats:i.outboundAudioRtpId.map(d=>e.outboundAudioRtp.get(d)),appData:((c=(o=this.callStatsInstance.producers)==null?void 0:o.get(n))==null?void 0:c.appData)||null})})}catch(i){this.callStatsInstance.logger.error("callStats::measurements::getProducerStatsFromReport",{error:{reason:i.reason,message:i.message}})}return r}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(n);r.push({consumerId:n,peerId:o,producerId:c,appData:d,videoStats:i.inboundVideoRtpId.map(l=>e.inboundVideoRtp.get(l)),audioStats:i.inboundAudioRtpId.map(l=>e.inboundAudioRtp.get(l))})})}catch(i){console.error("getConsumersReport: ",i,e)}return r}async getUserLocation(){return new Promise((e,r)=>{try{navigator.geolocation?navigator.geolocation.getCurrentPosition(i=>{e(i)}):r()}catch(i){r(i)}})}async getConnectivity(e){try{const r={iceServers:e||Zp},i=new Promise((u,h)=>{try{const m=new TT(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){h(m)}}),n=new Promise((u,h)=>{try{const m=new yT(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){h(m)}}),o=new Promise((u,h)=>{try{const m=new ET(r);m.addListener("done",u),m.addListener("failed",()=>{u({connectivity:!1})}),m.start(2e3)}catch(m){h(m)}}),[c,d,l]=await Promise.all([i,n,o]);return{host:c==null?void 0:c.connectivity,relay:d==null?void 0:d.connectivity,reflexive:l==null?void 0:l.connectivity}}catch(r){return{host:!1,relay:!1,reflexive:!1}}}async getThroughput(e){try{const i=await new Promise((n,o)=>{try{const c={iceServers:e||Zp},d=new vT(c);d.addListener("done",n),d.addListener("failed",o),d.start(1e4)}catch(c){o(c)}});return{throughput:i.throughput,fractionalLoss:0,RTT:i.RTT,jitter:0,backendRTT:i.backendRTT}}catch(r){return}}async getIPDetails(){var e,r;try{return this.ipDetails||(this.ipDetails=await Xp.getIPDetails({peerId:(e=this.callStatsInstance)==null?void 0:e.peerId,apiHostnames:(r=this.callStatsInstance)==null?void 0:r.apiHostnames,logger:this.callStatsInstance.logger})),this.ipDetails}catch(i){return}}async getNetworkQuality(e){const[r,i]=await Promise.all([this.getConnectivity(e),this.getThroughput(e)]);return{connectivity:r,throughput:i==null?void 0:i.throughput,fractionalLoss:i==null?void 0:i.fractionalLoss,RTT:i==null?void 0:i.RTT,jitter:i==null?void 0:i.jitter,backendRTT:i==null?void 0:i.backendRTT}}async getNetworkInfo(e,r=!1){var c,d;if(r){const l=await this.getIPDetails();return{ipDetails:l,effectiveNetworkType:(c=navigator.connection)==null?void 0:c.effectiveType,location:l!=null&&l.loc?em(l==null?void 0:l.loc):void 0}}const[i,n,o]=await Promise.all([this.getConnectivity(e),this.getThroughput(e),this.getIPDetails()]);return{ipDetails:o,effectiveNetworkType:(d=navigator.connection)==null?void 0:d.effectiveType,location:o!=null&&o.loc?em(o==null?void 0:o.loc):void 0,turnConnectivity:i?i.host||i.relay||i.reflexive:!1,connectivity:i,throughput:n==null?void 0:n.throughput,fractionalLoss:n==null?void 0:n.fractionalLoss,RTT:n==null?void 0:n.RTT,jitter:n==null?void 0:n.jitter,backendRTT:n==null?void 0:n.backendRTT}}}class wT extends sm{}class rm extends sm{constructor(){super(...arguments);p(this,"producerMap",new Map);p(this,"consumerMap",new Map)}async registerProducer(e){this.producerMap.set(e.id,e),await this.generateProducerStreamMap(e),e.on("close",this.deregisterProducer.bind(this,e)),e.on("pause",this.pauseProducer.bind(this,e.id)),e.on("resume",this.resumeProducer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareProducers.add(e.id)}async registerConsumer(e){this.consumerMap.set(e.id,e),await this.generateConsumerStreamMap(e),this.consumerPeerIdMap.set(e.id,{producerId:e.producerId,peerId:e.appData.peerId,appData:e.appData}),e.on("close",this.deregisterConsumer.bind(this,e)),e.on("pause",this.pauseConsumer.bind(this,e.id)),e.on("resume",this.resumeConsumer.bind(this,e.id)),e.appData.screenShare===!0&&this.screenShareConsumers.add(e.id)}async generateConsumerStreamMap(e,r=!1){const i=await e.getStats(),n=this.parseRTCReport(i,["inbound-rtp"],!1,e.id),o=[...n.consumerStreamMap.values()][0],c=r?this.getConsumerStatsFromParsedConsumerStats(n,o,e.id):void 0;for(const d of i.values())switch(d.type){case"inbound-rtp":{this.inboundConsumerMap.set(d.id,e.id);break}}return c}deregisterProducer(e){this.producerMap.delete(e.id),this.outboundProducerMap.forEach((r,i)=>{r===e.id&&this.outboundProducerMap.delete(i)}),this.pausedProducerMap.delete(e.id),this.screenShareProducers.delete(e.id)}deregisterConsumer(e){this.consumerMap.delete(e.id),this.inboundConsumerMap.forEach((r,i)=>{r===e.id&&this.inboundConsumerMap.delete(i)}),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=[],i=!1,n=void 0,o=void 0){var w,_,C,D,V,$,H,F,Z,be,Ge,Ps,gn;const c=e,d=new tm,l=r.length?new Set(r):void 0,u=[],h=[],m=[],S=new Map,y=new Map;for(const A of c.values()){if(l){if(l.size===0)break;if(l.has(A.type))i&&l.delete(A.type);else continue}switch(A.type){case"local-candidate":{u.push(this.getIceCandidateStats(A));break}case"remote-candidate":{h.push(this.getIceCandidateStats(A));break}case"candidate-pair":{const{nominated:T}=A,{selected:P}=A,B=A,Pe={nominated:T!=null?T:P,currentRoundTripTime:B.currentRoundTripTime,totalRoundTripTime:B.totalRoundTripTime,bytesReceived:B.bytesReceived,bytesSent:B.bytesSent,availableOutgoingBitrate:B.availableOutgoingBitrate,availableIncomingBitrate:B.availableIncomingBitrate,lastPacketReceivedTimestamp:B.lastPacketReceivedTimestamp,lastPacketSentTimestamp:B.lastPacketSentTimestamp,localCandidateId:B.localCandidateId,remoteCandidateId:B.remoteCandidateId,bytesDiscardedOnSend:B.bytesDiscardedOnSend,packetsSent:B.packetsSent,packetsReceived:B.packetsReceived,packetsDiscardedOnSend:B.packetsDiscardedOnSend};m.push(Pe),(A.nominated===!0||A.selected===!0)&&(d.candidatePair=Pe);break}case"transport":{const T=A;o&&(o.producing&&(this.overallProducingTransportsStatsMap[o.id]||(this.overallProducingTransportsStatsMap[o.id]={totalPacketsSent:0})),o.consuming&&(this.overallConsumingTransportsStatsMap[o.id]||(this.overallConsumingTransportsStatsMap[o.id]={totalPacketsReceived:0})));const P={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=P,o){if(o.producing){const B=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,B,P)}if(o.consuming){const B=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,B,P)}}break}case"remote-inbound-rtp":{const T=A,P={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,P);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(A.id))break;const T=A,P=n||this.outboundProducerMap.get(A.id),B=this.pausedProducerMap.get(P);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(P,{lastReportCalculated:!0})}this.overallProducersStatsMap[P]||(this.overallProducersStatsMap[P]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Pe=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(A.id)){d.staleProducerStreamMap=!0;break}const Le=this.callStatsInstance.producers.get(P);if(((w=Le==null?void 0:Le.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const x={bytesSent:T.bytesSent,packetsSent:T.packetsSent,nackCount:T.nackCount,ssrc:T.ssrc,mid:T.mid,active:T.active,codecId:T.codecId,headerBytesSent:T.headerBytesSent||0,totalPacketSendDelay:T.totalPacketSendDelay||0};if(T.mediaType==="video"||T.kind==="video"){const I=T,Fe={frameHeight:I.frameHeight,frameWidth:I.frameWidth,framesEncoded:I.framesEncoded,framesDropped:I.framesDropped?I.framesDropped:I.droppedFrames,framesPerSecond:I.framesPerSecond?I.framesPerSecond:I.framerateMean,framesSent:I.framesSent,keyFramesEncoded:I.keyFramesEncoded,firCount:I.firCount,encoderImplementation:I.encoderImplementation,hugeFramesSent:I.hugeFramesSent,pliCount:I.pliCount,qpSum:I.qpSum,qualityLimitationReason:I.qualityLimitationReason,qualityLimitationDurations:I.qualityLimitationDurations,qualityLimitationResolutionChanges:I.qualityLimitationResolutionChanges,totalEncodeTime:I.totalEncodeTime,totalPacketSendDelay:I.totalEncodeTime,retransmittedBytesSent:I.retransmittedBytesSent,retransmittedPacketsSent:I.retransmittedPacketsSent,scalabilityMode:I.scalabilityMode,powerEfficientEncoder:I.powerEfficientEncoder,...x};d.outboundVideoRtp.set(A.id,Fe),d.producerStreamMap.get(P).outboundVideoRtpId.push(A.id),this.processOutboundProducerVideoStats(P,Pe,Fe)}else if(T.mediaType==="audio"||T.kind==="audio"){const I=T,Fe={retransmittedBytesSent:I.retransmittedBytesSent,retransmittedPacketsSent:I.retransmittedPacketsSent,...x};d.outboundAudioRtp.set(A.id,Fe),d.producerStreamMap.get(P).outboundAudioRtpId.push(A.id),this.processOutboundProducerAudioStats(P,Pe,Fe)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(A.id))break;const T=A,P=n||this.inboundConsumerMap.get(A.id),B=this.pausedConsumerMap.get(P);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(P,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[P]||(this.overallConsumersStatsMap[P]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Pe=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(A.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Le={bytesReceived:T.bytesReceived,packetsReceived:T.packetsReceived,packetsLost:T.packetsLost>=0?T.packetsLost:0,jitter:T.jitter,nackCount:T.nackCount,jitterBufferDelay:T.jitterBufferDelay,jitterBufferEmittedCount:T.jitterBufferEmittedCount,lastPacketReceivedTimestamp:T.lastPacketReceivedTimestamp,ssrc:T.ssrc,mid:T.mid,codecId:T.codecId,headerBytesReceived:T.headerBytesReceived||0,packetsDiscarded:T.packetsDiscarded||0,jitterBufferMinimumDelay:T.jitterBufferMinimumDelay||0,jitterBufferTargetDelay:T.jitterBufferTargetDelay||0};if(T.mediaType==="video"||T.kind==="video"){const x=T,I={frameHeight:x.frameHeight,frameWidth:x.frameWidth,framesDecoded:x.framesDecoded,framesDropped:x.framesDropped?x.framesDropped:x.droppedFrames,framesPerSecond:x.framesPerSecond?x.framesPerSecond:x.framerateMean,framesReceived:x.framesReceived,keyFramesDecoded:x.keyFramesDecoded,firCount:x.firCount,decoderImplementation:x.decoderImplementation,pliCount:x.pliCount,totalProcessingDelay:x.totalProcessingDelay,qpSum:x.qpSum||0,totalAssemblyTime:x.totalAssemblyTime||0,totalDecodeTime:x.totalDecodeTime||0,totalFreezesDuration:x.totalFreezesDuration||0,totalInterFrameDelay:x.totalInterFrameDelay||0,totalPausesDuration:x.totalPausesDuration||0,totalSquaredInterFrameDelay:x.totalSquaredInterFrameDelay||0,freezeCount:x.freezeCount||0,pauseCount:x.pauseCount||0,powerEfficientDecoder:x.powerEfficientDecoder,...Le};I.score=Yp({frameWidth:I.frameWidth||0,framesDecoded:(I.framesDecoded||0)-(((_=this.videoConsumerToStatsMap.get(P))==null?void 0:_.framesDecoded)||0),framesPerSecond:I.framesPerSecond||0,packetsLost:(I.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(P))==null?void 0:C.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((D=this.videoConsumerToStatsMap.get(P))==null?void 0:D.packetsReceived)||0),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),y.set(P,{score:+(I.score*10).toFixed(),frameWidth:I.frameWidth||0,frameHeight:I.frameHeight||0,framesPerSecond:I.framesPerSecond||0,packetsLostPercentage:sd({packetsLost:(I.packetsLost||0)-(((V=this.videoConsumerToStatsMap.get(P))==null?void 0:V.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-((($=this.videoConsumerToStatsMap.get(P))==null?void 0:$.packetsReceived)||0)}),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((I.bytesReceived||0)-(((H=this.videoConsumerToStatsMap.get(P))==null?void 0:H.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,I),d.inboundVideoRtp.set(A.id,I),d.consumerStreamMap.get(P).inboundVideoRtpId.push(A.id),this.processInboundConsumerVideoStats(P,Pe,I)}else if(T.mediaType==="audio"||T.kind==="audio"){const x=T,I={audioLevel:x.audioLevel,concealedSamples:x.concealedSamples,concealmentEvents:x.concealmentEvents,totalAudioEnergy:x.totalAudioEnergy,totalSamplesDuration:x.totalSamplesDuration,totalSamplesReceived:x.totalSamplesReceived,fecPacketsDiscarded:x.fecPacketsDiscarded||0,fecPacketsReceived:x.fecPacketsReceived||0,insertedSamplesForDeceleration:x.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:x.removedSamplesForAcceleration||0,silentConcealedSamples:x.silentConcealedSamples||0,playoutId:x.playoutId,...Le};I.score=zp({concealmentEvents:(I.concealmentEvents||0)-(((F=this.audioConsumerToStatsMap.get(P))==null?void 0:F.concealmentEvents)||0),packetsLost:(I.packetsLost||0)-(((Z=this.audioConsumerToStatsMap.get(P))==null?void 0:Z.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((be=this.audioConsumerToStatsMap.get(P))==null?void 0:be.packetsReceived)||0),jitter:I.jitter||0}),y.set(P,{score:+(I.score*10).toFixed(),packetsLostPercentage:sd({packetsLost:(I.packetsLost||0)-(((Ge=this.audioConsumerToStatsMap.get(P))==null?void 0:Ge.packetsLost)||0),packetsReceived:(I.packetsReceived||0)-(((Ps=this.audioConsumerToStatsMap.get(P))==null?void 0:Ps.packetsReceived)||0)}),jitter:I.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((I.bytesReceived||0)-(((gn=this.audioConsumerToStatsMap.get(P))==null?void 0:gn.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,I),d.inboundAudioRtp.set(A.id,I),d.consumerStreamMap.get(P).inboundAudioRtpId.push(A.id),this.processInboundConsumerAudioStats(P,Pe,I)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((A,T)=>{var P,B,Pe,Le,x,I,Fe,Ac,Mc,Oc,Dc,Nc,Vc,Lc,xc,Uc,$c,Bc,Fc,Hc,qc,jc,Gc;if(A.outboundVideoRtpId.length>0){const me=[];A.outboundVideoRtpId.forEach(Yh=>{me.push(d.outboundVideoRtp.get(Yh))});const te=this.getWorkingSimulcastVideoStats(me);te.score=Jp({frameWidth:te.frameWidth||0,framesPerSecond:te.framesPerSecond||0,jitter:((P=te.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(te.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(T))==null?void 0:B.packetsSent)||0),packetsLost:(((Pe=te.remoteData)==null?void 0:Pe.packetsLost)||0)-(((x=(Le=this.videoProducerToStatsMap.get(T))==null?void 0:Le.remoteData)==null?void 0:x.packetsLost)||0),framesEncoded:(te.framesEncoded||0)-(((I=this.videoProducerToStatsMap.get(T))==null?void 0:I.framesEncoded)||0)}),S.set(T,{score:+(te.score*10).toFixed(),frameWidth:te.frameWidth||0,frameHeight:te.frameHeight||0,framesPerSecond:te.framesPerSecond||0,jitter:((Fe=te.remoteData)==null?void 0:Fe.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:td({packetsSent:(te.packetsSent||0)-(((Ac=this.videoProducerToStatsMap.get(T))==null?void 0:Ac.packetsSent)||0),packetsLost:(((Mc=te.remoteData)==null?void 0:Mc.packetsLost)||0)-(((Dc=(Oc=this.videoProducerToStatsMap.get(T))==null?void 0:Oc.remoteData)==null?void 0:Dc.packetsLost)||0)}),bitrate:((te.bytesSent||0)-(((Nc=this.videoProducerToStatsMap.get(T))==null?void 0:Nc.bytesSent)||0))*8/7,cpuLimitations:te.qualityLimitationReason==="cpu",bandwidthLimitations:te.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,te)}else if(A.outboundAudioRtpId.length>0){const me=d.outboundAudioRtp.get(A.outboundAudioRtpId[0]);me.score=Wp({packetsSent:(me.packetsSent||0)-(((Vc=this.audioProducerToStatsMap.get(T))==null?void 0:Vc.packetsSent)||0),packetsLost:(((Lc=me.remoteData)==null?void 0:Lc.packetsLost)||0)-(((Uc=(xc=this.audioProducerToStatsMap.get(T))==null?void 0:xc.remoteData)==null?void 0:Uc.packetsLost)||0),jitter:(($c=me.remoteData)==null?void 0:$c.jitter)||0}),S.set(T,{score:+(me.score*10).toFixed(),bitrate:((me.bytesSent||0)-(((Bc=this.audioProducerToStatsMap.get(T))==null?void 0:Bc.bytesSent)||0))*8/7,packetsLostPercentage:td({packetsSent:(me.packetsSent||0)-(((Fc=this.audioProducerToStatsMap.get(T))==null?void 0:Fc.packetsSent)||0),packetsLost:(((Hc=me.remoteData)==null?void 0:Hc.packetsLost)||0)-(((jc=(qc=this.audioProducerToStatsMap.get(T))==null?void 0:qc.remoteData)==null?void 0:jc.packetsLost)||0)}),jitter:((Gc=me.remoteData)==null?void 0:Gc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,me)}}),m.forEach(A=>{const T=u.find(B=>B.id===A.localCandidateId?(A.localCandidateId=B.id,B):null),P=h.find(B=>B.id===A.remoteCandidateId?(A.remoteCandidateId=B.id,B):null);T&&(A.localCandidateType=T.type,A.localCandidateAddress=kr(T.address),A.localCandidatePort=T.port,A.localCandidateProtocol=T.protocol,A.localCandidateUrl=T.url,A.localCandidateNetworkType=T.networkType,A.localCandidateRelatedAddress=kr(T.relatedAddress),A.localCandidateRelatedPort=T.relatedPort),P&&(A.remoteCandidateType=P.type,A.remoteCandidateAddress=kr(P.address),A.remoteCandidatePort=P.port,A.remoteCandidateProtocol=P.protocol,A.remoteCandidateUrl=P.url)}),d.candidatePair&&(d.transport?(d.transport.bytesReceived=d.candidatePair.bytesReceived,d.transport.bytesSent=d.candidatePair.bytesSent,d.transport.totalRoundTripTime=d.candidatePair.totalRoundTripTime,d.transport.availableOutgoingBitrate=d.candidatePair.availableOutgoingBitrate,d.transport.availableIncomingBitrate=d.candidatePair.availableIncomingBitrate,d.transport.roundTripTime=d.candidatePair.currentRoundTripTime):d.transport={bytesReceived:d.candidatePair.bytesReceived,bytesSent:d.candidatePair.bytesSent,totalRoundTripTime:d.candidatePair.totalRoundTripTime,availableOutgoingBitrate:d.candidatePair.availableOutgoingBitrate,availableIncomingBitrate:d.candidatePair.availableIncomingBitrate,roundTripTime:d.candidatePair.currentRoundTripTime}),d.transport&&(d.transport.candidatePairs=m),d.transport&&!d.transport.roundTripTime){let A=0,T=0;d.remoteInboundRtp.forEach((P,B)=>{P.roundTripTime&&P.roundTripTime>A&&(A=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=A,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(A){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(A){}return d}getProducerStatsFromReport(e){const r=[];try{e.producerStreamMap.forEach((i,n)=>{const o=this.producerMap.get(n),c=o.track.getSettings(),d=i.outboundVideoRtpId.map(u=>{const h=e.outboundVideoRtp.get(u);return h.frameHeight||(h.frameHeight=c.height,h.frameWidth=c.width,h.framesPerSecond=c.frameRate),h}),l={producerId:n,appData:o.appData,videoStats:d,audioStats:i.outboundAudioRtpId.map(u=>e.outboundAudioRtp.get(u))};r.push(l)})}catch(i){console.error("getProducersReport: ",i,e)}return r}getConsumerStatsFromParsedConsumerStats(e,r,i){let n;try{const{peerId:o,producerId:c,appData:d}=this.consumerPeerIdMap.get(i),l=r==null?void 0:r.inboundVideoRtpId.map(u=>{const m=this.consumerMap.get(i).track.getSettings(),S=e.inboundVideoRtp.get(u);return S.frameHeight||(S.frameHeight=m.height,S.frameWidth=m.width,S.framesPerSecond=m.frameRate),S});n={consumerId:i,peerId:o,producerId:c,appData:d,videoStats:l,audioStats:r==null?void 0:r.inboundAudioRtpId.map(u=>e.inboundAudioRtp.get(u))}}catch(o){console.error("getConsumerStatsFromParsedConsumerStats: ",o,e)}return n}getConsumerStatsFromReport(e){const r=[];try{e.consumerStreamMap.forEach((i,n)=>{r.push(this.getConsumerStatsFromParsedConsumerStats(e,i,n))})}catch(i){console.error("getConsumerStatsFromReport: ",i,e)}return r}}class PT extends rm{}function ad(s,t,e,r){if(s!=null&&s.logger&&s.logger.error("Callstats::handleError",{error:r}),typeof e=="function"&&r instanceof t)e.call(null,r,s);else throw r}function im(s,t,e){const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{ad(this,t,e,o)}):n}catch(n){ad(this,t,e,n)}return null},s}const z=(s,t)=>(e,r,i)=>{const n=i.value;return i.value=function(...o){try{const c=n.apply(this,o);return c&&c instanceof Promise?c.catch(d=>{ad(this,s,t,d)}):c}catch(c){ad(this,s,t,c)}return null},i},_T=(s,t)=>(e,r,i)=>{if(i)return im(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);o.value instanceof Function&&Object.defineProperty(e.prototype,n,im(o,s,t))}};var J=globalThis&&globalThis.__decorate||function(s,t,e,r){var i=arguments.length,n=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,e):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(s,t,e,r);else for(var c=s.length-1;c>=0;c--)(o=s[c])&&(n=(i<3?o(n):i>3?o(t,e,n):o(t,e))||n);return i>3&&n&&Object.defineProperty(t,e,n),n};const K=console;let j=class extends dt{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Up.PROD,n,o,c,d,l){super();p(this,"observer");p(this,"eventHandler");p(this,"measurements");p(this,"producingTransport");p(this,"consumingTransport");p(this,"producers",new Map);p(this,"consumers",new Map);p(this,"iceServers");p(this,"connectionInfoPromise");p(this,"pingStatsTimeout");p(this,"logger");p(this,"env");p(this,"apiHostnames");p(this,"peerId");p(this,"consumerSharedMediaStatesMap",new Map);p(this,"currentUserMediaStates",{});if(!l)throw Error("authToken is missing but required to initialize CallStats!");switch(this.env=i,this.apiHostnames=d,this.logger=o,this.peerId=c,this.eventHandler=new dT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new wT;break;case"Gecko":this.measurements=new rm;break;case"WebKit":this.measurements=new PT;break;default:throw Error(`Unknown engineName! ${r}`)}this.measurements.callStatsInstance=this,this.registerProducer=this.registerProducer.bind(this),this.registerConsumer=this.registerConsumer.bind(this),this.observer=new dt,this.measurements.observer.on("consumer_score",u=>{o.debug(`callStats::consumer_score ${[...u.entries()]}`),this.eventHandler.emit("consumer_score",u)}),this.measurements.observer.on("producer_score",u=>{o.debug(`callStats::producer_score ${[...u.entries()]}`),this.eventHandler.emit("producer_score",u)})}registerIceServers(e){this.iceServers=e}registerConsumer(e){var r;this.consumerSharedMediaStatesMap.has(e.id)||this.consumerSharedMediaStatesMap.set(e.id,{}),this.consumers.set(e.id,e),this.measurements.registerConsumer(e),this.logger.debug("callStats::registerConsumer",{consumerId:e.id,consumerkind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterConsumer.bind(this,e))}registerProducer(e){var r;this.producers.set(e.id,e),this.measurements.registerProducer(e),this.logger.debug("callStats::registerProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)}),e.on("close",this.deRegisterProducer.bind(this,e))}sendConsumerSharedMediaStateEvent(e,r){this.consumerSharedMediaStatesMap.has(e)||this.consumerSharedMediaStatesMap.set(e,{});const i=this.consumerSharedMediaStatesMap.get(e);this.consumerSharedMediaStatesMap.set(e,Object.assign(i,r))}registerProducingTransport(e){var i;this.producingTransport=e,e.on("close",this.disconnectProducingTransport.bind(this,e)),e.on("disconnect",this.disconnectProducingTransport.bind(this,e)),Array.from(((i=e._producers)==null?void 0:i.values())||[]).forEach(n=>{this.registerProducer(n)}),e.on("newproducer",this.registerProducer)}registerConsumingTransport(e){var i;this.consumingTransport=e,e.on("close",this.disconnectConsumingTransport.bind(this,e)),e.on("disconnect",this.disconnectConsumingTransport.bind(this,e)),Array.from(((i=e._consumers)==null?void 0:i.values())||[]).forEach(n=>{this.registerConsumer(n)}),e.on("newconsumer",this.registerConsumer)}deRegisterConsumer(e){this.consumers.delete(e.id)}deRegisterProducer(e){var r;this.producers.delete(e.id),this.logger.debug("callStats::deRegisterProducer",{producerId:e.id,producerKind:e.kind,isScreenShare:!!((r=e.appData)!=null&&r.screenShare)})}disconnectConsumingTransport(){this.consumingTransport=void 0}disconnectProducingTransport(){this.producingTransport=void 0}callEvent(e){this.eventHandler.callEvent(e)}sendPreCallTestBeginEvent(e=!1,r){this.connectionInfoPromise=this.measurements.getNetworkInfo(this.iceServers,e),this.eventHandler.callEvent({event:N.PRECALL_TEST_BEGIN,timestamp:r}),this.connectionInfoPromise&&this.connectionInfoPromise.then(i=>{this.eventHandler.callEvent({event:N.PRECALL_TEST_COMPLETE,metaData:{connectionInfo:i},timestamp:r})})}sendScreenShareToggleEvent(e,r=null,i){this.currentUserMediaStates.screen=e,this.eventHandler.callEvent({event:e?N.SCREENSHARE_STARTED:N.SCREENSHARE_STOPPED,metaData:{ssrc:r},timestamp:i})}sendScreenShareRequestedEvent(e){this.eventHandler.callEvent({event:N.SCREENSHARE_START_REQUESTED,timestamp:e})}sendActiveSpeakerEvent(e,r){this.eventHandler.callEvent({event:N.DOMINANT_SPEAKER,metaData:{peerId:e},timestamp:r})}devices(e,r,i){this.eventHandler.callEvent({event:e===Jt.AUDIO&&N.AUDIO_DEVICES_UPDATES||e===Jt.VIDEO&&N.VIDEO_DEVICES_UPDATES||e===Jt.SPEAKER&&N.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Jt.AUDIO&&N.SELECTED_MICROHPONE_UPDATE||e===Jt.VIDEO&&N.SELECTED_CAMERA_UPDATE||e===Jt.SPEAKER&&N.SELECTED_SPEAKER_UPDATE,metaData:{device:r},timestamp:i})}mediaPermission(e,r,i){this.eventHandler.callEvent({event:N.MEDIA_PERMISSION,metaData:{deviceType:e,permission:r},timestamp:i})}mediaPlaybackFailed(e,r){this.eventHandler.callEvent({event:e===Jt.AUDIO&&N.AUDIO_PLAY_FAILED||e===Jt.VIDEO&&N.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Jt.AUDIO&&N.AUDIO_TRACK_MUTED||e===Jt.VIDEO&&N.VIDEO_TRACK_MUTED,metaData:{deviceType:e},timestamp:r})}tabChanged(e,r){this.eventHandler.callEvent({event:N.TAB_CHANGE,metaData:{isMeetingsTabActive:e},timestamp:r})}browserBackgrounded(e){this.eventHandler.callEvent({event:N.BROWSER_BACKGROUNDED,timestamp:e})}browserForegrounded(e){this.eventHandler.callEvent({event:N.BROWSER_FOREGROUNDED,timestamp:e})}legacySwitch(e,r){this.eventHandler.callEvent({event:N.LEGACY_SWITCH,metadata:{on:e},timestamp:r})}async getPreCallTestResults(){return this.connectionInfoPromise}sendCallJoinBeginEvent(e,r){e={...e,meetingEnv:this.env},e.deviceInfo={...e.deviceInfo,userAgent:navigator.userAgent,cpus:navigator.hardwareConcurrency,memory:navigator.deviceMemory},this.eventHandler.callEvent({event:N.CALL_JOIN_BEGIN,metaData:{peerMetaData:e},timestamp:r})}sendNetworkQualityTestBeginEvent(e,r){this.eventHandler.callEvent({event:N.NET_QUALITY_TEST_BEGIN,timestamp:r}),new Promise(async(n,o)=>{const c=[];try{for(const d of e)try{if(d.iceServers&&d.iceServers.length>0){const l=await this.measurements.getNetworkQuality(d.iceServers);c.push({...d,networkResults:l})}}catch(l){console.warn("Error handling ",l)}n({regionData:c})}catch(d){console.warn("Error in callstats, ",d),o(d)}}).then(n=>{this.eventHandler.callEvent({event:N.NET_QUALITY_TEST_END,timestamp:r,metaData:n})})}sendWebSocketConnectedEvent(e){this.eventHandler.callEvent({event:N.WEBSOCKET_CONNECTED,timestamp:e})}sendTransportConnectedEvent(e){this.eventHandler.callEvent({event:N.TRANSPORT_CONNECTED,timestamp:e})}sendAudioToggleEvent(e,r){this.currentUserMediaStates.audio=e;let i;e?i=N.AUDIO_ON:i=N.AUDIO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendVideoToggleEvent(e,r){this.currentUserMediaStates.video=e;let i;e?i=N.VIDEO_ON:i=N.VIDEO_OFF,this.eventHandler.callEvent({event:i,timestamp:r})}sendParticipantRoleToggleEvent(e,r){this.eventHandler.callEvent({event:N.PARTICIPANT_ROLE,timestamp:r,metaData:e})}startPingStats(e=7e3){this.sendPingStatsEvent(!1,new Date),this.pingStatsTimeout=setInterval(this.sendPingStatsEvent.bind(this),e)}stopPingStats(){clearInterval(this.pingStatsTimeout)}async sendPingStatsEvent(e=!0,r){var c,d;let i,n;if(this.producingTransport&&(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),!i||!((c=i==null?void 0:i.producerReport)!=null&&c.length))){this.logger.debug("callStats::sendPingStatsEvent::staleProducingTransport",{disclaimer:"Stale producer? Regenerating Stream Maps!"});const l=await this.measurements.getProducersReport([...this.producers.values()]);i&&l?i.producerReport=l:(i=await this.measurements.getProcessedStats(this.producingTransport,!1,!0),(!i||!(i!=null&&i.producerReport))&&this.logger.debug("callStats::sendPingStatsEvent::noProducingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}if(this.consumingTransport&&(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),!n||!((d=n.consumerReport)!=null&&d.length))){this.logger.debug("callStats::sendPingStatsEvent::staleConsumingTransport",{disclaimer:"Stale consumer? Regenerating Stream Maps!"});const l=await this.measurements.getConsumersReport([...this.consumers.values()]);n&&l?n.consumerReport=l:(n=await this.measurements.getProcessedStats(this.consumingTransport,!0,!1),(!n||!n.consumerReport)&&this.logger.debug("callStats::sendPingStatsEvent::noConsumingTransportReport",{disclaimer:"Stream maps invalid despite regenerating!"}))}const o={producingTransportStats:i?i==null?void 0:i.transportReport:void 0,consumingTransportStats:n?n==null?void 0:n.transportReport:void 0,producerStats:[].concat((i==null?void 0:i.producerReport)||[]).concat((n==null?void 0:n.producerReport)||[]),consumerStats:[].concat((n==null?void 0:n.consumerReport)||[]).concat((i==null?void 0:i.consumerReport)||[])};if(e&&o.producerStats.length===0&&o.consumerStats.length===0){await this.eventHandler.flush();return}this.eventHandler.callEvent({event:N.PING_STAT,metaData:o,timestamp:r})}sendIVSPlayerRebufferEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_REBUFFERING,timestamp:e})}sendIVSPlayerAudioBlockEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_AUDIO_BLOCKED,timestamp:e})}sendIVSPlayerPlaybackBlockedEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_PLAYBACK_BLOCKED,timestamp:e})}sendIVSPlayerNetworkUnavailableEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_NETWORK_UNAVAILABLE,timestamp:e})}sendIVSPlayerInitializedEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_INITIALIZED,timestamp:e})}sendIVSPlayerWorkerErrorEvent(e){this.eventHandler.callEvent({event:N.IVS_PLAYER_WORKER_ERROR,timestamp:e})}sendIVSPlayerErrorEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_ERROR,timestamp:r,metaData:e})}sendIVSPlayerRecoverableErrorEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_RECOVERABLE_ERROR,timestamp:r,metaData:e})}sendIVSPlayerAnalyticsEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_ANALYTICS_EVENT,timestamp:r,metaData:e})}sendIVSPlayerPlaybackRateChangedEvent(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_PLAYBACK_RATE_CHANGED,timestamp:r,metaData:{updatedPlaybackRate:e}})}sendIVSPlayerQualityChanged(e,r){this.eventHandler.callEvent({event:N.IVS_PLAYER_QUALITY_CHANGED,timestamp:r,metaData:e})}sendPlayerLiveLatency(e,r){this.eventHandler.callEvent({event:N.LIVESTREAM_LATENCY,timestamp:r,metaData:{latency:e}})}sendDisconnectEvent(e){this.eventHandler.callEvent({event:N.DISCONNECT,timestamp:e})}sendReconnectEvent(e){this.eventHandler.callEvent({event:N.RECONNECT_ATTEMPT,timestamp:e})}expectedVideoResolution(e,r,i){this.eventHandler.callEvent({event:N.EXPECTED_VIDEO_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}expectedScreenshareResolution(e,r,i){this.eventHandler.callEvent({event:N.EXPECTED_SCREENSHARE_RESOLUTION,timestamp:i,metaData:{frameWidth:e,frameHeight:r}})}};J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerIceServers",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerConsumer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerProducer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendConsumerSharedMediaStateEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerProducingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"registerConsumingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"deRegisterConsumer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"deRegisterProducer",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"disconnectConsumingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"disconnectProducingTransport",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPreCallTestBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendScreenShareToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendScreenShareRequestedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendActiveSpeakerEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"devices",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"selectedDevice",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaPermission",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaPlaybackFailed",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"mediaTrackMuted",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"tabChanged",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"browserBackgrounded",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"browserForegrounded",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"legacySwitch",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"getPreCallTestResults",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendCallJoinBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendNetworkQualityTestBeginEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendWebSocketConnectedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendTransportConnectedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendAudioToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendVideoToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendParticipantRoleToggleEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"startPingStats",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"stopPingStats",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPingStatsEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerRebufferEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerAudioBlockEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerInitializedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerWorkerErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerRecoverableErrorEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerAnalyticsEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendIVSPlayerQualityChanged",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendPlayerLiveLatency",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendDisconnectEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"sendReconnectEvent",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"expectedVideoResolution",null),J([z(TypeError,(s,t)=>K.error(t,s))],j.prototype,"expectedScreenshareResolution",null),j=J([_T(TypeError,(s,t)=>K.error(t,s))],j);const kT=j;class nm extends dt{constructor(){super(...arguments);p(this,"stats");p(this,"peerId");p(this,"backend");p(this,"iceServers");p(this,"initialized",!1);p(this,"stalled",!1);p(this,"ipInformation");p(this,"logger")}async initialize({peerId:e,engineName:r,env:i=Up.PROD,iceServers:n,apiBase:o="https://api.cluster.dyte.in",flags:c,logger:d=console,apiHostnames:l,skipConnectivityChecks:u=!1,authToken:h}){var m,S,y;try{if(this.peerId=e,this.logger=d,!h){this.logger.error("callStats::initialize",{event:"auth_token_missing",peerId:this.peerId}),this.stallCallStats();return}this.ipInformation=await Xp.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new kT(o,r,i,c,d,e,l,h),this.iceServers=n,(m=this.backend)==null||m.registerIceServers(this.iceServers),this.initialized=!0,(y=(S=this.backend)==null?void 0:S.eventHandler)==null||y.emit("initialized",this.ipInformation),this.emit("initialized",this.ipInformation),this.startPreCallTest(u)}catch(w){this.logger.error("callStats::CallStatsIntegration",{peerId:this.peerId,error:w instanceof Error?w.message:String(w),stack:w instanceof Error?w.stack:void 0}),this.stallCallStats()}}configureSendTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerProducingTransport(e)})}configureRecvTransport(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.registerConsumingTransport(e)})}async candidateRegionalNetworkQualityTest(e){const r=new Date;this.onSafeInitialization(()=>{var i;try{(i=this.backend)==null||i.sendNetworkQualityTestBeginEvent(e,r)}catch(n){this.logger.error("callStats::sendNetworkQualityTestBeginEvent",{error:{reason:n.reason}})}})}async roomJoined(e){const r=new Date;this.onSafeInitialization(()=>{var i,n;(i=this.backend)==null||i.sendCallJoinBeginEvent(e,r),this.backend,(n=this.backend)==null||n.startPingStats()})}audioOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!1,e)})}audioOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendAudioToggleEvent(!0,e)})}videoOff(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!1,e)})}videoOn(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendVideoToggleEvent(!0,e)})}callEnded(){const e=new Date;this.onSafeInitialization(()=>{var r,i;(r=this.backend)==null||r.stopPingStats(),(i=this.backend)==null||i.sendDisconnectEvent(e)})}screenShareStart(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!0,e,r)})}consumerSharedMediaState(e,r){this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendConsumerSharedMediaStateEvent(e,r)})}screenShareStop(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendScreenShareToggleEvent(!1,e,r)})}screenShareRequested(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.sendScreenShareRequestedEvent(e)})}activeSpeaker(e){if(e!==this.peerId)return;const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendActiveSpeakerEvent(e,r)})}devices(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.devices(e,r,i)})}selectedDevice(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.selectedDevice(e,r,i)})}mediaPermission(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.mediaPermission(e,r,i)})}mediaPlaybackFailed(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaPlaybackFailed(e,r)})}mediaTrackMuted(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.mediaTrackMuted(e,r)})}tabChanged(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.tabChanged(e,r)})}browserBackgrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserBackgrounded(e)})}browserForegrounded(){const e=new Date;this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.browserForegrounded(e)})}legacySwitch(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.legacySwitch(e,r)})}async startPreCallTest(e=!1){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPreCallTestBeginEvent(e,r)})}onPreCallTestResults(e){return this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.once("precall_end",e)}),e}onReceivingConsumerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_audio_status",e)})}onReceivingConsumerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_video_status",e)})}onReceivingProducerAudioStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_audio_status",e)})}onReceivingProducerVideoStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_video_status",e)})}onReceivingProducingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producing_transport_status",e)})}onReceivingConsumingTransportStatus(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consuming_transport_status",e)})}onProducerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("producer_score",e)})}onConsumerScore(e){this.onSafeInitialization(()=>{var r;(r=this.backend)==null||r.eventHandler.on("consumer_score",e)})}onSafeInitialization(e){if(this.initialized)e(this.ipInformation,!1);else if(!this.stalled){const r=i=>{e(i,!0)};return this.once("initialized",r),r}return()=>{}}removeInitializationListener(e){this.removeListener("initialized",e)}stallCallStats(){this.stalled=!0,this.removeAllListeners("initialized")}ivsPlayerEvent(e,r){const i=new Date;this.onSafeInitialization(()=>{var n,o,c,d,l,u,h,m,S,y,w;switch(e){case"PlayerRebuffering":(n=this.backend)==null||n.sendIVSPlayerRebufferEvent(i);break;case"PlayerAudioBlocked":(o=this.backend)==null||o.sendIVSPlayerAudioBlockEvent(i);break;case"PlayerPlaybackBlocked":(c=this.backend)==null||c.sendIVSPlayerPlaybackBlockedEvent(i);break;case"PlayerNetworkUnavailable":(d=this.backend)==null||d.sendIVSPlayerNetworkUnavailableEvent(i);break;case"PlayerInitialized":(l=this.backend)==null||l.sendIVSPlayerInitializedEvent(i);break;case"PlayerWorkerError":(u=this.backend)==null||u.sendIVSPlayerWorkerErrorEvent(i);break;case"PlayerError":(h=this.backend)==null||h.sendIVSPlayerErrorEvent(r,i);break;case"PlayerRecoverableError":(m=this.backend)==null||m.sendIVSPlayerRecoverableErrorEvent(r,i);break;case"PlayerAnalyticsEvent":(S=this.backend)==null||S.sendIVSPlayerAnalyticsEvent(r,i);break;case"PlayerPlaybackRateChanged":(y=this.backend)==null||y.sendIVSPlayerPlaybackRateChangedEvent(r,i);break;case"PlayerQualityChanged":(w=this.backend)==null||w.sendIVSPlayerQualityChanged(r,i);break}})}livestreamLatency(e){const r=new Date;this.onSafeInitialization(()=>{var i;(i=this.backend)==null||i.sendPlayerLiveLatency(e,r)})}expectedVideoResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedVideoResolution(e,r,i)})}expectedScreenshareResolution(e,r){const i=new Date;this.onSafeInitialization(()=>{var n;(n=this.backend)==null||n.expectedScreenshareResolution(e,r,i)})}}new nm().setMaxListeners(30);class CT{constructor(){g(this,Po,void 0)}get telemetry(){var t;return(t=a(this,Po))==null?void 0:t.getValue("telemetry")}init(t){f(this,Po,t)}info(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("info",t,e,r)}error(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("error",t,e,r)}debug(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("debug",t,e,r)}log(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("log",t,e,r)}warn(t,e,r){var i;(i=this.telemetry)==null||i.addLogInCurrentSpan("warn",t,e,r)}}Po=new WeakMap;class RT extends dt.EventEmitter{constructor(e){super();g(this,ar,void 0);g(this,or,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,ar,new Map),f(this,or,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,ar).set(e,[]);const i=a(this,or).get(e).map(()=>new Promise(n=>{a(this,ar).get(e).push(n)}));super.emit(e,...r),await Promise.race([Promise.all(i),new Promise((n,o)=>setTimeout(()=>o(new Error(`emitAsync failed to resolve for event ${e}.`)),this.asyncPromiseTimeout))]),a(this,ar).delete(e)}onAsync(e,r){const i=a(this,ar),n=async(...o)=>{var d;try{await r(...o)}catch(l){this.logger.error("[onAsync]",{error:l})}const c=(d=i.get(e))==null?void 0:d.shift();c==null||c()};return a(this,or).get(e)||a(this,or).set(e,[]),a(this,or).get(e).push(n),super.on(e,n)}reset(){f(this,ar,new Map),f(this,or,new Map),super.removeAllListeners()}}ar=new WeakMap,or=new WeakMap;var IT=typeof global=="object"&&global&&global.Object===Object&&global;const am=IT;var AT=typeof self=="object"&&self&&self.Object===Object&&self,MT=am||AT||Function("return this")();const cs=MT;var OT=cs.Symbol;const ks=OT;var om=Object.prototype,DT=om.hasOwnProperty,NT=om.toString,Ha=ks?ks.toStringTag:void 0;function VT(s){var t=DT.call(s,Ha),e=s[Ha];try{s[Ha]=void 0;var r=!0}catch(n){}var i=NT.call(s);return r&&(t?s[Ha]=e:delete s[Ha]),i}var LT=Object.prototype,xT=LT.toString;function UT(s){return xT.call(s)}var $T="[object Null]",BT="[object Undefined]",cm=ks?ks.toStringTag:void 0;function ui(s){return s==null?s===void 0?BT:$T:cm&&cm in Object(s)?VT(s):UT(s)}function Cs(s){return s!=null&&typeof s=="object"}var FT="[object Symbol]";function od(s){return typeof s=="symbol"||Cs(s)&&ui(s)==FT}function HT(s,t){for(var e=-1,r=s==null?0:s.length,i=Array(r);++e<r;)i[e]=t(s[e],e,s);return i}var qT=Array.isArray;const Ot=qT;var jT=1/0,dm=ks?ks.prototype:void 0,lm=dm?dm.toString:void 0;function um(s){if(typeof s=="string")return s;if(Ot(s))return HT(s,um)+"";if(od(s))return lm?lm.call(s):"";var t=s+"";return t=="0"&&1/s==-jT?"-0":t}var GT=/\s/;function WT(s){for(var t=s.length;t--&&GT.test(s.charAt(t)););return t}var JT=/^\s+/;function KT(s){return s&&s.slice(0,WT(s)+1).replace(JT,"")}function Kt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var hm=0/0,zT=/^[-+]0x[0-9a-f]+$/i,YT=/^0b[01]+$/i,QT=/^0o[0-7]+$/i,XT=parseInt;function pm(s){if(typeof s=="number")return s;if(od(s))return hm;if(Kt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Kt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=KT(s);var e=YT.test(s);return e||QT.test(s)?XT(s.slice(2),e?2:8):zT.test(s)?hm:+s}function Su(s){return s}var ZT="[object AsyncFunction]",ey="[object Function]",ty="[object GeneratorFunction]",sy="[object Proxy]";function vu(s){if(!Kt(s))return!1;var t=ui(s);return t==ey||t==ty||t==ZT||t==sy}var ry=cs["__core-js_shared__"];const Tu=ry;var mm=function(){var s=/[^.]+$/.exec(Tu&&Tu.keys&&Tu.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function iy(s){return!!mm&&mm in s}var ny=Function.prototype,ay=ny.toString;function hi(s){if(s!=null){try{return ay.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var oy=/[\\^$.*+?()[\]{}|]/g,cy=/^\[object .+?Constructor\]$/,dy=Function.prototype,ly=Object.prototype,uy=dy.toString,hy=ly.hasOwnProperty,py=RegExp("^"+uy.call(hy).replace(oy,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function my(s){if(!Kt(s)||iy(s))return!1;var t=vu(s)?py:cy;return t.test(hi(s))}function gy(s,t){return s==null?void 0:s[t]}function pi(s,t){var e=gy(s,t);return my(e)?e:void 0}var fy=pi(cs,"WeakMap");const yu=fy;var gm=Object.create,Sy=function(){function s(){}return function(t){if(!Kt(t))return{};if(gm)return gm(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const vy=Sy;function Ty(s,t,e){switch(e.length){case 0:return s.call(t);case 1:return s.call(t,e[0]);case 2:return s.call(t,e[0],e[1]);case 3:return s.call(t,e[0],e[1],e[2])}return s.apply(t,e)}function yy(){}function fm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var Ey=800,by=16,wy=Date.now;function Py(s){var t=0,e=0;return function(){var r=wy(),i=by-(r-e);if(e=r,i>0){if(++t>=Ey)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function _y(s){return function(){return s}}var ky=function(){try{var s=pi(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const cd=ky;var Cy=cd?function(s,t){return cd(s,"toString",{configurable:!0,enumerable:!1,value:_y(t),writable:!0})}:Su,Ry=Py(Cy);const Iy=Ry;function Ay(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function My(s,t,e,r){for(var i=s.length,n=e+(r?1:-1);r?n--:++n<i;)if(t(s[n],n,s))return n;return-1}function Oy(s){return s!==s}function Dy(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function Ny(s,t,e){return t===t?Dy(s,t,e):My(s,Oy,e)}function Vy(s,t){var e=s==null?0:s.length;return!!e&&Ny(s,t,0)>-1}var Ly=9007199254740991,xy=/^(?:0|[1-9]\d*)$/;function Eu(s,t){var e=typeof s;return t=t==null?Ly:t,!!t&&(e=="number"||e!="symbol"&&xy.test(s))&&s>-1&&s%1==0&&s<t}function bu(s,t,e){t=="__proto__"&&cd?cd(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function qa(s,t){return s===t||s!==s&&t!==t}var Uy=Object.prototype,$y=Uy.hasOwnProperty;function Sm(s,t,e){var r=s[t];(!($y.call(s,t)&&qa(r,e))||e===void 0&&!(t in s))&&bu(s,t,e)}function ja(s,t,e,r){var i=!e;e||(e={});for(var n=-1,o=t.length;++n<o;){var c=t[n],d=r?r(e[c],s[c],c,e,s):void 0;d===void 0&&(d=s[c]),i?bu(e,c,d):Sm(e,c,d)}return e}var vm=Math.max;function By(s,t,e){return t=vm(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=vm(r.length-t,0),o=Array(n);++i<n;)o[i]=r[t+i];i=-1;for(var c=Array(t+1);++i<t;)c[i]=r[i];return c[t]=e(o),Ty(s,this,c)}}function Fy(s,t){return Iy(By(s,t,Su),s+"")}var Hy=9007199254740991;function wu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=Hy}function Ga(s){return s!=null&&wu(s.length)&&!vu(s)}function qy(s,t,e){if(!Kt(e))return!1;var r=typeof t;return(r=="number"?Ga(e)&&Eu(t,e.length):r=="string"&&t in e)?qa(e[t],s):!1}function jy(s){return Fy(function(t,e){var r=-1,i=e.length,n=i>1?e[i-1]:void 0,o=i>2?e[2]:void 0;for(n=s.length>3&&typeof n=="function"?(i--,n):void 0,o&&qy(e[0],e[1],o)&&(n=i<3?void 0:n,i=1),t=Object(t);++r<i;){var c=e[r];c&&s(t,c,r,n)}return t})}var Gy=Object.prototype;function dd(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||Gy;return s===e}function Wy(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var Jy="[object Arguments]";function Tm(s){return Cs(s)&&ui(s)==Jy}var ym=Object.prototype,Ky=ym.hasOwnProperty,zy=ym.propertyIsEnumerable,Yy=Tm(function(){return arguments}())?Tm:function(s){return Cs(s)&&Ky.call(s,"callee")&&!zy.call(s,"callee")};const Wa=Yy;function Qy(){return!1}var Em=typeof exports=="object"&&exports&&!exports.nodeType&&exports,bm=Em&&typeof module=="object"&&module&&!module.nodeType&&module,Xy=bm&&bm.exports===Em,wm=Xy?cs.Buffer:void 0,Zy=wm?wm.isBuffer:void 0,eE=Zy||Qy;const yn=eE;var tE="[object Arguments]",sE="[object Array]",rE="[object Boolean]",iE="[object Date]",nE="[object Error]",aE="[object Function]",oE="[object Map]",cE="[object Number]",dE="[object Object]",lE="[object RegExp]",uE="[object Set]",hE="[object String]",pE="[object WeakMap]",mE="[object ArrayBuffer]",gE="[object DataView]",fE="[object Float32Array]",SE="[object Float64Array]",vE="[object Int8Array]",TE="[object Int16Array]",yE="[object Int32Array]",EE="[object Uint8Array]",bE="[object Uint8ClampedArray]",wE="[object Uint16Array]",PE="[object Uint32Array]",ye={};ye[fE]=ye[SE]=ye[vE]=ye[TE]=ye[yE]=ye[EE]=ye[bE]=ye[wE]=ye[PE]=!0,ye[tE]=ye[sE]=ye[mE]=ye[rE]=ye[gE]=ye[iE]=ye[nE]=ye[aE]=ye[oE]=ye[cE]=ye[dE]=ye[lE]=ye[uE]=ye[hE]=ye[pE]=!1;function _E(s){return Cs(s)&&wu(s.length)&&!!ye[ui(s)]}function Pu(s){return function(t){return s(t)}}var Pm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ja=Pm&&typeof module=="object"&&module&&!module.nodeType&&module,kE=Ja&&Ja.exports===Pm,_u=kE&&am.process,CE=function(){try{var s=Ja&&Ja.require&&Ja.require("util").types;return s||_u&&_u.binding&&_u.binding("util")}catch(t){}}();const En=CE;var _m=En&&En.isTypedArray,RE=_m?Pu(_m):_E;const ld=RE;var IE=Object.prototype,AE=IE.hasOwnProperty;function km(s,t){var e=Ot(s),r=!e&&Wa(s),i=!e&&!r&&yn(s),n=!e&&!r&&!i&&ld(s),o=e||r||i||n,c=o?Wy(s.length,String):[],d=c.length;for(var l in s)(t||AE.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Eu(l,d)))&&c.push(l);return c}function Cm(s,t){return function(e){return s(t(e))}}var ME=Cm(Object.keys,Object);const OE=ME;var DE=Object.prototype,NE=DE.hasOwnProperty;function Rm(s){if(!dd(s))return OE(s);var t=[];for(var e in Object(s))NE.call(s,e)&&e!="constructor"&&t.push(e);return t}function ud(s){return Ga(s)?km(s):Rm(s)}function VE(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var LE=Object.prototype,xE=LE.hasOwnProperty;function UE(s){if(!Kt(s))return VE(s);var t=dd(s),e=[];for(var r in s)r=="constructor"&&(t||!xE.call(s,r))||e.push(r);return e}function Ka(s){return Ga(s)?km(s,!0):UE(s)}var $E=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,BE=/^\w*$/;function ku(s,t){if(Ot(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||od(s)?!0:BE.test(s)||!$E.test(s)||t!=null&&s in Object(t)}var FE=pi(Object,"create");const za=FE;function HE(){this.__data__=za?za(null):{},this.size=0}function qE(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var jE="__lodash_hash_undefined__",GE=Object.prototype,WE=GE.hasOwnProperty;function JE(s){var t=this.__data__;if(za){var e=t[s];return e===jE?void 0:e}return WE.call(t,s)?t[s]:void 0}var KE=Object.prototype,zE=KE.hasOwnProperty;function YE(s){var t=this.__data__;return za?t[s]!==void 0:zE.call(t,s)}var QE="__lodash_hash_undefined__";function XE(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=za&&t===void 0?QE:t,this}function mi(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}mi.prototype.clear=HE,mi.prototype.delete=qE,mi.prototype.get=JE,mi.prototype.has=YE,mi.prototype.set=XE;function ZE(){this.__data__=[],this.size=0}function hd(s,t){for(var e=s.length;e--;)if(qa(s[e][0],t))return e;return-1}var eb=Array.prototype,tb=eb.splice;function sb(s){var t=this.__data__,e=hd(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():tb.call(t,e,1),--this.size,!0}function rb(s){var t=this.__data__,e=hd(t,s);return e<0?void 0:t[e][1]}function ib(s){return hd(this.__data__,s)>-1}function nb(s,t){var e=this.__data__,r=hd(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function js(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}js.prototype.clear=ZE,js.prototype.delete=sb,js.prototype.get=rb,js.prototype.has=ib,js.prototype.set=nb;var ab=pi(cs,"Map");const Ya=ab;function ob(){this.size=0,this.__data__={hash:new mi,map:new(Ya||js),string:new mi}}function cb(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function pd(s,t){var e=s.__data__;return cb(t)?e[typeof t=="string"?"string":"hash"]:e.map}function db(s){var t=pd(this,s).delete(s);return this.size-=t?1:0,t}function lb(s){return pd(this,s).get(s)}function ub(s){return pd(this,s).has(s)}function hb(s,t){var e=pd(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function Gs(s){var t=-1,e=s==null?0:s.length;for(this.clear();++t<e;){var r=s[t];this.set(r[0],r[1])}}Gs.prototype.clear=ob,Gs.prototype.delete=db,Gs.prototype.get=lb,Gs.prototype.has=ub,Gs.prototype.set=hb;var pb="Expected a function";function Cu(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(pb);var e=function(){var r=arguments,i=t?t.apply(this,r):r[0],n=e.cache;if(n.has(i))return n.get(i);var o=s.apply(this,r);return e.cache=n.set(i,o)||n,o};return e.cache=new(Cu.Cache||Gs),e}Cu.Cache=Gs;var mb=500;function gb(s){var t=Cu(s,function(r){return e.size===mb&&e.clear(),r}),e=t.cache;return t}var fb=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Sb=/\\(\\)?/g,vb=gb(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(fb,function(e,r,i,n){t.push(i?n.replace(Sb,"$1"):r||e)}),t});const Tb=vb;function yb(s){return s==null?"":um(s)}function Im(s,t){return Ot(s)?s:ku(s,t)?[s]:Tb(yb(s))}var Eb=1/0;function md(s){if(typeof s=="string"||od(s))return s;var t=s+"";return t=="0"&&1/s==-Eb?"-0":t}function Am(s,t){t=Im(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[md(t[e++])];return e&&e==r?s:void 0}function bb(s,t,e){var r=s==null?void 0:Am(s,t);return r===void 0?e:r}function Mm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var wb=Cm(Object.getPrototypeOf,Object);const Ru=wb;var Pb="[object Object]",_b=Function.prototype,kb=Object.prototype,Om=_b.toString,Cb=kb.hasOwnProperty,Rb=Om.call(Object);function Ib(s){if(!Cs(s)||ui(s)!=Pb)return!1;var t=Ru(s);if(t===null)return!0;var e=Cb.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Om.call(e)==Rb}function Ab(){this.__data__=new js,this.size=0}function Mb(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function Ob(s){return this.__data__.get(s)}function Db(s){return this.__data__.has(s)}var Nb=200;function Vb(s,t){var e=this.__data__;if(e instanceof js){var r=e.__data__;if(!Ya||r.length<Nb-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new Gs(r)}return e.set(s,t),this.size=e.size,this}function ds(s){var t=this.__data__=new js(s);this.size=t.size}ds.prototype.clear=Ab,ds.prototype.delete=Mb,ds.prototype.get=Ob,ds.prototype.has=Db,ds.prototype.set=Vb;function Lb(s,t){return s&&ja(t,ud(t),s)}function xb(s,t){return s&&ja(t,Ka(t),s)}var Dm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Nm=Dm&&typeof module=="object"&&module&&!module.nodeType&&module,Ub=Nm&&Nm.exports===Dm,Vm=Ub?cs.Buffer:void 0,Lm=Vm?Vm.allocUnsafe:void 0;function xm(s,t){if(t)return s.slice();var e=s.length,r=Lm?Lm(e):new s.constructor(e);return s.copy(r),r}function $b(s,t){for(var e=-1,r=s==null?0:s.length,i=0,n=[];++e<r;){var o=s[e];t(o,e,s)&&(n[i++]=o)}return n}function Um(){return[]}var Bb=Object.prototype,Fb=Bb.propertyIsEnumerable,$m=Object.getOwnPropertySymbols,Hb=$m?function(s){return s==null?[]:(s=Object(s),$b($m(s),function(t){return Fb.call(s,t)}))}:Um;const Iu=Hb;function qb(s,t){return ja(s,Iu(s),t)}var jb=Object.getOwnPropertySymbols,Gb=jb?function(s){for(var t=[];s;)Mm(t,Iu(s)),s=Ru(s);return t}:Um;const Bm=Gb;function Wb(s,t){return ja(s,Bm(s),t)}function Fm(s,t,e){var r=t(s);return Ot(s)?r:Mm(r,e(s))}function Au(s){return Fm(s,ud,Iu)}function Jb(s){return Fm(s,Ka,Bm)}var Kb=pi(cs,"DataView");const Mu=Kb;var zb=pi(cs,"Promise");const Ou=zb;var Yb=pi(cs,"Set");const bn=Yb;var Hm="[object Map]",Qb="[object Object]",qm="[object Promise]",jm="[object Set]",Gm="[object WeakMap]",Wm="[object DataView]",Xb=hi(Mu),Zb=hi(Ya),ew=hi(Ou),tw=hi(bn),sw=hi(yu),gi=ui;(Mu&&gi(new Mu(new ArrayBuffer(1)))!=Wm||Ya&&gi(new Ya)!=Hm||Ou&&gi(Ou.resolve())!=qm||bn&&gi(new bn)!=jm||yu&&gi(new yu)!=Gm)&&(gi=function(s){var t=ui(s),e=t==Qb?s.constructor:void 0,r=e?hi(e):"";if(r)switch(r){case Xb:return Wm;case Zb:return Hm;case ew:return qm;case tw:return jm;case sw:return Gm}return t});const wn=gi;var rw=Object.prototype,iw=rw.hasOwnProperty;function nw(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&iw.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var aw=cs.Uint8Array;const gd=aw;function Du(s){var t=new s.constructor(s.byteLength);return new gd(t).set(new gd(s)),t}function ow(s,t){var e=t?Du(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var cw=/\w*$/;function dw(s){var t=new s.constructor(s.source,cw.exec(s));return t.lastIndex=s.lastIndex,t}var Jm=ks?ks.prototype:void 0,Km=Jm?Jm.valueOf:void 0;function lw(s){return Km?Object(Km.call(s)):{}}function zm(s,t){var e=t?Du(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var uw="[object Boolean]",hw="[object Date]",pw="[object Map]",mw="[object Number]",gw="[object RegExp]",fw="[object Set]",Sw="[object String]",vw="[object Symbol]",Tw="[object ArrayBuffer]",yw="[object DataView]",Ew="[object Float32Array]",bw="[object Float64Array]",ww="[object Int8Array]",Pw="[object Int16Array]",_w="[object Int32Array]",kw="[object Uint8Array]",Cw="[object Uint8ClampedArray]",Rw="[object Uint16Array]",Iw="[object Uint32Array]";function Aw(s,t,e){var r=s.constructor;switch(t){case Tw:return Du(s);case uw:case hw:return new r(+s);case yw:return ow(s,e);case Ew:case bw:case ww:case Pw:case _w:case kw:case Cw:case Rw:case Iw:return zm(s,e);case pw:return new r;case mw:case Sw:return new r(s);case gw:return dw(s);case fw:return new r;case vw:return lw(s)}}function Ym(s){return typeof s.constructor=="function"&&!dd(s)?vy(Ru(s)):{}}var Mw="[object Map]";function Ow(s){return Cs(s)&&wn(s)==Mw}var Qm=En&&En.isMap,Dw=Qm?Pu(Qm):Ow;const Nw=Dw;var Vw="[object Set]";function Lw(s){return Cs(s)&&wn(s)==Vw}var Xm=En&&En.isSet,xw=Xm?Pu(Xm):Lw;const Uw=xw;var $w=1,Bw=2,Fw=4,Zm="[object Arguments]",Hw="[object Array]",qw="[object Boolean]",jw="[object Date]",Gw="[object Error]",eg="[object Function]",Ww="[object GeneratorFunction]",Jw="[object Map]",Kw="[object Number]",tg="[object Object]",zw="[object RegExp]",Yw="[object Set]",Qw="[object String]",Xw="[object Symbol]",Zw="[object WeakMap]",eP="[object ArrayBuffer]",tP="[object DataView]",sP="[object Float32Array]",rP="[object Float64Array]",iP="[object Int8Array]",nP="[object Int16Array]",aP="[object Int32Array]",oP="[object Uint8Array]",cP="[object Uint8ClampedArray]",dP="[object Uint16Array]",lP="[object Uint32Array]",ge={};ge[Zm]=ge[Hw]=ge[eP]=ge[tP]=ge[qw]=ge[jw]=ge[sP]=ge[rP]=ge[iP]=ge[nP]=ge[aP]=ge[Jw]=ge[Kw]=ge[tg]=ge[zw]=ge[Yw]=ge[Qw]=ge[Xw]=ge[oP]=ge[cP]=ge[dP]=ge[lP]=!0,ge[Gw]=ge[eg]=ge[Zw]=!1;function Qa(s,t,e,r,i,n){var o,c=t&$w,d=t&Bw,l=t&Fw;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!Kt(s))return s;var u=Ot(s);if(u){if(o=nw(s),!c)return fm(s,o)}else{var h=wn(s),m=h==eg||h==Ww;if(yn(s))return xm(s,c);if(h==tg||h==Zm||m&&!i){if(o=d||m?{}:Ym(s),!c)return d?Wb(s,xb(o,s)):qb(s,Lb(o,s))}else{if(!ge[h])return i?s:{};o=Aw(s,h,c)}}n||(n=new ds);var S=n.get(s);if(S)return S;n.set(s,o),Uw(s)?s.forEach(function(_){o.add(Qa(_,t,e,_,s,n))}):Nw(s)&&s.forEach(function(_,C){o.set(C,Qa(_,t,e,C,s,n))});var y=l?d?Jb:Au:d?Ka:ud,w=u?void 0:y(s);return Ay(w||s,function(_,C){w&&(C=_,_=s[C]),Sm(o,C,Qa(_,t,e,C,s,n))}),o}var uP=4;function hP(s){return Qa(s,uP)}var pP=1,mP=4;function Nu(s){return Qa(s,pP|mP)}var gP="__lodash_hash_undefined__";function fP(s){return this.__data__.set(s,gP),this}function SP(s){return this.__data__.has(s)}function Xa(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new Gs;++t<e;)this.add(s[t])}Xa.prototype.add=Xa.prototype.push=fP,Xa.prototype.has=SP;function vP(s,t){for(var e=-1,r=s==null?0:s.length;++e<r;)if(t(s[e],e,s))return!0;return!1}function sg(s,t){return s.has(t)}var TP=1,yP=2;function rg(s,t,e,r,i,n){var o=e&TP,c=s.length,d=t.length;if(c!=d&&!(o&&d>c))return!1;var l=n.get(s),u=n.get(t);if(l&&u)return l==t&&u==s;var h=-1,m=!0,S=e&yP?new Xa:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var y=s[h],w=t[h];if(r)var _=o?r(w,y,h,t,s,n):r(y,w,h,s,t,n);if(_!==void 0){if(_)continue;m=!1;break}if(S){if(!vP(t,function(C,D){if(!sg(S,D)&&(y===C||i(y,C,e,r,n)))return S.push(D)})){m=!1;break}}else if(!(y===w||i(y,w,e,r,n))){m=!1;break}}return n.delete(s),n.delete(t),m}function EP(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function Vu(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var bP=1,wP=2,PP="[object Boolean]",_P="[object Date]",kP="[object Error]",CP="[object Map]",RP="[object Number]",IP="[object RegExp]",AP="[object Set]",MP="[object String]",OP="[object Symbol]",DP="[object ArrayBuffer]",NP="[object DataView]",ig=ks?ks.prototype:void 0,Lu=ig?ig.valueOf:void 0;function VP(s,t,e,r,i,n,o){switch(e){case NP:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case DP:return!(s.byteLength!=t.byteLength||!n(new gd(s),new gd(t)));case PP:case _P:case RP:return qa(+s,+t);case kP:return s.name==t.name&&s.message==t.message;case IP:case MP:return s==t+"";case CP:var c=EP;case AP:var d=r&bP;if(c||(c=Vu),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=wP,o.set(s,t);var u=rg(c(s),c(t),r,i,n,o);return o.delete(s),u;case OP:if(Lu)return Lu.call(s)==Lu.call(t)}return!1}var LP=1,xP=Object.prototype,UP=xP.hasOwnProperty;function $P(s,t,e,r,i,n){var o=e&LP,c=Au(s),d=c.length,l=Au(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var m=c[h];if(!(o?m in t:UP.call(t,m)))return!1}var S=n.get(s),y=n.get(t);if(S&&y)return S==t&&y==s;var w=!0;n.set(s,t),n.set(t,s);for(var _=o;++h<d;){m=c[h];var C=s[m],D=t[m];if(r)var V=o?r(D,C,m,t,s,n):r(C,D,m,s,t,n);if(!(V===void 0?C===D||i(C,D,e,r,n):V)){w=!1;break}_||(_=m=="constructor")}if(w&&!_){var $=s.constructor,H=t.constructor;$!=H&&"constructor"in s&&"constructor"in t&&!(typeof $=="function"&&$ instanceof $&&typeof H=="function"&&H instanceof H)&&(w=!1)}return n.delete(s),n.delete(t),w}var BP=1,ng="[object Arguments]",ag="[object Array]",fd="[object Object]",FP=Object.prototype,og=FP.hasOwnProperty;function HP(s,t,e,r,i,n){var o=Ot(s),c=Ot(t),d=o?ag:wn(s),l=c?ag:wn(t);d=d==ng?fd:d,l=l==ng?fd:l;var u=d==fd,h=l==fd,m=d==l;if(m&&yn(s)){if(!yn(t))return!1;o=!0,u=!1}if(m&&!u)return n||(n=new ds),o||ld(s)?rg(s,t,e,r,i,n):VP(s,t,d,e,r,i,n);if(!(e&BP)){var S=u&&og.call(s,"__wrapped__"),y=h&&og.call(t,"__wrapped__");if(S||y){var w=S?s.value():s,_=y?t.value():t;return n||(n=new ds),i(w,_,e,r,n)}}return m?(n||(n=new ds),$P(s,t,e,r,i,n)):!1}function Sd(s,t,e,r,i){return s===t?!0:s==null||t==null||!Cs(s)&&!Cs(t)?s!==s&&t!==t:HP(s,t,e,r,Sd,i)}var qP=1,jP=2;function GP(s,t,e,r){var i=e.length,n=i,o=!r;if(s==null)return!n;for(s=Object(s);i--;){var c=e[i];if(o&&c[2]?c[1]!==s[c[0]]:!(c[0]in s))return!1}for(;++i<n;){c=e[i];var d=c[0],l=s[d],u=c[1];if(o&&c[2]){if(l===void 0&&!(d in s))return!1}else{var h=new ds;if(r)var m=r(l,u,d,s,t,h);if(!(m===void 0?Sd(u,l,qP|jP,r,h):m))return!1}}return!0}function cg(s){return s===s&&!Kt(s)}function WP(s){for(var t=ud(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,cg(i)]}return t}function dg(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function JP(s){var t=WP(s);return t.length==1&&t[0][2]?dg(t[0][0],t[0][1]):function(e){return e===s||GP(e,s,t)}}function KP(s,t){return s!=null&&t in Object(s)}function zP(s,t,e){t=Im(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=md(t[r]);if(!(n=s!=null&&e(s,o)))break;s=s[o]}return n||++r!=i?n:(i=s==null?0:s.length,!!i&&wu(i)&&Eu(o,i)&&(Ot(s)||Wa(s)))}function YP(s,t){return s!=null&&zP(s,t,KP)}var QP=1,XP=2;function ZP(s,t){return ku(s)&&cg(t)?dg(md(s),t):function(e){var r=bb(e,s);return r===void 0&&r===t?YP(e,s):Sd(t,r,QP|XP)}}function e_(s){return function(t){return t==null?void 0:t[s]}}function t_(s){return function(t){return Am(t,s)}}function s_(s){return ku(s)?e_(md(s)):t_(s)}function r_(s){return typeof s=="function"?s:s==null?Su:typeof s=="object"?Ot(s)?ZP(s[0],s[1]):JP(s):s_(s)}function i_(s){return function(t,e,r){for(var i=-1,n=Object(t),o=r(t),c=o.length;c--;){var d=o[s?c:++i];if(e(n[d],d,n)===!1)break}return t}}var n_=i_();const a_=n_;var o_=function(){return cs.Date.now()};const xu=o_;var c_="Expected a function",d_=Math.max,l_=Math.min;function Uu(s,t,e){var r,i,n,o,c,d,l=0,u=!1,h=!1,m=!0;if(typeof s!="function")throw new TypeError(c_);t=pm(t)||0,Kt(e)&&(u=!!e.leading,h="maxWait"in e,n=h?d_(pm(e.maxWait)||0,t):n,m="trailing"in e?!!e.trailing:m);function S(F){var Z=r,be=i;return r=i=void 0,l=F,o=s.apply(be,Z),o}function y(F){return l=F,c=setTimeout(C,t),u?S(F):o}function w(F){var Z=F-d,be=F-l,Ge=t-Z;return h?l_(Ge,n-be):Ge}function _(F){var Z=F-d,be=F-l;return d===void 0||Z>=t||Z<0||h&&be>=n}function C(){var F=xu();if(_(F))return D(F);c=setTimeout(C,w(F))}function D(F){return c=void 0,m&&r?S(F):(r=i=void 0,o)}function V(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function $(){return c===void 0?o:D(xu())}function H(){var F=xu(),Z=_(F);if(r=arguments,i=this,d=F,Z){if(c===void 0)return y(d);if(h)return clearTimeout(c),c=setTimeout(C,t),S(d)}return c===void 0&&(c=setTimeout(C,t)),o}return H.cancel=V,H.flush=$,H}function $u(s,t,e){(e!==void 0&&!qa(s[t],e)||e===void 0&&!(t in s))&&bu(s,t,e)}function u_(s){return Cs(s)&&Ga(s)}function Bu(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function h_(s){return ja(s,Ka(s))}function p_(s,t,e,r,i,n,o){var c=Bu(s,e),d=Bu(t,e),l=o.get(d);if(l){$u(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var m=Ot(d),S=!m&&yn(d),y=!m&&!S&&ld(d);u=d,m||S||y?Ot(c)?u=c:u_(c)?u=fm(c):S?(h=!1,u=xm(d,!0)):y?(h=!1,u=zm(d,!0)):u=[]:Ib(d)||Wa(d)?(u=c,Wa(c)?u=h_(c):(!Kt(c)||vu(c))&&(u=Ym(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),$u(s,e,u)}function lg(s,t,e,r,i){s!==t&&a_(t,function(n,o){if(i||(i=new ds),Kt(n))p_(s,t,o,e,lg,r,i);else{var c=r?r(Bu(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),$u(s,o,c)}},Ka)}function m_(s,t,e){for(var r=-1,i=s==null?0:s.length;++r<i;)if(e(t,s[r]))return!0;return!1}var g_="[object Map]",f_="[object Set]",S_=Object.prototype,v_=S_.hasOwnProperty;function T_(s){if(s==null)return!0;if(Ga(s)&&(Ot(s)||typeof s=="string"||typeof s.splice=="function"||yn(s)||ld(s)||Wa(s)))return!s.length;var t=wn(s);if(t==g_||t==f_)return!s.size;if(dd(s))return!Rm(s).length;for(var e in s)if(v_.call(s,e))return!1;return!0}function y_(s,t){return Sd(s,t)}var E_=jy(function(s,t,e){lg(s,t,e)});const Cr=E_;var b_=1/0,w_=bn&&1/Vu(new bn([,-0]))[1]==b_?function(s){return new bn(s)}:yy;const P_=w_;var __=200;function ug(s,t,e){var r=-1,i=Vy,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=m_;else if(n>=__){var l=t?null:P_(s);if(l)return Vu(l);o=!1,i=sg,d=new Xa}else d=t?[]:c;e:for(;++r<n;){var u=s[r],h=t?t(u):u;if(u=e||u!==0?u:0,o&&h===h){for(var m=d.length;m--;)if(d[m]===h)continue e;t&&d.push(h),c.push(u)}else i(d,h,e)||(d!==c&&d.push(h),c.push(u))}return c}function k_(s){return s&&s.length?ug(s):[]}function C_(s,t){return s&&s.length?ug(s,r_(t)):[]}function vd(s){const t={};return typeof(s==null?void 0:s.code)=="number"&&(t.code=s.code),typeof(s==null?void 0:s.code)=="string"&&(t.code=s.code.substring(0,100)),typeof(s==null?void 0:s.name)=="string"&&(t.name=s.name.substring(0,500)),typeof(s==null?void 0:s.message)=="string"&&(t.message=s.message.substring(0,500)),typeof(s==null?void 0:s.reason)=="string"&&(t.reason=s.reason.substring(0,500)),typeof(s==null?void 0:s.stack)=="string"&&(t.stack=s.stack.substring(0,500)),t}const R_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},hg={STAGING:"staging",PROD:"prod"},I_={pip:!0,poll:!0,chat:!0,stage:!0,theme:!0,plugin:!0,tracing:!0,internals:!0,recording:!0,livestream:!0,participant:!0,connectedMeetings:!0,devTools:{logs:!1}};function Pn(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function A_({baseURI:s}){return s.includes("staging.realtime")?hg.STAGING:hg.PROD}function _n({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function M_(s){const t=s.getValue("baseURI");return{location:_n({servicePrefix:"location",baseURI:t}),locationLegacy:_n({servicePrefix:"location-legacy",baseURI:t}),daCollector:_n({servicePrefix:"da-collector",baseURI:t})}}const O_='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m16.242 2.932 4.826 4.826a2.75 2.75 0 0 1-.715 4.404l-4.87 2.435a.75.75 0 0 0-.374.426l-1.44 4.166a1.25 1.25 0 0 1-2.065.476L8.5 16.561 4.06 21H3v-1.06l4.44-4.44-3.105-3.104a1.25 1.25 0 0 1 .476-2.066l4.166-1.44a.75.75 0 0 0 .426-.373l2.435-4.87a2.75 2.75 0 0 1 4.405-.715Zm3.766 5.886-4.826-4.826a1.25 1.25 0 0 0-2.002.325l-2.435 4.871a2.25 2.25 0 0 1-1.278 1.12l-3.789 1.31 6.705 6.704 1.308-3.789a2.25 2.25 0 0 1 1.12-1.277l4.872-2.436a1.25 1.25 0 0 0 .325-2.002Z" fill="currentColor"/></svg>',D_='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Td=s=>{if(!s)return;if(!s.startsWith("<svg"))return new Promise(n=>{n(s)});const e=new Blob([s],{type:"image/svg+xml"}),r=new Image,i=window.URL.createObjectURL(e);return new Promise((n,o)=>{r.onload=()=>{n(r),window.URL.revokeObjectURL(i)},r.onerror=()=>{o(),window.URL.revokeObjectURL(i)},r.src=i})},fi={logs:"https://api.realtime.cloudflare.com/logs/otel/logs",mock:{url:"https://api.realtime.cloudflare.com/mock",domain:"mock.realtime.cloudflare.com",app:"https://examples.realtime.cloudflare.com/meeting",stagingApp:"https://examples.staging.realtime.cloudflare.com/meeting"},apiBase:{prod:"https://api.realtime.cloudflare.com",staging:"https://api.staging.realtime.cloudflare.com",prodAlternate:"https://api.realtime.cloudflare.com"},baseURI:{prod:"realtime.cloudflare.com",staging:"staging.realtime.cloudflare.com"}},N_=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,Fu="__rtk_plugins__",V_=[Fu];function pg(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(fi.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function L_(s,t){var r;const e=(r=s==null?void 0:s.getValue("telemetry"))==null?void 0:r.logLevel;if(e==="off")return!1;if(e!=="all"){const i=["debug","log","info","warn","error"],n=i.indexOf(t.toLowerCase()),o=i.indexOf(e);if(n<o)return!1}return!0}function mg(s,t,e={}){return Object.getOwnPropertyNames(s).forEach(r=>{var n;if([null,void 0,NaN].includes(s[r])||t&&(((n=t.match(/\./g))==null?void 0:n.length)||0)>=10)return;const i=t?`${t}.${r}`:r;typeof s[r]=="object"?mg(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function gg(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=mg(o,r),d=JSON.stringify(c);if(!(t==null?void 0:t.startsWith("[SDP]"))&&d.length>5e3){const u=`Log named: "${t}" is trying to log an flattened object of size
10
+ ${d.length} chars that is beyond permitted limit of 5000 chars. Please optimize.`;throw pg(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(n){const o=vd(n);i[`${r}.error.message`]=o.message||"",i[`${r}.error.stack`]=o.stack||"",i[`${r}.error.reason`]=o.reason||"",i[`${r}.error.source`]="safelyFlattenObjForOpenTelemetry"}return i}class E{constructor(){p(this,"logsCache",[]);p(this,"logsProcessorTimer");p(this,"compressionSupported",null);p(this,"tracingEnabled",!0);p(this,"initialized",!1);p(this,"logLevel","log");p(this,"logsProcessingInterval",7e3);p(this,"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"]);p(this,"meetingMetadata",{})}isCompressionSupported(){if(this.compressionSupported===null)try{this.compressionSupported=typeof CompressionStream!="undefined"&&typeof Blob!="undefined"&&typeof Blob.prototype.stream=="function"&&typeof Response!="undefined"}catch(t){this.compressionSupported=!1,this.addLogInCurrentSpan("warn","Compression feature detection failed, using uncompressed logs",{error:t})}return this.compressionSupported}get logsEndpoint(){const t=Rr.getContext(this.meetingMetadata.peerId);return`https://${_n({servicePrefix:"api-silos",baseURI:t.getValue("baseURI")})}/otel/logs`}get logsBatchSize(){return this.isCompressionSupported()?50:25}resetPeerId(t){this.meetingMetadata.peerId=t}init(t,e,r,i){this.tracingEnabled=!0,this.initialized=!1,i&&(this.logLevel=i),this.logsCache=[];const n=t.getValue("peerId");this.meetingMetadata=e,this.tracingEnabled=r,this.meetingMetadata.peerId=n,this.meetingMetadata.sdkVersion=t.getValue("sdkVersion");const{RNDeviceInfoImpl:o}=navigator;this.meetingMetadata.deviceInfo=navigator.isReactNative?o==null?void 0:o.getDeviceInfo():Te.getDeviceInfo(),this.meetingMetadata.visitedUrl=!navigator.isReactNative&&typeof window!="undefined"&&window.location.href,this.logsProcessorTimer=setInterval(()=>this.processCachedLogs().catch(()=>{}),this.logsProcessingInterval),r&&(this.initialized=!0)}static trace(t,e=void 0){return(r,i,n)=>{const o=n.value;return n.value=function(...d){const l=this==null?void 0:this.telemetry;if(!l||!l.initialized||navigator.isReactNative||!l.tracingEnabled)return o.apply(this,d);l.addLogInCurrentSpan("info",t,e);const u=performance.now(),h=o.apply(this,d);return Promise.resolve(h).then(()=>{const m=performance.now();m-u>10&&l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:m-u})}).catch(()=>{const m=performance.now();l.addLogInCurrentSpan("info",`${t}_timing`,{execTime:m-u})}),h},n}}injectContext(t){var i;const e=vn().replace(/-/g,"").substring(0,16),r=(i=this.meetingMetadata.peerId)==null?void 0:i.replace(/-/g,"");t.TRACEPARENT=`00-${r}-${e}-01`}addLogInCurrentSpan(t,e,r={},i=!1){r!=null&&r.error&&Object.assign(r,{error:vd(r.error)});const n=Rr.getContext(this.meetingMetadata.peerId);if(pg(n)&&(T_(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!L_(n,t))try{const c=gg(n,e,r,"metadata"),d=new Date,l={message:e,level:t,...c,loggedAt:d.toISOString(),loggedAtTzOffset:d.getTimezoneOffset()};i?this.sendOtelLogsToNewRelic([l],{isInDestructionMode:!1}).catch(()=>{}):this.logsCache.push(l)}catch(c){this.addLogInCurrentSpan("error","opentelemetry::addLogInCurrentSpan_failed",{error:vd(c)})}}async sendOtelLogsToNewRelic(t,{isInDestructionMode:e=!1}={isInDestructionMode:!1}){const r=new AbortController,i=setTimeout(()=>r.abort("Logs request timed out after 8 seconds"),8e3);try{const n=Rr.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:gg(n,"sendOtelLogsToNewRelic",this.meetingMetadata,"meetingMetadata"),serviceName:n.getValue("sdkName"),logs:t});let c;const d={Authorization:`Bearer ${n.getValue("authToken")}`};if(this.isCompressionSupported()){const l=new Blob([o]).stream().pipeThrough(new CompressionStream("gzip"));c=await new Response(l).arrayBuffer(),d["Content-Type"]="application/gzip",d["Content-Encoding"]="gzip"}else c=o,d["Content-Type"]="application/json";await fetch(this.logsEndpoint,{method:"POST",headers:d,body:c,signal:r.signal,keepalive:!!e})}catch(n){e||(this.addLogInCurrentSpan("error","opentelemetry::sendOtelLogToNewRelic_failed",{error:vd(n)}),this.logsCache.push(...t))}finally{clearTimeout(i)}}async processCachedLogs({isInDestructionMode:t=!1}={isInDestructionMode:!1}){const e=this.logsCache.splice(0,this.logsBatchSize);e!=null&&e.length&&await this.sendOtelLogsToNewRelic(e,{isInDestructionMode:t})}async destruct(){for(clearInterval(this.logsProcessorTimer);this.logsCache.length;)await this.processCachedLogs({isInDestructionMode:!0})}}function x_(s){const t={...s},e=new Map,r=(l,u)=>(e.has(l)||e.set(l,new Set),e.get(l).add(u),()=>{var h;return(h=e.get(l))==null?void 0:h.delete(u)}),i=(l,u)=>{var h;(h=e.get(l))==null||h.delete(u)},n=l=>{var u;(u=e.get(l))==null||u.forEach(h=>{try{h(t[l])}catch(m){}})};return{subscribe:r,unsubscribe:i,notify:n,setValue:(l,u,h=!0)=>{t[l]=u,h&&n(l)},getValue:l=>t[l],getAllValues:()=>t}}class U_{constructor(){p(this,"contexts",new Map);p(this,"mostRecentPeerId",null)}createContext(t,e){if(this.contexts.has(t))return this.contexts.get(t);const r=new E,i=new CT;this.contexts.set(t,x_(e)),this.contexts.get(t).setValue("peerSessionStore",new RT(i));const n=new nm;return n.setMaxListeners(50),this.contexts.get(t).setValue("logger",i),this.contexts.get(t).setValue("telemetry",r),this.contexts.get(t).setValue("callstats",n),this.mostRecentPeerId=t,this.contexts.get(t)}remapContext(t,e){const r=e.getValue("peerId");r!==t&&(e.setValue("peerId",t),this.mostRecentPeerId=t,this.contexts.set(t,e),this.contexts.delete(r))}getContext(t){return this.contexts.get(t)}getMostRecentPeerId(){return this.mostRecentPeerId}}const Rr=new U_,$_={"00":"Client","01":"Controller","02":"RoomNodeClient","03":"HiveNodeClient","04":"SocketService","05":"Chat","06":"Plugin","07":"Polls","08":"Meta","09":"Preset",10:"Recording",11:"Self",12:"Participant",13:"Spotlight",14:"Remote Request",15:"Webinar",16:"LocalMediaHandler",17:"End-End Encryption",18:"AI",19:"Livestream",20:"Stage"},yd={"0000":"Internal exception.","0001":"Failed to initialize.","0002":"Failed to join room.","0003":"Failed to leave room.","0004":"Invalid auth token","0010":"Browser not supported","0011":"HTTP Network Error","0012":"Websocket Network Error","0013":"Rate Limited","0014":"Failed to establish media connection.","0100":"Internal exception","0101":"Permission denied","0102":"Prerequisite module missing","0200":"Internal exception.","0300":"Internal exception","0400":"Internal exception","0404":"Missing prerequisites to establish a websocket connection","0500":"Internal exception","0501":"Permission denied.","0502":"Invalid message body.","0503":"Text Message is too large","0504":"Message not found by the given id","0505":"Action not permitted without joining room","0506":"Message search is disabled","0600":"Internal exception","0601":"Permission denied.","0602":"Auth token not set for plugin","0603":"Iframe was not provided","0604":"Active plugins store is not available yet","0700":"Internal exception","0705":"Action not permitted without joining room","0800":"Internal exception","0801":"Permission denied","0900":"Internal exception","0904":"Could not load preset",1e3:"Internal exception",1001:"Permission denied",1004:"Could not find specified recording",1005:"Action not permitted in given recording state",1100:"Internal exception",1101:"Permission denied",1102:"Unsupported",1103:"Name cannot be empty",1104:"No device selected while calling meeting.self.setDevice",1105:"Action not permitted without joining room",1106:"Can't set currently used device",1200:"Internal exception",1201:"Permission denied",1202:"Invalid page number was requested",1203:"Invalid participant count per page was requested",1204:"No participants exists with the given UserIds",1205:"Action not permitted without joining room",1206:"Manual Subscription Mode was not ACTIVATED",1207:"Invalid view mode",1208:"Manual Subscription not enabled for organization",1209:"Broadcast message type must be a non-empty string",1300:"Internal exception",1400:"Internal exception",1402:"No existing remote requests",1403:"No peer exists with given id",1500:"Internal exception",1600:"Internal exception",1601:"Failed to get audio track",1602:"Failed to get video track",1603:"Incorrect device",1604:"Failed to change device",1605:"Failed to get audio & video track",1606:"No audio input devices are available",1607:"No video input devices are available",1608:"No audio output devices (speakers) are available",1609:"Failed to fetch list of media devices",1610:"No media track exists",1611:"Failed to unmute track",1612:"Failed to get screenshare tracks",1701:"Crypto error",1800:"Internal exception",1801:"Can't fetch transcript file",1900:"Internal exception",1901:"Permission denied.",1902:"Livestream that has not yet started, can't be stopped",2e3:"Internal exception",2001:"Permission denied",2002:"Unsupported",2003:"Stage is disabled",2004:"Method not implemented",2005:"Action not permitted without joining room",2006:"Action not permitted in current stage status",9900:"Internal exception"};Object.keys(yd).forEach(s=>{yd[s]=`{${$_[s.slice(0,2)]}} ${yd[s]}`});class R extends Error{constructor(e,r,i=void 0,n=!1){super(e);p(this,"code");this.code=r,this.name="ClientError";const o=this.code?`[ERR${this.code}]`:"[ERR]",c=this.code?yd[this.code]:"";this.message=`${o}: ${c}
11
+ ${this.message}`;try{let d=n&&!!i;r&&r.endsWith("00")&&i&&(d=!0),d&&i.error("ClientError",{error:{message:this.message,name:this.name,code:r}});const l=Rr.getContext(Rr.getMostRecentPeerId());if(l){const u=l.getValue("onError");try{u(this)}catch(h){}}typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("ClientError",{detail:this}))}catch(d){}}}function Ed(s,t,e,r){if(r instanceof R)throw r;if(r instanceof t){const i=new R(r.message,e);throw i.stack=r.stack,i}else throw r}function fg(s,t,e){if(!s.value){const i=s.get,n=s.set;return i&&(s.get=function(){try{return i.apply(this)}catch(o){Ed(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Ed(this,t,e,c)}}),s}const r=s.value;return s.value=function(...i){try{const n=r.apply(this,i);return n&&n instanceof Promise?n.catch(o=>{Ed(this,t,e,o)}):n}catch(n){Ed(this,t,e,n)}},s}function B_(s,t){return(e,r,i)=>{if(i)return fg(i,s,t);for(const n of Reflect.ownKeys(e.prototype).filter(o=>o!=="constructor")){const o=Object.getOwnPropertyDescriptor(e.prototype,n);(o.value instanceof Function||o.get instanceof Function||o.set instanceof Function)&&Object.defineProperty(e.prototype,n,fg(o,s,t))}}}const lt=s=>B_(Error,s);var Ws=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Ws||{}),G=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(G||{});typeof process!="undefined"&&(VS=process==null?void 0:process.env)!=null&&VS.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var Sg=[-2,-1,0,1,2],F_=[0,1,2,3,4];function H_(s){s=s.trim();let t="0",e="0",r="0";return s.length==4?(t=`0x${s[1]}${s[1]}`,e=`0x${s[2]}${s[2]}`,r=`0x${s[3]}${s[3]}`):s.length>6&&(t=`0x${s[1]}${s[2]}`,e=`0x${s[3]}${s[4]}`,r=`0x${s[5]}${s[6]}`),[+t,+e,+r]}var q_=(s,t,e)=>{let r,i,n;if(t==0)r=i=n=e;else{const o=(l,u,h)=>(h<0&&(h+=1),h>1&&(h-=1),h<.16666666666666666?l+(u-l)*6*h:h<.5?u:h<.6666666666666666?l+(u-l)*(.6666666666666666-h)*6:l),c=e<.5?e*(1+t):e+t-e*t,d=2*e-c;r=o(d,c,s+1/3),i=o(d,c,s),n=o(d,c,s-1/3)}return[Math.round(r*255),Math.round(i*255),Math.round(n*255)]},j_=(s,t,e)=>{s/=255,t/=255,e/=255;const r=Math.max(s,t,e),i=Math.min(s,t,e);let n,o;const c=(r+i)/2;if(r==i)n=o=0;else{const d=r-i;switch(o=c>.5?d/(2-r-i):d/(r+i),r){case s:n=(t-e)/d+(t<e?6:0);break;case t:n=(e-s)/d+2;break;case e:n=(s-t)/d+4;break}n/=6}return[n,o,c]},G_=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},vg=(s,t=Sg,e=.4)=>{const r=[],[i,n,o]=H_(s),[c,d,l]=j_(i,n,o),u=Math.round(l*100);u>70?e=.8:u>60?e=.9:u<10?e=.075:u<42&&(e=.3);const h=t.findIndex(_=>_===0);if(h===-1)throw new Error("Invalid reducer provided, it must contain atleast one zero");const m=5-h,S=h+1,y=(100-u)/m,w=u/S;for(const _ of t){let C;_<0?C=u+_*w*e:_>0?C=u+_*y*e:C=u;const[D,V,$]=q_(c,d,C/100);r.push(G_(D,V,$))}return r},Tg={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"}},W_=s=>{const[t,e,r,i,n]=vg(s,Sg);return{300:t,400:e,500:r,600:i,700:n}},J_=s=>{if(s==="#FFFFFF")return Tg.light.background;if(s==="#000000")return Tg.dark.background;const[t,e,r,i,n]=vg(s,F_);return{1e3:t,900:e,800:r,700:i,600:n}},K_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:W_("#2160FD"),background:J_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function yg(){return Nu(K_)}var z_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:yg(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"hybrid"};function Y_(){return Nu(z_)}var Q_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:yg(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate:30,simulcast:!1},screenshare:{quality:"hd",frame_rate:5}},max_video_streams:{mobile:6,desktop:6},max_screenshare_count:1,track_recording:{subscriptions:[]}},version:"2.0.0"};function Hu(){return Nu(Q_)}function X_(){Te.isElectron()&&window.electronGetDisplayMediaSource&&(navigator.mediaDevices.getDisplayMedia=async()=>{const s=await window.electronGetDisplayMediaSource({types:["window","screen"]});let t=[];if(s&&(Array.isArray(s)?t=s:t=[s]),!(t!=null&&t.length))throw new Error("Couldn't find any media source for screen share.");let e=t.find(n=>{var o;return(o=n.id)==null?void 0:o.includes("screen")});e=e!=null?e:t[0];const r={audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e.id}}};return await navigator.mediaDevices.getUserMedia(r)})}var k=(s=>(s.NEW_PRODUCER="NEW_PRODUCER",s.ROOM_NODE_CONNECTION_ERROR="ROOM_NODE_CONNECTION_ERROR",s.SOCKET_SERVICE_ROOM_JOINED="SOCKET_SERVICE_ROOM_JOINED",s.SOCKET_SERVICE_RECONNECTED="SOCKET_SERVICE_RECONNECTED",s.SOCKET_SERVICE_DISCONNECTED="SOCKET_SERVICE_DISCONNECTED",s.SOCKET_SERVICE_FAILED="SOCKET_SERVICE_FAILED",s.SOCKET_STATE_UPDATE="SOCKET_STATE_UPDATE",s.ROOM_NODE_RECONNECTED="ROOM_NODE_RECONNECTED",s.ROOM_NODE_DISCONNECTED="ROOM_NODE_DISCONNECTED",s.ROOM_NODE_FAILED="ROOM_NODE_FAILED",s.TRANSPORT_STATE_UPDATE="TRANSPORT_STATE_UPDATE",s.PRODUCER_SCORE_UPDATE="PRODUCER_SCORE_UPDATE",s.CONSUMER_SCORE_UPDATE="CONSUMER_SCORE_UPDATE",s.PRODUCER_STATUS_UPDATE="PRODUCER_STATUS_UPDATE",s.CONSUMER_STATUS_UPDATE="CONSUMER_STATUS_UPDATE",s.LOW_CONSUMER_SCORE="LOW_CONSUMER_SCORE",s.MEDIA_PERMISSION_ERROR="MEDIA_PERMISSION_ERROR",s.MEDIA_PERMISSION_UPDATE="MEDIA_PERMISSION_UPDATE",s.MESSAGE="websocket/message",s.ROOM_MESSAGE="websocket/room-message",s.PEER_JOINED_INTERNAL="peer/joined-internal",s.PEER_CLOSED="websocket/peer-closed",s.CONSUMER_CLOSED="websocket/consumer-closed",s.CONSUMER_PAUSED="websocket/consumer-paused",s.CONSUMER_RESUMED="websocket/consumer-resumed",s.PRODUCER_CLOSED="websocket/producer-closed",s.NEW_CONSUMER="websocket/new-consumer",s.PRODUCER_SCORE="websocket/producer-score",s.CONSUMER_SCORE="websocket/consumer-score",s.PRODUCER_TOGGLE="cf/producer-toggle",s.UPDATE_ACTIVE="media/update-active",s.RESET_PRODUCER_STATE="cf/reset-producer-state",s.ROOM_STATE="sockethub/room-state",s.GET_STAGE_REQUESTS="GET_STAGE_REQUESTS",s.UPDATE_STAGE_REQUESTS="UPDATE_STAGE_REQUESTS",s.KICK_PEER="KICK_PEER",s.UPDATE_PEER_STAGE_STATUS="UPDATE_PEER_STAGE_STATUS",s.JOIN_MEDIA_ROOM="JOIN_MEDIA_ROOM",s.LEAVE_MEDIA_ROOM="LEAVE_MEDIA_ROOM",s.PIP_HANGUP="PIP_HANGUP",s.E2EE_ACTIVE_PRODUCER="E2EE_ACTIVE_PRODUCER",s.E2EE_INACTIVE_PRODUCER="E2EE_INACTIVE_PRODUCER",s.E2EE_ACTIVE_CONSUMER="E2EE_ACTIVE_CONSUMER",s.E2EE_INACTIVE_CONSUMER="E2EE_INACTIVE_CONSUMER",s.SOCKET_PEERS="SOCKET_PEERS",s.UPDATE_PERMISSIONS="UPDATE_PERMISSIONS",s.MAX_SPATIAL_LAYER_CHANGE="MAX_SPATIAL_LAYER_CHANGE",s.MUTE_SELF="MUTE_SELF",s.MUTE_SELF_VIDEO="MUTE_SELF_VIDEO",s))(k||{});class kn extends dt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::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 dt.EventEmitter{constructor(e){super();p(this,"logger");this.logger=e,super.setMaxListeners(25)}emit(e,...r){return super.emit("*",e,...r),super.emit(e,...r)}on(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::maxListenersExceeded",{eventListener:{eventName:e.toString(),listenerCount:this.listenerCount(e)}}))}catch(n){}return super.on(e,r)}addListener(e,r){var i;try{const n=this.listenerCount(e);n>25&&n%25===0&&((i=this.logger)==null||i.warn("CustomEventEmitter::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)}}function Z_(s,t=2){return s.replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w\s]/g,"").trim().split(/\s+/).slice(0,t).map(i=>i.charAt(0)).join("").toUpperCase()}const Eg=1080,bg=1920,ek=(s,t,e,r,i,n)=>{let o=.5,c=.5;const d=i,l=n,u=Math.min(e/d,r/l);let h=d*u,m=l*u,S,y,w,_,C=1;return h<e&&(C=e/h),Math.abs(C-1)<1e-14&&m<r&&(C=r/m),h*=C,m*=C,w=d/(h/e),_=l/(m/r),S=(d-w)*o,y=(l-_)*c,S<0&&(S=0),y<0&&(y=0),w>d&&(w=d),_>l&&(_=l),[S,y,w,_,s,t,e,r]},zh=class extends Dt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);g(this,Xt,void 0);g(this,Ii,void 0);g(this,ht,void 0);g(this,Zt,void 0);g(this,De,{height:Eg,width:bg});g(this,gs,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,cr,void 0);g(this,St,{});g(this,Ue,void 0);g(this,$n,void 0);g(this,Bn,void 0);g(this,dr,void 0);g(this,Fn,!1);p(this,"cleanupEventListeners",()=>{a(this,Ii).unsubscribe("stageStatus",this.handlePipMediaControls),a(this,Ue).removeListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Ue).removeListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Ue).removeListener("roomLeft",()=>this.disable())});p(this,"enablePipMediaControls",()=>{this.mountAudioEvents(),this.mountVideoEvents()});p(this,"onSelfVideoUpdateListener",({videoEnabled:e})=>{this.updateMediaSession("CAMERA",e)});p(this,"onSelfAudioUpdateListener",({audioEnabled:e})=>{this.updateMediaSession("MIC",e)});p(this,"handlePipMediaControls",e=>{e==="ON_STAGE"?this.enablePipMediaControls():this.unmountEvents()});p(this,"eventCallback",e=>{e==="CAMERA"&&(a(this,Ue).videoEnabled?a(this,Ue).disableVideo():a(this,Ue).enableVideo(),this.emit("cameraToggled")),e==="MIC"&&(a(this,Ue).audioEnabled?a(this,Ue).disableAudio():a(this,Ue).enableAudio(),this.emit("micToggled")),e==="END"&&(a(this,Ii).getValue("peerSessionStore").emit(k.PIP_HANGUP),this.cleanupEventListeners(),this.emit("hangup"),this.cleanup())});p(this,"unmountEvents",()=>{navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||(navigator.mediaSession.setActionHandler("togglemicrophone",void 0),navigator.mediaSession.setActionHandler("togglecamera",void 0))});p(this,"animate",()=>{if(!this.isActive&&a(this,dr)==="active"){this.disable(!0);return}a(this,St)!==void 0&&this.paintCanvas(),a(this,cr)!==void 0&&f(this,cr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,dr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,cr)),e!==!0&&document.body.removeChild(a(this,ht)),f(this,cr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,Ii,e),f(this,dr,"idle"),f(this,Ue,r),f(this,gs,{brand:r.config.designTokens.colors.brand[500],background:r.config.designTokens.colors.background[1e3],text:r.config.designTokens.colors.text,videoBackground:r.config.designTokens.colors.videoBg,textOnBrand:r.config.designTokens.colors.textOnBrand}),i&&this.setupIcon("pin",i),n&&this.setupIcon("handRaise",n)}static async _init(e,r){let i,n;try{i=await Td(O_),n=await Td(D_)}catch(o){}return new zh(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,Bn,r);break;case"pin":f(this,$n,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,Bn,await Td(r));break;case"pin":f(this,$n,await Td(r));break}}constructImage(e){const r=new Image,i=new Blob([e],{type:"image/svg+xml"}),n=window.URL.createObjectURL(i);return new Promise(o=>{r.onload=()=>{o(r),window.URL.revokeObjectURL(n)},r.src=n})}createVideoContainer(){f(this,ht,document.createElement("div")),a(this,ht).style.width="0.1px",a(this,ht).style.height="0.1px",a(this,ht).style.overflow="hidden",a(this,ht).style.position="absolute",a(this,ht).style.bottom="0",a(this,ht).style.right="0",a(this,ht).style.opacity="0",a(this,ht).appendChild(a(this,Zt))}setupEventListeners(){a(this,Ii).subscribe("stageStatus",this.handlePipMediaControls),a(this,Ue).addListener("videoUpdate",this.onSelfVideoUpdateListener),a(this,Ue).addListener("audioUpdate",this.onSelfAudioUpdateListener),a(this,Ue).addListener("roomLeft",()=>this.disable())}createCanvas(){const e=document.createElement("canvas");e.height=a(this,De).height,e.width=a(this,De).width,f(this,Xt,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||a(this,Ue).permissions.canProduceAudio&&navigator.mediaSession.setActionHandler("togglemicrophone",()=>{this.eventCallback("MIC")})}mountVideoEvents(){navigator.mediaSession===void 0||navigator.mediaSession.setCameraActive===void 0||a(this,Ue).permissions.canProduceVideo&&navigator.mediaSession.setActionHandler("togglecamera",()=>{this.eventCallback("CAMERA")})}getSources(){const r=Object.values(a(this,St)).reduce((i,n)=>(i[n.pinned?"pinned":"regular"].push(n),i),{pinned:[],regular:[]});return[...r.pinned,...r.regular]}drawEmptyTile(e,r,i,n){if(a(this,Xt)===void 0)return;const o=a(this,Xt).getContext("2d"),c=a(this,Xt).width,d=0,l=0,u=r-d*2,h=i-d*2,m=Math.floor(c/u),S=Math.floor(e/m),w=e%m*(u+d)+d,_=S*(h+d)+d,{displayText:C,image:D}=n!=null?n:{};o.fillStyle=C||D?a(this,gs).videoBackground:a(this,gs).background,o.strokeStyle=a(this,gs).brand,o.beginPath(),o.moveTo(w+l,_),o.arcTo(w+u,_,w+u,_+l,l),o.arcTo(w+u,_+h,w+u-l,_+h,l),o.arcTo(w,_+h,w,_+h-l,l),o.arcTo(w,_,w+l,_,l),o.closePath(),o.fill(),o.stroke();const V=u/6,$=u/2+w,H=h/2+_;o.save(),(C||D)&&(o.beginPath(),o.arc($,H,V,0,Math.PI*2),o.fillStyle=a(this,gs).brand,o.fill(),D?(o.clip(),o.drawImage(D,$-V,H-V,V*2,V*2),o.restore()):C&&(o.fillStyle=a(this,gs).textOnBrand,o.font=`${V/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(C,$,H)),this.drawIcons(n,w,_,Math.max(u,h)))}drawIcons(e,r,i,n){const o=Math.min(Math.max(n*.15,100),200),c=o*.2,d=o*.2;let l=r+c;const u=i+c,h=m=>{const S=a(this,Xt).getContext("2d");S.save(),S.fillStyle=a(this,gs).background,S.beginPath(),S.moveTo(l+d,u),S.arcTo(l+o,u,l+o,u+d,d),S.arcTo(l+o,u+o,l+o-d,u+o,d),S.arcTo(l,u+o,l,u+o-d,d),S.arcTo(l,u,l+d,u,d),S.closePath(),S.fill(),typeof m=="string"?(S.font=`${o/1.5}px sans-serif`,S.fillStyle=a(this,gs).text,S.textAlign="center",S.textBaseline="top",S.fillText(m,o/2+l,u+c)):S.drawImage(m,l+c,u+c,o-c*2,o-c*2),l+=o+c,S.restore()};e.pinned&&h(a(this,$n)),e.handRaised&&h(a(this,Bn)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,Xt)===void 0)return;const n=a(this,Xt).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,De).height-5;){let h=0;for(;h<a(this,De).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const m=o[d].element,[S,y,w,_,C,D,V,$]=ek(h,c,e,r,m.videoWidth,m.videoHeight);((u=m==null?void 0:m.classList)==null?void 0:u.contains("mirror"))?(n.save(),n.scale(-1,1),n.drawImage(m,S,y,w,_,-1*C,D,-1*V,$),n.restore()):n.drawImage(m,S,y,w,_,C,D,V,$),this.drawIcons(o[d],C,D,Math.max(V,$))}else this.drawEmptyTile(d,e,r,o[d]);d+=1,h+=e}c+=r}}calcGridElemSize(e){switch(e){case 0:case 1:return[a(this,De).width,a(this,De).height];case 2:return[Math.floor(a(this,De).width/2),a(this,De).height];case 3:case 4:return[Math.floor(a(this,De).width/2),Math.floor(a(this,De).height/2)];case 5:case 6:return[Math.floor(a(this,De).width/3),Math.floor(a(this,De).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,De).width/3),Math.floor(a(this,De).height/3)];default:return[Math.floor(a(this,De).width/3),Math.floor(a(this,De).height/2)]}}paintCanvas(){let e=this.getSources().length;e!==1&&(e=e%2>0?e+1:e);const[r,i]=this.calcGridElemSize(e);this.drawTile(r,i,e)}isSupported(){var e;return!!window.chrome&&document.pictureInPictureEnabled&&((e=a(this,Ue).config)==null?void 0:e.viewType)!=="LIVESTREAM"}get isActive(){return document.pictureInPictureElement!==null}cleanup(){if(f(this,Fn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,ht))try{document.body.removeChild(a(this,ht))}catch(e){}this.removeAllSources(),f(this,Xt,void 0),f(this,Zt,void 0),f(this,cr,void 0)}init({height:e,width:r}={}){if(!this.isSupported())throw this.logger.error("Pip.unsupported"),new Error("Picture-in-picture is not available in this environment");if(a(this,Fn))return;f(this,Fn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,De,{height:e!=null?e:Eg,width:r!=null?r:bg}),i.height=a(this,De).height,i.width=a(this,De).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,Xt).captureStream(24),f(this,Zt,i),a(this,Zt).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,Zt).onleavepictureinpicture=()=>{this.emit("pipEnded")}}catch(n){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){a(this,St)[e]!==void 0&&(a(this,St)[e].enabled=!0)}disableSource(e){a(this,St)[e]!==void 0&&(a(this,St)[e].enabled=!1)}async generateAvatar(e,r){if(!r)return;const i=new Image;try{const n=await(await fetch(r)).blob(),o=window.URL.createObjectURL(n);i.onload=()=>{this.updateSource(e,{image:i}),window.URL.revokeObjectURL(o)},i.src=o}catch(n){this.logger.error("Pip::GenerateAvatar",{error:n})}}addSource(e,r,i,n=!1,o=void 0,c=void 0,d=!1){this.logger.debug("Pip::AddSource",{pip:{id:e,handRaised:d}}),a(this,St)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?Z_(o):void 0,imageUrl:c,handRaised:d},c&&this.generateAvatar(e,c)}updateSource(e,r){this.logger.info("Pip::UpdateSource",{pip:{id:e,handRaised:r.handRaised,reaction:r.reaction}});const i=a(this,St)[e];i&&(a(this,St)[e]={...i,...r})}removeSource(e){delete a(this,St)[e]}removePinnedSource(){Object.values(a(this,St)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,St,{})}enable(){f(this,dr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,Ue).videoEnabled),this.updateMediaSession("MIC",a(this,Ue).audioEnabled),document.body.appendChild(a(this,ht)),f(this,cr,requestAnimationFrame(()=>this.animate())),a(this,Zt).onloadedmetadata=()=>{a(this,Zt).requestPictureInPicture().then(()=>{f(this,dr,"active")})},a(this,Zt).readyState===4&&a(this,Zt).requestPictureInPicture().then(()=>{f(this,dr,"active")})}};let qu=zh;Xt=new WeakMap,Ii=new WeakMap,ht=new WeakMap,Zt=new WeakMap,De=new WeakMap,gs=new WeakMap,cr=new WeakMap,St=new WeakMap,Ue=new WeakMap,$n=new WeakMap,Bn=new WeakMap,dr=new WeakMap,Fn=new WeakMap;function ju(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function tk(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let Js="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),bd=[];for(let s=0;s<Js.length;s++)bd[Js[s].charCodeAt(0)]=s;bd["-".charCodeAt(0)]=Js.indexOf("+"),bd["_".charCodeAt(0)]=Js.indexOf("/");function sk(s){let t=s.length*3/4;s[s.length-2]=="="?t-=2:s[s.length-1]=="="&&(t-=1);let e=new Uint8Array(t),r=0,i=0,n,o=0;for(let c=0;c<s.length;c++){if(n=bd[s.charCodeAt(c)],n===void 0)switch(s[c]){case"=":i=0;case`
12
+ `:case"\r":case" ":case" ":continue;default:throw Error("invalid base64 string.")}switch(i){case 0:o=n,i=1;break;case 1:e[r++]=o<<2|(n&48)>>4,o=n,i=2;break;case 2:e[r++]=(o&15)<<4|(n&60)>>2,o=n,i=3;break;case 3:e[r++]=(o&3)<<6|n,i=0;break}}if(i==1)throw Error("invalid base64 string.");return e.subarray(0,r)}function rk(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=Js[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=Js[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=Js[i|r>>6],t+=Js[r&63],e=0;break}return e&&(t+=Js[i],t+="=",e==1&&(t+="=")),t}var wd;(function(s){s.symbol=Symbol.for("protobuf-ts/unknown"),s.onRead=(e,r,i,n,o)=>{(t(r)?r[s.symbol]:r[s.symbol]=[]).push({no:i,wireType:n,data:o})},s.onWrite=(e,r,i)=>{for(let{no:n,wireType:o,data:c}of s.list(r))i.tag(n,o).raw(c)},s.list=(e,r)=>{if(t(e)){let i=e[s.symbol];return r?i.filter(n=>n.no==r):i}return[]},s.last=(e,r)=>s.list(e,r).slice(-1)[0];const t=e=>e&&Array.isArray(e[s.symbol])})(wd||(wd={}));var xe;(function(s){s[s.Varint=0]="Varint",s[s.Bit64=1]="Bit64",s[s.LengthDelimited=2]="LengthDelimited",s[s.StartGroup=3]="StartGroup",s[s.EndGroup=4]="EndGroup",s[s.Bit32=5]="Bit32"})(xe||(xe={}));function ik(){let s=0,t=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(s|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}let e=this.buf[this.pos++];if(s|=(e&15)<<28,t=(e&112)>>4,!(e&128))return this.assertBounds(),[s,t];for(let r=3;r<=31;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,!(i&128))return this.assertBounds(),[s,t]}throw new Error("invalid varint")}function Gu(s,t,e){for(let n=0;n<28;n=n+7){const o=s>>>n,c=!(!(o>>>7)&&t==0),d=(c?o|128:o)&255;if(e.push(d),!c)return}const r=s>>>28&15|(t&7)<<4,i=!!(t>>3);if(e.push((i?r|128:r)&255),!!i){for(let n=3;n<31;n=n+7){const o=t>>>n,c=!!(o>>>7),d=(c?o|128:o)&255;if(e.push(d),!c)return}e.push(t>>>31&1)}}const Pd=(1<<16)*(1<<16);function wg(s){let t=s[0]=="-";t&&(s=s.slice(1));const e=1e6;let r=0,i=0;function n(o,c){const d=Number(s.slice(o,c));i*=e,r=r*e+d,r>=Pd&&(i=i+(r/Pd|0),r=r%Pd)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function Wu(s,t){if(t>>>0<=2097151)return""+(Pd*t+(s>>>0));let e=s&16777215,r=(s>>>24|t<<8)>>>0&16777215,i=t>>16&65535,n=e+r*6777216+i*6710656,o=r+i*8147497,c=i*2,d=1e7;n>=d&&(o+=Math.floor(n/d),n%=d),o>=d&&(c+=Math.floor(o/d),o%=d);function l(u,h){let m=u?String(u):"";return h?"0000000".slice(m.length)+m:m}return l(c,0)+l(o,c)+l(n,1)}function Pg(s,t){if(s>=0){for(;s>127;)t.push(s&127|128),s=s>>>7;t.push(s)}else{for(let e=0;e<9;e++)t.push(s&127|128),s=s>>7;t.push(1)}}function nk(){let s=this.buf[this.pos++],t=s&127;if(!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<7,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<14,!(s&128))return this.assertBounds(),t;if(s=this.buf[this.pos++],t|=(s&127)<<21,!(s&128))return this.assertBounds(),t;s=this.buf[this.pos++],t|=(s&15)<<28;for(let e=5;s&128&&e<10;e++)s=this.buf[this.pos++];if(s&128)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let pe;function ak(){const s=new DataView(new ArrayBuffer(8));pe=globalThis.BigInt!==void 0&&typeof s.getBigInt64=="function"&&typeof s.getBigUint64=="function"&&typeof s.setBigInt64=="function"&&typeof s.setBigUint64=="function"?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:s}:void 0}ak();function _g(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const kg=/^-?[0-9]+$/,_d=4294967296,kd=2147483648;class Cg{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*_d+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class ut extends Cg{static from(t){if(pe)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=pe.C(t);case"number":if(t===0)return this.ZERO;t=pe.C(t);case"bigint":if(!t)return this.ZERO;if(t<pe.UMIN)throw new Error("signed value for ulong");if(t>pe.UMAX)throw new Error("ulong too large");return pe.V.setBigUint64(0,t,!0),new ut(pe.V.getInt32(0,!0),pe.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!kg.test(t))throw new Error("string is no integer");let[e,r,i]=wg(t);if(e)throw new Error("signed value for ulong");return new ut(r,i);case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");if(t<0)throw new Error("signed value for ulong");return new ut(t,t/_d)}throw new Error("unknown value "+typeof t)}toString(){return pe?this.toBigInt().toString():Wu(this.lo,this.hi)}toBigInt(){return _g(pe),pe.V.setInt32(0,this.lo,!0),pe.V.setInt32(4,this.hi,!0),pe.V.getBigUint64(0,!0)}}ut.ZERO=new ut(0,0);class fe extends Cg{static from(t){if(pe)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=pe.C(t);case"number":if(t===0)return this.ZERO;t=pe.C(t);case"bigint":if(!t)return this.ZERO;if(t<pe.MIN)throw new Error("signed long too small");if(t>pe.MAX)throw new Error("signed long too large");return pe.V.setBigInt64(0,t,!0),new fe(pe.V.getInt32(0,!0),pe.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!kg.test(t))throw new Error("string is no integer");let[e,r,i]=wg(t);if(e){if(i>kd||i==kd&&r!=0)throw new Error("signed long too small")}else if(i>=kd)throw new Error("signed long too large");let n=new fe(r,i);return e?n.negate():n;case"number":if(t==0)return this.ZERO;if(!Number.isSafeInteger(t))throw new Error("number is no integer");return t>0?new fe(t,t/_d):new fe(-t,-t/_d).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&kd)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new fe(e,t)}toString(){if(pe)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+Wu(t.lo,t.hi)}return Wu(this.lo,this.hi)}toBigInt(){return _g(pe),pe.V.setInt32(0,this.lo,!0),pe.V.setInt32(4,this.hi,!0),pe.V.getBigInt64(0,!0)}}fe.ZERO=new fe(0,0);const Rg={readUnknownField:!0,readerFactory:s=>new ck(s)};function ok(s){return s?Object.assign(Object.assign({},Rg),s):Rg}class ck{constructor(t,e){this.varint64=ik,this.uint32=nk,this.buf=t,this.len=t.length,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.textDecoder=e!=null?e:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let t=this.uint32(),e=t>>>3,r=t&7;if(e<=0||r<0||r>5)throw new Error("illegal tag: field no "+e+" wire type "+r);return[e,r]}skip(t){let e=this.pos;switch(t){case xe.Varint:for(;this.buf[this.pos++]&128;);break;case xe.Bit64:this.pos+=4;case xe.Bit32:this.pos+=4;break;case xe.LengthDelimited:let r=this.uint32();this.pos+=r;break;case xe.StartGroup:let i;for(;(i=this.tag()[1])!==xe.EndGroup;)this.skip(i);break;default:throw new Error("cant skip wire type "+t)}return this.assertBounds(),this.buf.subarray(e,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let t=this.uint32();return t>>>1^-(t&1)}int64(){return new fe(...this.varint64())}uint64(){return new ut(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new fe(t,e)}bool(){let[t,e]=this.varint64();return t!==0||e!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new ut(this.sfixed32(),this.sfixed32())}sfixed64(){return new fe(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 t=this.uint32(),e=this.pos;return this.pos+=t,this.assertBounds(),this.buf.subarray(e,e+t)}string(){return this.textDecoder.decode(this.bytes())}}function re(s,t){if(!s)throw new Error(t)}const dk=34028234663852886e22,lk=-34028234663852886e22,uk=4294967295,hk=2147483647,pk=-2147483648;function Za(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>hk||s<pk)throw new Error("invalid int 32: "+s)}function Cd(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>uk||s<0)throw new Error("invalid uint 32: "+s)}function Ju(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>dk||s<lk))throw new Error("invalid float 32: "+s)}const Ig={writeUnknownFields:!0,writerFactory:()=>new gk};function mk(s){return s?Object.assign(Object.assign({},Ig),s):Ig}class gk{constructor(t){this.stack=[],this.textEncoder=t!=null?t:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let t=0;for(let i=0;i<this.chunks.length;i++)t+=this.chunks[i].length;let e=new Uint8Array(t),r=0;for(let i=0;i<this.chunks.length;i++)e.set(this.chunks[i],r),r+=this.chunks[i].length;return this.chunks=[],e}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let t=this.finish(),e=this.stack.pop();if(!e)throw new Error("invalid state, fork stack empty");return this.chunks=e.chunks,this.buf=e.buf,this.uint32(t.byteLength),this.raw(t)}tag(t,e){return this.uint32((t<<3|e)>>>0)}raw(t){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(t),this}uint32(t){for(Cd(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return Za(t),Pg(t,this.buf),this}bool(t){return this.buf.push(t?1:0),this}bytes(t){return this.uint32(t.byteLength),this.raw(t)}string(t){let e=this.textEncoder.encode(t);return this.uint32(e.byteLength),this.raw(e)}float(t){Ju(t);let e=new Uint8Array(4);return new DataView(e.buffer).setFloat32(0,t,!0),this.raw(e)}double(t){let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t,!0),this.raw(e)}fixed32(t){Cd(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){Za(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return Za(t),t=(t<<1^t>>31)>>>0,Pg(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=fe.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}fixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=ut.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=fe.from(t);return Gu(e.lo,e.hi,this.buf),this}sint64(t){let e=fe.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return Gu(i,n,this.buf),this}uint64(t){let e=ut.from(t);return Gu(e.lo,e.hi,this.buf),this}}const Ag={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Mg={ignoreUnknownFields:!1};function fk(s){return s?Object.assign(Object.assign({},Mg),s):Mg}function Sk(s){return s?Object.assign(Object.assign({},Ag),s):Ag}const Og=Symbol.for("protobuf-ts/message-type");function Dg(s){let t=!1;const e=[];for(let r=0;r<s.length;r++){let i=s.charAt(r);i=="_"?t=!0:/\d/.test(i)?(e.push(i),t=!0):t?(e.push(i.toUpperCase()),t=!1):r==0?e.push(i.toLowerCase()):e.push(i)}return e.join("")}var O;(function(s){s[s.DOUBLE=1]="DOUBLE",s[s.FLOAT=2]="FLOAT",s[s.INT64=3]="INT64",s[s.UINT64=4]="UINT64",s[s.INT32=5]="INT32",s[s.FIXED64=6]="FIXED64",s[s.FIXED32=7]="FIXED32",s[s.BOOL=8]="BOOL",s[s.STRING=9]="STRING",s[s.BYTES=12]="BYTES",s[s.UINT32=13]="UINT32",s[s.SFIXED32=15]="SFIXED32",s[s.SFIXED64=16]="SFIXED64",s[s.SINT32=17]="SINT32",s[s.SINT64=18]="SINT64"})(O||(O={}));var Rs;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(Rs||(Rs={}));var Rd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(Rd||(Rd={}));function vk(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Dg(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Dg(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:Rd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function Tk(s){if(typeof s!="object"||s===null||!s.hasOwnProperty("oneofKind"))return!1;switch(typeof s.oneofKind){case"string":return s[s.oneofKind]===void 0?!1:Object.keys(s).length==2;case"undefined":return Object.keys(s).length==1;default:return!1}}class yk{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}prepare(){if(this.data)return;const t=[],e=[],r=[];for(let i of this.fields)if(i.oneof)r.includes(i.oneof)||(r.push(i.oneof),t.push(i.oneof),e.push(i.oneof));else switch(e.push(i.localName),i.kind){case"scalar":case"enum":(!i.opt||i.repeat)&&t.push(i.localName);break;case"message":i.repeat&&t.push(i.localName);break;case"map":t.push(i.localName);break}this.data={req:t,known:e,oneofs:Object.values(r)}}is(t,e,r=!1){if(e<0)return!0;if(t==null||typeof t!="object")return!1;this.prepare();let i=Object.keys(t),n=this.data;if(i.length<n.req.length||n.req.some(o=>!i.includes(o))||!r&&i.some(o=>!n.known.includes(o)))return!1;if(e<1)return!0;for(const o of n.oneofs){const c=t[o];if(!Tk(c))return!1;if(c.oneofKind===void 0)continue;const d=this.fields.find(l=>l.localName===c.oneofKind);if(!d||!this.field(c[c.oneofKind],d,r,e))return!1}for(const o of this.fields)if(o.oneof===void 0&&!this.field(t[o.localName],o,r,e))return!1;return!0}field(t,e,r,i){let n=e.repeat;switch(e.kind){case"scalar":return t===void 0?e.opt:n?this.scalars(t,e.T,i,e.L):this.scalar(t,e.T,e.L);case"enum":return t===void 0?e.opt:n?this.scalars(t,O.INT32,i):this.scalar(t,O.INT32);case"message":return t===void 0?!0:n?this.messages(t,e.T(),r,i):this.message(t,e.T(),r,i);case"map":if(typeof t!="object"||t===null)return!1;if(i<2)return!0;if(!this.mapKeys(t,e.K,i))return!1;switch(e.V.kind){case"scalar":return this.scalars(Object.values(t),e.V.T,i,e.V.L);case"enum":return this.scalars(Object.values(t),O.INT32,i);case"message":return this.messages(Object.values(t),e.V.T(),r,i)}break}return!0}message(t,e,r,i){return r?e.isAssignable(t,i):e.is(t,i)}messages(t,e,r,i){if(!Array.isArray(t))return!1;if(i<2)return!0;if(r){for(let n=0;n<t.length&&n<i;n++)if(!e.isAssignable(t[n],i-1))return!1}else for(let n=0;n<t.length&&n<i;n++)if(!e.is(t[n],i-1))return!1;return!0}scalar(t,e,r){let i=typeof t;switch(e){case O.UINT64:case O.FIXED64:case O.INT64:case O.SFIXED64:case O.SINT64:switch(r){case Rs.BIGINT:return i=="bigint";case Rs.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case O.BOOL:return i=="boolean";case O.STRING:return i=="string";case O.BYTES:return t instanceof Uint8Array;case O.DOUBLE:case O.FLOAT:return i=="number"&&!isNaN(t);default:return i=="number"&&Number.isInteger(t)}}scalars(t,e,r,i){if(!Array.isArray(t))return!1;if(r<2)return!0;if(Array.isArray(t)){for(let n=0;n<t.length&&n<r;n++)if(!this.scalar(t[n],e,i))return!1}return!0}mapKeys(t,e,r){let i=Object.keys(t);switch(e){case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case O.BOOL:return this.scalars(i.slice(0,r).map(n=>n=="true"?!0:n=="false"?!1:n),e,r);default:return this.scalars(i,e,r,Rs.STRING)}}}function ls(s,t){switch(t){case Rs.BIGINT:return s.toBigInt();case Rs.NUMBER:return s.toNumber();default:return s.toString()}}class Ek{constructor(t){this.info=t}prepare(){var t;if(this.fMap===void 0){this.fMap={};const e=(t=this.info.fields)!==null&&t!==void 0?t:[];for(const r of e)this.fMap[r.name]=r,this.fMap[r.jsonName]=r,this.fMap[r.localName]=r}}assert(t,e,r){if(!t){let i=ju(r);throw(i=="number"||i=="boolean")&&(i=r.toString()),new Error(`Cannot parse JSON ${i} for ${this.info.typeName}#${e}`)}}read(t,e,r){this.prepare();const i=[];for(const[n,o]of Object.entries(t)){const c=this.fMap[n];if(!c){if(!r.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${n}`);continue}const d=c.localName;let l;if(c.oneof){if(o===null&&(c.kind!=="enum"||c.T()[0]!=="google.protobuf.NullValue"))continue;if(i.includes(c.oneof))throw new Error(`Multiple members of the oneof group "${c.oneof}" of ${this.info.typeName} are present in JSON.`);i.push(c.oneof),l=e[c.oneof]={oneofKind:d}}else l=e;if(c.kind=="map"){if(o===null)continue;this.assert(tk(o),c.name,o);const u=l[d];for(const[h,m]of Object.entries(o)){this.assert(m!==null,c.name+" map value",null);let S;switch(c.V.kind){case"message":S=c.V.T().internalJsonRead(m,r);break;case"enum":if(S=this.enum(c.V.T(),m,c.name,r.ignoreUnknownFields),S===!1)continue;break;case"scalar":S=this.scalar(m,c.V.T,c.V.L,c.name);break}this.assert(S!==void 0,c.name+" map value",m);let y=h;c.K==O.BOOL&&(y=y=="true"?!0:y=="false"?!1:y),y=this.scalar(y,c.K,Rs.STRING,c.name).toString(),u[y]=S}}else if(c.repeat){if(o===null)continue;this.assert(Array.isArray(o),c.name,o);const u=l[d];for(const h of o){this.assert(h!==null,c.name,null);let m;switch(c.kind){case"message":m=c.T().internalJsonRead(h,r);break;case"enum":if(m=this.enum(c.T(),h,c.name,r.ignoreUnknownFields),m===!1)continue;break;case"scalar":m=this.scalar(h,c.T,c.L,c.name);break}this.assert(m!==void 0,c.name,o),u.push(m)}}else switch(c.kind){case"message":if(o===null&&c.T().typeName!="google.protobuf.Value"){this.assert(c.oneof===void 0,c.name+" (oneof member)",null);continue}l[d]=c.T().internalJsonRead(o,r,l[d]);break;case"enum":if(o===null)continue;let u=this.enum(c.T(),o,c.name,r.ignoreUnknownFields);if(u===!1)continue;l[d]=u;break;case"scalar":if(o===null)continue;l[d]=this.scalar(o,c.T,c.L,c.name);break}}}enum(t,e,r,i){if(t[0]=="google.protobuf.NullValue"&&re(e===null||e==="NULL_VALUE",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} only accepts null.`),e===null)return 0;switch(typeof e){case"number":return re(Number.isInteger(e),`Unable to parse field ${this.info.typeName}#${r}, enum can only be integral number, got ${e}.`),e;case"string":let n=e;t[2]&&e.substring(0,t[2].length)===t[2]&&(n=e.substring(t[2].length));let o=t[1][n];return typeof o=="undefined"&&i?!1:(re(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}re(!1,`Unable to parse field ${this.info.typeName}#${r}, cannot parse enum value from ${typeof e}".`)}scalar(t,e,r,i){let n;try{switch(e){case O.DOUBLE:case O.FLOAT:if(t===null)return 0;if(t==="NaN")return Number.NaN;if(t==="Infinity")return Number.POSITIVE_INFINITY;if(t==="-Infinity")return Number.NEGATIVE_INFINITY;if(t===""){n="empty string";break}if(typeof t=="string"&&t.trim().length!==t.length){n="extra whitespace";break}if(typeof t!="string"&&typeof t!="number")break;let o=Number(t);if(Number.isNaN(o)){n="not a number";break}if(!Number.isFinite(o)){n="too large or small";break}return e==O.FLOAT&&Ju(o),o;case O.INT32:case O.FIXED32:case O.SFIXED32:case O.SINT32:case O.UINT32:if(t===null)return 0;let c;if(typeof t=="number"?c=t:t===""?n="empty string":typeof t=="string"&&(t.trim().length!==t.length?n="extra whitespace":c=Number(t)),c===void 0)break;return e==O.UINT32?Cd(c):Za(c),c;case O.INT64:case O.SFIXED64:case O.SINT64:if(t===null)return ls(fe.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ls(fe.from(t),r);case O.FIXED64:case O.UINT64:if(t===null)return ls(ut.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ls(ut.from(t),r);case O.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case O.STRING:if(t===null)return"";if(typeof t!="string"){n="extra whitespace";break}try{encodeURIComponent(t)}catch(d){d="invalid UTF8";break}return t;case O.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return sk(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class bk{constructor(t){var e;this.fields=(e=t.fields)!==null&&e!==void 0?e:[]}write(t,e){const r={},i=t;for(const n of this.fields){if(!n.oneof){let l=this.field(n,i[n.localName],e);l!==void 0&&(r[e.useProtoFieldName?n.name:n.jsonName]=l);continue}const o=i[n.oneof];if(o.oneofKind!==n.localName)continue;const c=n.kind=="scalar"||n.kind=="enum"?Object.assign(Object.assign({},e),{emitDefaultValues:!0}):e;let d=this.field(n,o[n.localName],c);re(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){re(typeof e=="object"&&e!==null);const n={};switch(t.V.kind){case"scalar":for(const[d,l]of Object.entries(e)){const u=this.scalar(t.V.T,l,t.name,!1,!0);re(u!==void 0),n[d.toString()]=u}break;case"message":const o=t.V.T();for(const[d,l]of Object.entries(e)){const u=this.message(o,l,t.name,r);re(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){re(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);re(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){re(Array.isArray(e));const n=[];switch(t.kind){case"scalar":for(let d=0;d<e.length;d++){const l=this.scalar(t.T,e[d],t.name,t.opt,!0);re(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){re(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);re(l!==void 0),n.push(l)}break;case"message":const c=t.T();for(let d=0;d<e.length;d++){const l=this.message(c,e[d],t.name,r);re(l!==void 0),n.push(l)}break}(r.emitDefaultValues||n.length>0||r.emitDefaultValues)&&(i=n)}else switch(t.kind){case"scalar":i=this.scalar(t.T,e,t.name,t.opt,r.emitDefaultValues);break;case"enum":i=this.enum(t.T(),e,t.name,t.opt,r.emitDefaultValues,r.enumAsInteger);break;case"message":i=this.message(t.T(),e,t.name,r);break}return i}enum(t,e,r,i,n,o){if(t[0]=="google.protobuf.NullValue")return!n&&!i?void 0:null;if(e===void 0){re(i);return}if(!(e===0&&!n&&!i))return re(typeof e=="number"),re(Number.isInteger(e)),o||!t[1].hasOwnProperty(e)?e:t[2]?t[2]+t[1][e]:t[1][e]}message(t,e,r,i){return e===void 0?i.emitDefaultValues?null:void 0:t.internalJsonWrite(e,i)}scalar(t,e,r,i,n){if(e===void 0){re(i);return}const o=n||i;switch(t){case O.INT32:case O.SFIXED32:case O.SINT32:return e===0?o?0:void 0:(Za(e),e);case O.FIXED32:case O.UINT32:return e===0?o?0:void 0:(Cd(e),e);case O.FLOAT:Ju(e);case O.DOUBLE:return e===0?o?0:void 0:(re(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case O.STRING:return e===""?o?"":void 0:(re(typeof e=="string"),e);case O.BOOL:return e===!1?o?!1:void 0:(re(typeof e=="boolean"),e);case O.UINT64:case O.FIXED64:re(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=ut.from(e);return c.isZero()&&!o?void 0:c.toString();case O.INT64:case O.SFIXED64:case O.SINT64:re(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=fe.from(e);return d.isZero()&&!o?void 0:d.toString();case O.BYTES:return re(e instanceof Uint8Array),e.byteLength?rk(e):o?"":void 0}}}function Ku(s,t=Rs.STRING){switch(s){case O.BOOL:return!1;case O.UINT64:case O.FIXED64:return ls(ut.ZERO,t);case O.INT64:case O.SFIXED64:case O.SINT64:return ls(fe.ZERO,t);case O.DOUBLE:case O.FLOAT:return 0;case O.BYTES:return new Uint8Array(0);case O.STRING:return"";default:return 0}}class wk{constructor(t){this.info=t}prepare(){var t;if(!this.fieldNoToField){const e=(t=this.info.fields)!==null&&t!==void 0?t:[];this.fieldNoToField=new Map(e.map(r=>[r.no,r]))}}read(t,e,r,i){this.prepare();const n=i===void 0?t.len:t.pos+i;for(;t.pos<n;){const[o,c]=t.tag(),d=this.fieldNoToField.get(o);if(!d){let m=r.readUnknownField;if(m=="throw")throw new Error(`Unknown field ${o} (wire type ${c}) for ${this.info.typeName}`);let S=t.skip(c);m!==!1&&(m===!0?wd.onRead:m)(this.info.typeName,e,o,c,S);continue}let l=e,u=d.repeat,h=d.localName;switch(d.oneof&&(l=l[d.oneof],l.oneofKind!==h&&(l=e[d.oneof]={oneofKind:h})),d.kind){case"scalar":case"enum":let m=d.kind=="enum"?O.INT32:d.T,S=d.kind=="scalar"?d.L:void 0;if(u){let _=l[h];if(c==xe.LengthDelimited&&m!=O.STRING&&m!=O.BYTES){let C=t.uint32()+t.pos;for(;t.pos<C;)_.push(this.scalar(t,m,S))}else _.push(this.scalar(t,m,S))}else l[h]=this.scalar(t,m,S);break;case"message":if(u){let _=l[h],C=d.T().internalBinaryRead(t,t.uint32(),r);_.push(C)}else l[h]=d.T().internalBinaryRead(t,t.uint32(),r,l[h]);break;case"map":let[y,w]=this.mapEntry(d,t,r);l[h][y]=w;break}}}mapEntry(t,e,r){let i=e.uint32(),n=e.pos+i,o,c;for(;e.pos<n;){let[d,l]=e.tag();switch(d){case 1:t.K==O.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,Rs.STRING);break;case 2:switch(t.V.kind){case"scalar":c=this.scalar(e,t.V.T,t.V.L);break;case"enum":c=e.int32();break;case"message":c=t.V.T().internalBinaryRead(e,e.uint32(),r);break}break;default:throw new Error(`Unknown field ${d} (wire type ${l}) in map entry for ${this.info.typeName}#${t.name}`)}}if(o===void 0){let d=Ku(t.K);o=t.K==O.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=Ku(t.V.T,t.V.L);break;case"enum":c=0;break;case"message":c=t.V.T().create();break}return[o,c]}scalar(t,e,r){switch(e){case O.INT32:return t.int32();case O.STRING:return t.string();case O.BOOL:return t.bool();case O.DOUBLE:return t.double();case O.FLOAT:return t.float();case O.INT64:return ls(t.int64(),r);case O.UINT64:return ls(t.uint64(),r);case O.FIXED64:return ls(t.fixed64(),r);case O.FIXED32:return t.fixed32();case O.BYTES:return t.bytes();case O.UINT32:return t.uint32();case O.SFIXED32:return t.sfixed32();case O.SFIXED64:return ls(t.sfixed64(),r);case O.SINT32:return t.sint32();case O.SINT64:return ls(t.sint64(),r)}}}class Pk{constructor(t){this.info=t}prepare(){if(!this.fields){const t=this.info.fields?this.info.fields.concat():[];this.fields=t.sort((e,r)=>e.no-r.no)}}write(t,e,r){this.prepare();for(const n of this.fields){let o,c,d=n.repeat,l=n.localName;if(n.oneof){const u=t[n.oneof];if(u.oneofKind!==l)continue;o=u[l],c=!0}else o=t[l],c=!1;switch(n.kind){case"scalar":case"enum":let u=n.kind=="enum"?O.INT32:n.T;if(d)if(re(Array.isArray(o)),d==Rd.PACKED)this.packed(e,u,n.no,o);else for(const h of o)this.scalar(e,u,n.no,h,!0);else o===void 0?re(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){re(Array.isArray(o));for(const h of o)this.message(e,r,n.T(),n.no,h)}else this.message(e,r,n.T(),n.no,o);break;case"map":re(typeof o=="object"&&o!==null);for(const[h,m]of Object.entries(o))this.mapEntry(e,r,n,h,m);break}}let i=r.writeUnknownFields;i!==!1&&(i===!0?wd.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,xe.LengthDelimited),t.fork();let o=i;switch(r.K){case O.INT32:case O.FIXED32:case O.UINT32:case O.SFIXED32:case O.SINT32:o=Number.parseInt(i);break;case O.BOOL:re(i=="true"||i=="false"),o=i=="true";break}switch(this.scalar(t,r.K,1,o,!0),r.V.kind){case"scalar":this.scalar(t,r.V.T,2,n,!0);break;case"enum":this.scalar(t,O.INT32,2,n,!0);break;case"message":this.message(t,e,r.V.T(),2,n);break}t.join()}message(t,e,r,i,n){n!==void 0&&(r.internalBinaryWrite(n,t.tag(i,xe.LengthDelimited).fork(),e),t.join())}scalar(t,e,r,i,n){let[o,c,d]=this.scalarInfo(e,i);(!d||n)&&(t.tag(r,o),t[c](i))}packed(t,e,r,i){if(!i.length)return;re(e!==O.BYTES&&e!==O.STRING),t.tag(r,xe.LengthDelimited),t.fork();let[,n]=this.scalarInfo(e);for(let o=0;o<i.length;o++)t[n](i[o]);t.join()}scalarInfo(t,e){let r=xe.Varint,i,n=e===void 0,o=e===0;switch(t){case O.INT32:i="int32";break;case O.STRING:o=n||!e.length,r=xe.LengthDelimited,i="string";break;case O.BOOL:o=e===!1,i="bool";break;case O.UINT32:i="uint32";break;case O.DOUBLE:r=xe.Bit64,i="double";break;case O.FLOAT:r=xe.Bit32,i="float";break;case O.INT64:o=n||fe.from(e).isZero(),i="int64";break;case O.UINT64:o=n||ut.from(e).isZero(),i="uint64";break;case O.FIXED64:o=n||ut.from(e).isZero(),r=xe.Bit64,i="fixed64";break;case O.BYTES:o=n||!e.byteLength,r=xe.LengthDelimited,i="bytes";break;case O.FIXED32:r=xe.Bit32,i="fixed32";break;case O.SFIXED32:r=xe.Bit32,i="sfixed32";break;case O.SFIXED64:o=n||fe.from(e).isZero(),r=xe.Bit64,i="sfixed64";break;case O.SINT32:i="sint32";break;case O.SINT64:o=n||fe.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function _k(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Og,{value:s});for(let e of s.fields){let r=e.localName;if(!e.opt)if(e.oneof)t[e.oneof]={oneofKind:void 0};else if(e.repeat)t[r]=[];else switch(e.kind){case"scalar":t[r]=Ku(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function zu(s,t,e){let r,i=e,n;for(let o of s.fields){let c=o.localName;if(o.oneof){const d=i[o.oneof];if((d==null?void 0:d.oneofKind)==null)continue;if(r=d[c],n=t[o.oneof],n.oneofKind=d.oneofKind,r==null){delete n[c];continue}}else if(r=i[c],n=t,r==null)continue;switch(o.repeat&&(n[c].length=r.length),o.kind){case"scalar":case"enum":if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=r[l];else n[c]=r;break;case"message":let d=o.T();if(o.repeat)for(let l=0;l<r.length;l++)n[c][l]=d.create(r[l]);else n[c]===void 0?n[c]=d.create(r):d.mergePartial(n[c],r);break;case"map":switch(o.V.kind){case"scalar":case"enum":Object.assign(n[c],r);break;case"message":let l=o.V.T();for(let u of Object.keys(r))n[c][u]=l.create(r[u]);break}break}}}function kk(s,t,e){if(t===e)return!0;if(!t||!e)return!1;for(let r of s.fields){let i=r.localName,n=r.oneof?t[r.oneof][i]:t[i],o=r.oneof?e[r.oneof][i]:e[i];switch(r.kind){case"enum":case"scalar":let c=r.kind=="enum"?O.INT32:r.T;if(!(r.repeat?Vg(c,n,o):Ng(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Lg(r.V.T(),Id(n),Id(o)):Vg(r.V.kind=="enum"?O.INT32:r.V.T,Id(n),Id(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Lg(d,n,o):d.equals(n,o)))return!1;break}}return!0}const Id=Object.values;function Ng(s,t,e){if(t===e)return!0;if(s!==O.BYTES)return!1;let r=t,i=e;if(r.length!==i.length)return!1;for(let n=0;n<r.length;n++)if(r[n]!=i[n])return!1;return!0}function Vg(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Ng(s,t[r],e[r]))return!1;return!0}function Lg(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!s.equals(t[r],e[r]))return!1;return!0}const xg=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({})),Ck=xg[Og]={};class v{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(vk),this.options=r!=null?r:{},Ck.value=this,this.messagePrototype=Object.create(null,xg),this.refTypeCheck=new yk(this),this.refJsonReader=new Ek(this),this.refJsonWriter=new bk(this),this.refBinReader=new wk(this),this.refBinWriter=new Pk(this)}create(t){let e=_k(this);return t!==void 0&&zu(this,e,t),e}clone(t){let e=this.create();return zu(this,e,t),e}equals(t,e){return kk(this,t,e)}is(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!1)}isAssignable(t,e=this.defaultCheckDepth){return this.refTypeCheck.is(t,e,!0)}mergePartial(t,e){zu(this,t,e)}fromBinary(t,e){let r=ok(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,fk(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,Sk(e))}toJsonString(t,e){var r;let i=this.toJson(t,e);return JSON.stringify(i,null,(r=e==null?void 0:e.prettySpaces)!==null&&r!==void 0?r:0)}toBinary(t,e){let r=mk(e);return this.internalBinaryWrite(t,r.writerFactory(),r).finish()}internalJsonRead(t,e,r){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){let i=r!=null?r:this.create();return this.refJsonReader.read(t,i,e),i}throw new Error(`Unable to parse message ${this.typeName} from JSON ${ju(t)}.`)}internalJsonWrite(t,e){return this.refJsonWriter.write(t,e)}internalBinaryWrite(t,e,r){return this.refBinWriter.write(t,e,r),e}internalBinaryRead(t,e,r,i){let n=i!=null?i:this.create();return this.refBinReader.read(t,n,r,e),n}}var Ks;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(Ks||(Ks={}));var zs;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(zs||(zs={}));class Rk extends v{constructor(){super("media.Codec",[{no:1,name:"channels",kind:"scalar",opt:!0,T:5},{no:2,name:"clock_rate",kind:"scalar",T:5},{no:3,name:"mime_type",kind:"scalar",T:9},{no:4,name:"sdp_fmtp_line",kind:"scalar",opt:!0,T:9},{no:5,name:"payload_type",kind:"scalar",opt:!0,T:13}])}}const Ug=new Rk;class Ik extends v{constructor(){super("media.HeaderExtension",[{no:1,name:"direction",kind:"scalar",opt:!0,T:9},{no:2,name:"uri",kind:"scalar",T:9}])}}const Ak=new Ik;class Mk extends v{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new Mk;class Ok extends v{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Ks]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const us=new Ok;class Dk extends v{constructor(){super("media.ProducerPayload",[{no:1,name:"kind",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",T:8},{no:3,name:"screen_share",kind:"scalar",T:8},{no:4,name:"msid",kind:"scalar",T:9},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"mime_type",kind:"scalar",opt:!0,T:9}])}}const Nk=new Dk;class Vk extends v{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:()=>us},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>Nk}])}}const Lk=new Vk;class xk extends v{constructor(){super("media.AudioActivityRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"energy",kind:"scalar",T:5},{no:3,name:"silent",kind:"scalar",T:8}])}}const Uk=new xk;class $k extends v{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>us},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const $g=new $k;class Bk extends v{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>us}])}}const Fk=new Bk;class Hk extends v{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>us}])}}new Hk;class qk extends v{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 jk=new qk;class Gk extends v{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 Wk=new Gk;class Jk extends v{constructor(){super("media.ProducerEntry",[{no:1,name:"producing_transport_id",kind:"scalar",T:9},{no:2,name:"producer_id",kind:"scalar",T:9}])}}new Jk;class Kk extends v{constructor(){super("media.ConsumerEntry",[{no:1,name:"consuming_transport_id",kind:"scalar",T:9},{no:2,name:"consumer_id",kind:"scalar",T:9}])}}new Kk;class zk extends v{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",zs]},{no:3,name:"pause",kind:"scalar",T:8},{no:4,name:"screen_share",kind:"scalar",T:8},{no:5,name:"app_data",kind:"scalar",opt:!0,T:9},{no:6,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"codec",kind:"message",T:()=>Ug}])}}const eo=new zk;class Yk extends v{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>eo},{no:3,name:"producer_track",kind:"message",T:()=>Wk},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const Qk=new Yk;class Xk extends v{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>Qk}}])}}const Bg=new Xk;class Zk extends v{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>qg},{no:2,name:"receiver",kind:"message",T:()=>qg}])}}const Fg=new Zk;class eC extends v{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Ug},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>Ak}])}}const Hg=new eC;class tC extends v{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Hg},{no:2,name:"video",kind:"message",T:()=>Hg}])}}const qg=new tC;class sC extends v{constructor(){super("media.PreferredCodec",[{no:1,name:"audio",kind:"scalar",opt:!0,T:9},{no:2,name:"video",kind:"scalar",opt:!0,T:9}])}}const rC=new sC;class iC extends v{constructor(){super("media.Simulcast",[{no:1,name:"preferred_rid",kind:"scalar",opt:!0,T:9},{no:2,name:"priority_ordering",kind:"scalar",opt:!0,T:9},{no:3,name:"rid_not_available",kind:"scalar",opt:!0,T:9}])}}const jg=new iC;class nC extends v{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 aC=new nC;class oC extends v{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:()=>aC},{no:9,name:"capabilities",kind:"message",T:()=>Fg}])}}const cC=new oC;class dC extends v{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const lC=new dC;class uC extends v{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const hC=new uC;class pC extends v{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 pC;class mC extends v{constructor(){super("media.edge.ConsumePeerRequest",[{no:1,name:"producing_peer_id",kind:"scalar",T:9},{no:2,name:"paused",kind:"scalar",opt:!0,T:8},{no:3,name:"producer_id",kind:"scalar",opt:!0,T:9},{no:4,name:"preferred_codec",kind:"message",T:()=>rC},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>jg}])}}const gC=new mC;class fC extends v{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>gC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const SC=new fC;class vC extends v{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>jg},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const TC=new vC;class yC extends v{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>TC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const EC=new yC;class bC extends v{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:()=>us},{no:5,name:"msid",kind:"scalar",T:9},{no:6,name:"app_data",kind:"scalar",opt:!0,T:9},{no:7,name:"mime_type",kind:"scalar",opt:!0,T:9},{no:8,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const wC=new bC;class PC extends v{constructor(){super("media.edge.SelectedPeersRequest",[])}}new PC;class _C extends v{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const kC=new _C;class CC extends v{constructor(){super("media.edge.ProducerToggleRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}const Ad=new CC;class RC extends v{constructor(){super("media.edge.ConsumerToggleRequest",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"pause",kind:"scalar",T:8}])}}new RC;class IC extends v{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>us},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const AC=new IC;class MC extends v{constructor(){super("media.edge.ConsumerCloseRequest",[{no:1,name:"consumer_ids",kind:"scalar",repeat:2,T:9},{no:2,name:"description",kind:"message",T:()=>us},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const OC=new MC;class DC extends v{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new DC;class NC extends v{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Gg=new NC;class VC extends v{constructor(){super("media.edge.PeerDisplayNameEditRequest",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}const LC=new VC;class xC extends v{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 UC=new xC;class $C extends v{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 BC=new $C;class FC extends v{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 HC=new FC;class qC extends v{constructor(){super("media.edge.ErrorResponse",[{no:1,name:"error_message",kind:"scalar",T:9},{no:2,name:"event_id",kind:"scalar",T:5}])}}const jC=new qC;class GC extends v{constructor(){super("media.edge.EmptyResponse",[])}}new GC;class WC extends v{constructor(){super("media.edge.RoomParticipants",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"producer_states",kind:"message",repeat:1,T:()=>eo},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"user_id",kind:"scalar",opt:!0,T:9},{no:5,name:"capabilities",kind:"message",T:()=>Fg}])}}const Wg=new WC;class JC extends v{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 Yu=new JC;class KC extends v{constructor(){super("media.edge.SelectedPeersDiffEntry",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"priority",kind:"scalar",T:5}])}}const zC=new KC;class YC extends v{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>zC}])}}const Jg=new YC;class QC extends v{constructor(){super("media.edge.PeerJoinResponse",[])}}new QC;class XC extends v{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>HC},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Wg},{no:3,name:"selected_peers",kind:"message",T:()=>Yu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Qu=new XC;class ZC extends v{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const eR=new ZC;class tR extends v{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Bg}])}}new tR;class sR extends v{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Bg},{no:3,name:"description",kind:"message",T:()=>us}])}}const rR=new sR;class iR extends v{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:()=>us}])}}const nR=new iR;class aR extends v{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>jk}])}}new aR;class oR extends v{constructor(){super("media.edge.ActiveSpeakerResponse",[{no:1,name:"responsepeer_id",kind:"scalar",T:9},{no:2,name:"volume",kind:"scalar",T:5}])}}new oR;class cR extends v{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new cR;class dR extends v{constructor(){super("media.edge.ProducerToggleResponse",[])}}new dR;class lR extends v{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new lR;class uR extends v{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>us}])}}const hR=new uR;class pR extends v{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>us}])}}const mR=new pR;class gR extends v{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new gR;class fR extends v{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new fR;class SR extends v{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new SR;class vR extends v{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const TR=new vR;class yR extends v{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const ER=new yR;class bR extends v{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const wR=new bR;class PR extends v{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Wg}])}}const Kg=new PR;class _R extends v{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const zg=new _R;class kR extends v{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>zg},{no:3,name:"screenshare",kind:"message",T:()=>zg}])}}const CR=new kR;class RR extends v{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>$g},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>CR}])}}new RR;class IR extends v{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>eo}])}}const AR=new IR;class MR extends v{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>eo},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Yg=new MR;class OR extends v{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>eo}])}}const DR=new OR;class NR extends v{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Xu=new NR;class VR extends v{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Qg=new VR;class LR extends v{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new LR;class xR extends v{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new xR;class UR extends v{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new UR;class $R extends v{constructor(){super("media.edge.PeerDisplayNameEditBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"display_name",kind:"scalar",T:9}])}}new $R;class BR extends v{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new BR;class FR extends v{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new FR;class HR extends v{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 Zu=new HR;class qR extends v{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 qR;class jR extends v{constructor(){super("socket.api.ErrorMessage",[{no:1,name:"code",kind:"scalar",opt:!0,T:5},{no:2,name:"message",kind:"scalar",T:9}])}}const GR=new jR;var Si;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(Si||(Si={}));var Ys;(function(s){s[s.UNSPECIFIED=0]="UNSPECIFIED",s[s.ON_STAGE=1]="ON_STAGE",s[s.APPROVED_STAGE=2]="APPROVED_STAGE",s[s.REQUESTED_STAGE=3]="REQUESTED_STAGE",s[s.OFF_STAGE=4]="OFF_STAGE"})(Ys||(Ys={}));var eh;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(eh||(eh={}));var th;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(th||(th={}));var Md;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Md||(Md={}));class WR extends v{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 JR=new WR;class KR extends v{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",Ys,"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:()=>JR}])}}const Od=new KR;class zR extends v{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Od}])}}const Cn=new zR;class YR extends v{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",Ys,"STAGE_TYPE_"]}])}}const Xg=new YR;class QR extends v{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 XR=new QR;class ZR extends v{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Od}])}}const sh=new ZR;class eI extends v{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Zg=new eI;class tI extends v{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:()=>rI},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const ef=new tI;class sI extends v{constructor(){super("socket.room.ActiveRecording",[{no:1,name:"recording_id",kind:"scalar",T:9},{no:2,name:"recording_type",kind:"enum",T:()=>["common.RecordingType",Si]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const rI=new sI;class iI extends v{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>ef}])}}const tf=new iI;class nI extends v{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const sf=new nI;class aI extends v{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 aI;class oI extends v{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Od},{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",Md,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const cI=new oI;class dI extends v{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Od},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const lI=new dI;class uI extends v{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>ef}])}}new uI;class hI extends v{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new hI;class pI extends v{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 rh=new pI;class mI extends v{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 gI=new mI;class fI extends v{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:()=>gI}])}}const rf=new fI;class SI extends v{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>rf},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>rf}])}}const vI=new SI;class TI extends v{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const yI=new TI;class EI extends v{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>yI}])}}const bI=new EI;class wI extends v{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:()=>rh}])}}const PI=new wI;class _I extends v{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>PI}])}}const nf=new _I;class kI extends v{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 CI=new kI;class RI extends v{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>CI}])}}new RI;class II extends v{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const AI=new II;class MI extends v{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>AI}])}}const OI=new MI;class DI extends v{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>LI}])}}const NI=new DI;class VI extends v{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:()=>rh}])}}const LI=new VI;class xI extends v{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 UI=new xI;class $I extends v{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:()=>UI}])}}const BI=new $I;class FI extends v{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:()=>rh}])}}const af=new FI;class HI extends v{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>af}])}}new HI;class qI extends v{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 jI=new qI;class GI extends v{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>KI}])}}const WI=new GI;class JI extends v{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 KI=new JI;class zI extends v{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const of=new zI;class YI extends v{constructor(){super("socket.room.BroadcastMessage",[{no:1,name:"type",kind:"scalar",T:9},{no:2,name:"payload",kind:"scalar",T:12},{no:3,name:"timestamp",kind:"scalar",T:4,L:2},{no:4,name:"ids",kind:"scalar",repeat:2,T:9},{no:5,name:"broadcast_type",kind:"enum",opt:!0,T:()=>["socket.room.BroadcastType",th,"BROADCAST_TYPE_"]}])}}const to=new YI;class QI extends v{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const XI=new QI;class ZI extends v{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const e0=new ZI;class t0 extends v{constructor(){super("socket.room.WaitingRoomRequest",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9},{no:3,name:"display_name",kind:"scalar",T:9},{no:4,name:"picture",kind:"scalar",opt:!0,T:9},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_name",kind:"scalar",opt:!0,T:9}])}}const s0=new t0;class r0 extends v{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>s0}])}}const cf=new r0;class i0 extends v{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 df=new i0;var ih;(function(s){s[s.NONE=0]="NONE",s[s.SKIP=1]="SKIP",s[s.ON_PRIVILEGED_USER_ENTRY=2]="ON_PRIVILEGED_USER_ENTRY",s[s.SKIP_ON_ACCEPT=3]="SKIP_ON_ACCEPT"})(ih||(ih={}));var Ir;(function(s){s[s.NONE=0]="NONE",s[s.ALLOWED=1]="ALLOWED",s[s.NOT_ALLOWED=2]="NOT_ALLOWED",s[s.CAN_REQUEST=3]="CAN_REQUEST"})(Ir||(Ir={}));class n0 extends v{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 a0=new n0;class o0 extends v{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 c0=new o0;class d0 extends v{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 l0=new d0;class u0 extends v{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 h0=new u0;class p0 extends v{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>l0},{no:2,name:"private",kind:"message",T:()=>h0}])}}const m0=new p0;class g0 extends v{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 f0=new g0;class S0 extends v{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ir,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Ir,"STREAM_PERMISSION_TYPE_"]}])}}const nh=new S0;class v0 extends v{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>nh},{no:2,name:"audio",kind:"message",T:()=>nh},{no:3,name:"screenshare",kind:"message",T:()=>nh}])}}const T0=new v0;class y0 extends v{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>a0},{no:2,name:"plugins",kind:"message",T:()=>c0},{no:3,name:"chat",kind:"message",T:()=>m0},{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",ih,"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",eh,"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:()=>f0},{no:23,name:"media",kind:"message",T:()=>T0}])}}const ah=new y0;class E0 extends v{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const b0=new E0;class w0 extends v{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 P0=new w0;class _0 extends v{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>P0}])}}const k0=new _0;class C0 extends v{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>ah}])}}const lf=new C0;class R0 extends v{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>lf}])}}const I0=new R0;class A0 extends v{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>lf}])}}const uf=new A0;class M0 extends v{constructor(){super("socket.preset.PeerUserIDMap",[{no:1,name:"peer_id",kind:"scalar",T:9},{no:2,name:"user_id",kind:"scalar",T:9}])}}const O0=new M0;class D0 extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>O0},{no:2,name:"patch",kind:"message",T:()=>ah}])}}new D0;class N0 extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>ah}])}}new N0;class V0 extends v{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 Ar=new V0;class L0 extends v{constructor(){super("socket.chat.GetPaginatedChatMessageFilters",[{no:1,name:"pinned",kind:"scalar",oneof:"filters",T:8},{no:2,name:"user_id",kind:"scalar",oneof:"filters",T:9}])}}const x0=new L0;class U0 extends v{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},{no:6,name:"filters",kind:"message",T:()=>x0}])}}const $0=new U0;class B0 extends v{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ar},{no:2,name:"next",kind:"scalar",T:8}])}}const F0=new B0;class H0 extends v{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Ar}])}}const hf=new H0;class q0 extends v{constructor(){super("socket.chat.SendChatMessageToRoomRequest",[{no:1,name:"payload_type",kind:"scalar",T:5},{no:2,name:"payload",kind:"scalar",T:9}])}}const j0=new q0;class G0 extends v{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Ar}])}}const oh=new G0;class W0 extends v{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 J0=new W0;class K0 extends v{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Ar}])}}const ch=new K0;class z0 extends v{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}])}}new z0;class Y0 extends v{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Ar}])}}new Y0;class Q0 extends v{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 X0=new Q0;class Z0 extends v{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 eA=new Z0;class tA extends v{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},{no:4,name:"message",kind:"message",T:()=>Ar}])}}const Dd=new tA;class sA extends v{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Ar}])}}const Nd=new sA;class rA extends v{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 iA=new rA;class nA extends v{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 Vd=new nA;class aA extends v{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 oA=new aA;class cA extends v{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}])}}new cA;class dA extends v{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new dA;class lA extends v{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}])}}new lA;class uA extends v{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}])}}new uA;class hA extends v{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new hA;class pA extends v{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new pA;class mA extends v{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Ar},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const gA=new mA;class fA extends v{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:()=>gA},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const SA=new fA;class vA extends v{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>SA}])}}new vA;class TA extends v{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 yA=new TA;class EA extends v{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>yA}])}}new EA;class bA extends v{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new bA;class wA extends v{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}new wA;class PA extends v{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new PA;class _A extends v{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new _A;class kA extends v{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}])}}new kA;class CA extends v{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}])}}new CA;class RA extends v{constructor(){super("socket.plugin.PluginEventToRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new RA;class IA extends v{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}])}}new IA;class AA extends v{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 dh=new AA;class MA extends v{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:()=>dh}])}}const OA=new MA;class DA extends v{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:()=>dh}])}}const NA=new DA;class VA extends v{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:()=>dh}])}}const LA=new VA;class xA extends v{constructor(){super("socket.plugin.PluginStoreDeleteRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"store_name",kind:"scalar",T:9}])}}new xA;class UA extends v{constructor(){super("socket.plugin.EnablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"enabled_by",kind:"scalar",T:9}])}}const $A=new UA;class BA extends v{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>$A}])}}new BA;class FA extends v{constructor(){super("socket.plugin.DisablePluginResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"disabled_by",kind:"scalar",T:9}])}}new FA;class HA extends v{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 qA=new HA;class jA extends v{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:()=>qA}])}}const pf=new jA;class GA extends v{constructor(){super("socket.plugin.PluginEventResponse",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"plugin_data",kind:"scalar",T:12}])}}new GA;class WA extends v{constructor(){super("socket.livestreaming.LiveStreamingEvent",[{no:1,name:"livestream_id",kind:"scalar",T:9},{no:2,name:"err_message",kind:"scalar",T:9},{no:3,name:"name",kind:"scalar",T:9},{no:4,name:"meeting_id",kind:"scalar",T:9},{no:5,name:"playback_url",kind:"scalar",T:9},{no:6,name:"org_id",kind:"scalar",T:9},{no:7,name:"room_name",kind:"scalar",T:9},{no:8,name:"room_uuid",kind:"scalar",T:9},{no:9,name:"status",kind:"scalar",T:9},{no:10,name:"manual_ingest",kind:"scalar",opt:!0,T:8}])}}const mf=new WA;class JA extends v{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const gf=new JA;class KA extends v{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 zA=new KA;class YA extends v{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>zA}])}}const lh=new YA;class QA extends v{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const XA=new QA;class ZA extends v{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const eM=new ZA;class tM extends v{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const ff=new tM;class sM extends v{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:()=>iM},{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 Sf=new sM;class rM extends v{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:()=>aM}])}}const iM=new rM;class nM extends v{constructor(){super("socket.polls.PollVote",[{no:1,name:"user_id",kind:"scalar",T:9},{no:2,name:"name",kind:"scalar",T:9}])}}const aM=new nM;class oM extends v{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 cM=new oM;class dM extends v{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 lM=new dM;class uM extends v{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>Sf}])}}const uh=new uM;class hM extends v{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>Sf}])}}const pM=new hM;class mM extends v{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",Si]}])}}const vf=new mM;class gM extends v{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 t=this.create(),e=Date.now();return t.seconds=fe.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(fe.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=fe.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=fe.from(t.seconds).toNumber()*1e3;if(r<Date.parse("0001-01-01T00:00:00Z")||r>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(t.nanos<0)throw new Error("Unable to encode invalid Timestamp to JSON. Nanos must not be negative.");let i="Z";if(t.nanos>0){let n=(t.nanos+1e9).toString().substring(1);n.substring(3)==="000000"?i="."+n.substring(0,3)+"Z":n.substring(6)==="000"?i="."+n.substring(0,6)+"Z":i="."+n+"Z"}return new Date(r).toISOString().replace(".000Z",i)}internalJsonRead(t,e,r){if(typeof t!="string")throw new Error("Unable to parse Timestamp from JSON "+ju(t)+".");let i=t.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 n=Date.parse(i[1]+"-"+i[2]+"-"+i[3]+"T"+i[4]+":"+i[5]+":"+i[6]+(i[8]?i[8]:"Z"));if(Number.isNaN(n))throw new Error("Unable to parse Timestamp from JSON. Invalid value.");if(n<Date.parse("0001-01-01T00:00:00Z")||n>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 r||(r=this.create()),r.seconds=fe.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new gM;class fM extends v{constructor(){super("common.BaseHubMessage",[{no:1,name:"event",kind:"scalar",T:5},{no:2,name:"id",kind:"scalar",T:9},{no:3,name:"peer_id",kind:"scalar",T:9},{no:4,name:"room_id",kind:"scalar",T:9},{no:5,name:"user_id",kind:"scalar",T:9},{no:6,name:"payload",kind:"scalar",T:12},{no:7,name:"error",kind:"scalar",opt:!0,T:8},{no:8,name:"sid",kind:"scalar",opt:!0,T:9},{no:9,name:"room_object_id",kind:"scalar",opt:!0,T:9},{no:10,name:"preset",kind:"scalar",opt:!0,T:9},{no:11,name:"use_start_session",kind:"scalar",opt:!0,T:8}])}}const hh=new fM;class SM extends v{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>hh}])}}new SM;class vM extends v{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>hh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>hh}])}}new vM;const TM=0,yM=1,EM=2,bM=3,wM=5,PM={getPeerInfo:0,updatePeerInfo:1,getRoomPeersInfo:2,joinRoom:3,leaveRoom:4,getRoomInfo:5,updateRoomInfo:6,closeRoom:7,startedLivestream:8,stoppedLivestream:9,erroredLivestream:10,getStagePeers:11,getStageRequests:12,requestStageAccess:13,cancelStageRequest:14,grantStageAccess:15,denyStageAccess:16,roomPeerCount:17,joinStage:18,leaveStage:19,getConnectedRoomsDump:20,createConnectedRooms:21,deleteConnectedRooms:22,movePeers:23,transferPeer:24,movedPeer:25,connectedRoomsUpdated:26,connectedRoomsDeleted:27,getAllAddedParticipants:28,broadcastMessage:29,kick:30,kickAll:31,transcript:32,getWaitingRoomRequests:33,acceptWaitingRoomRequests:34,waitingRoomRequestAccepted:35,denyWaitingRoomRequests:36,waitingRoomRequestDenied:37,peerStageStatusUpdate:38,broadcastToEntity:39,recordingStarted:40,recordingStopped:41,recordingPaused:42,getRoomStageState:43,livestreamingInvoked:44},_M={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},kM={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},CM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},Tf={unknown:0,createWebRTCTransport:1,produce:2,consume:3,toggleProducer:4,toggleConsumer:5,closeProducer:6,closeConsumer:7,updateConsumersSimulcastConfig:8,joinRoom:16,leaveRoom:17,selectedPeer:18,globalPinPeer:19,selfJoinComplete:20,peerJoinedBroadcast:25,peerLeaveBroadcast:26,peerProducerCreateBroadcast:27,peerProducerToggleBroadcast:28,peerProducerCloseBroadcast:29,globalPeerPinBroadcast:30,recordingStartedBroadcast:31,recordingStoppedBroadcast:32,peerDisplayNameEditBroadcast:33,mediaRoomTerminationBroadcastResponse:36,selectedPeerDiff:40,renegotiateSessionDescription:50,errorResponse:60,kickPeer:90,kickAll:91,changeDisplayName:92,hostControlPeer:93,hostControlAllPeers:94,audioActivity:100},RM={getUserPresets:0,updateUserPreset:1};function so(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function yf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const U=so(TM,PM),Je=so(yM,_M),Qs=so(EM,kM),Xs=so(bM,CM),Mr=yf(Tf,16777216),hs=yf(Tf,50331648),Ld=so(wM,RM);var IM=Object.defineProperty,AM=Object.getOwnPropertyDescriptor,Or=(s,t,e,r)=>{for(var i=r>1?void 0:r?AM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&IM(t,e,i),i},zt=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(zt||{});class Zs{constructor(t,e){g(this,xt,void 0);g(this,Hn,void 0);f(this,xt,e),f(this,Hn,t)}get telemetry(){return a(this,Hn).getValue("telemetry")}get logger(){return a(this,Hn).getValue("logger")}getChatMessages(){return a(this,xt).sendMessagePromise(Je.getMessages)}async getChatMessagesPaginated(t,e,r,i){const n={timeStamp:t,size:e,from:0,reversed:r,...i&&{filters:{filters:i}}},o=await a(this,xt).sendMessagePromise(Je.getPaginatedMessages,$0.toBinary(n));return o.payload?F0.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,xt).sendMessage(Je.sendMessageToRoom,j0.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,xt).sendMessage(Je.sendMessageToPeers,J0.toBinary(i))}sendMessage(t,e,r){if(r&&r.length>0){this.sendMessageToPeers(t,e,r);return}this.sendMessageToRoom(t,e)}async editMessage(t,e,r,i){const n={chatId:t,payloadType:r,payload:e};i!==void 0&&(n.pinned=i);const o=await a(this,xt).sendMessagePromise(Je.editMessage,X0.toBinary(n));return Nd.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,xt).sendMessagePromise(Je.deleteMessage,iA.toBinary(e));return{id:Vd.fromBinary(r.payload).chatId}}async searchMessages(t,e){var i,n,o,c;const r={searchTerm:t,timeStamp:(i=e.timestamp)!=null?i:Date.now(),size:(n=e.limit)!=null?n:75,from:(o=e.offset)!=null?o:0,reversed:(c=e.reversed)!=null?c:!0};try{const d=await a(this,xt).sendMessagePromise(Je.searchChannelMessages,oA.toBinary(r));return hf.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,xt).sendMessagePromise(Je.pinMessage,eA.toBinary(r));return Dd.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Je.sendMessageToRoom:{r=oh.fromBinary.bind(oh),i=oh.create();break}case Je.sendMessageToPeers:{r=ch.fromBinary.bind(ch),i=ch.create();break}case Je.editMessage:{r=Nd.fromBinary.bind(Nd),i=Nd.create();break}case Je.pinMessage:{r=Dd.fromBinary.bind(Dd),i=Dd.create();break}case Je.deleteMessage:{r=Vd.fromBinary.bind(Vd),i=Vd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,xt).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("chatSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}xt=new WeakMap,Hn=new WeakMap,Or([E.trace("SocketService.getChatMessages")],Zs.prototype,"getChatMessages",1),Or([E.trace("SocketService.getChatMessagesPaginated")],Zs.prototype,"getChatMessagesPaginated",1),Or([E.trace("SocketService.sendMessageToRoom")],Zs.prototype,"sendMessageToRoom",1),Or([E.trace("SocketService.sendMessageToPeers")],Zs.prototype,"sendMessageToPeers",1),Or([E.trace("SocketService.sendMessage")],Zs.prototype,"sendMessage",1),Or([E.trace("SocketService.editMessage")],Zs.prototype,"editMessage",1),Or([E.trace("SocketService.deleteMessage")],Zs.prototype,"deleteMessage",1),Or([E.trace("SocketService.searchMessages")],Zs.prototype,"searchMessages",1);function MM(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Is(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Is(e));const t={};return Object.keys(s).forEach(e=>{const r=pu(e)?e:MM(e);t[r]=Is(s[e])}),t}function OM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Ef(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Ef(e));const t={};return Object.keys(s).forEach(e=>{const r=pu(e)?e:OM(e);t[r]=s[e]}),t}class xd extends Error{constructor(e){const r=e instanceof Error?e.message:`Request failed with status ${e.status}`;super(r);p(this,"status");p(this,"response");p(this,"isTimeout");e instanceof Error?(this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(this.status=e.status,this.response=e,this.isTimeout=!1),this.name="RequestError"}get isHttpError(){return this.status!==void 0}get isNetworkError(){return this.status===void 0&&!this.isTimeout}}class bf{constructor(t){p(this,"defaults");this.defaults={baseURL:t.baseURL,headers:{common:{}},timeout:t.timeout,retry:t.retry,retryDelay:t.retryDelay}}buildURL(t,e){const{baseURL:r}=this.defaults,i=t.startsWith("http")?t:`${r}${t.startsWith("/")?t:`/${t}`}`;if(e){const n=new URLSearchParams;return Object.entries(e).forEach(([o,c])=>{n.append(o,c)}),`${i}${i.includes("?")?"&":"?"}${n.toString()}`}return i}async request(t){var h;const e=((h=t.method)==null?void 0:h.toUpperCase())||"GET",r=this.buildURL(t.url||"",t.params),i={...this.defaults.headers.common,...t.headers};e!=="GET"&&e!=="HEAD"&&t.data&&!i["Content-Type"]&&(i["Content-Type"]="application/json");const o=i["Content-Type"]==="application/json"?JSON.stringify(t.data):t.data,c={method:e,headers:i,body:e!=="GET"&&e!=="HEAD"&&t.data?o:void 0},d=t.timeout||this.defaults.timeout,l=t.retry!==void 0?t.retry:this.defaults.retry,u=t.retryDelay||this.defaults.retryDelay;try{const m=new AbortController,S=setTimeout(()=>m.abort(),d);c.signal=m.signal;const y=await fetch(r,c);clearTimeout(S);let w=null;const _=y.headers.get("content-type");_&&_.includes("application/json")?w=await y.json():w=await y.text();const C={};y.headers.forEach((V,$)=>{C[$]=V});const D={data:w,status:y.status,statusText:y.statusText,headers:C,config:t};if(!y.ok)throw D;return D}catch(m){if(m instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,u)),this.defaults.baseURL===fi.apiBase.prod?this.defaults.baseURL=fi.apiBase.prodAlternate:this.defaults.baseURL===fi.apiBase.prodAlternate&&(this.defaults.baseURL=fi.apiBase.prod),this.request({...t,retry:l-1});throw m}}async get(t,e={}){return this.request({...e,method:"GET",url:t})}async post(t,e,r={}){return this.request({...r,method:"POST",url:t,data:e})}async put(t,e,r={}){return this.request({...r,method:"PUT",url:t,data:e})}}const DM=3,NM=30,VM=8e3;class LM{constructor(t,e){p(this,"fetchClient");p(this,"requests");p(this,"roomName");p(this,"roomUUID");p(this,"authToken");p(this,"organizationId");p(this,"iceServers");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=VM,retry:i=DM,retryDelay:n=NM,baseURL:o=fi.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new bf({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new bf({baseURL:"",timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.setAuthToken(c,{bearer:!0});const l=this.requests.request.bind(this.requests);this.requests.request=async u=>{var m,S,y,w,_;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const C=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:C.status,statusText:C.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),C}catch(C){if(!C)throw new R("Unknown network error occurred","0011");if(C instanceof R||C instanceof xd)throw C;((m=C.config)==null?void 0:m.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:C,networkCall:{status:C.status,statusText:C.statusText,baseURL:((S=C.config)==null?void 0:S.baseURL)||this.requests.defaults.baseURL,url:(y=C.config)==null?void 0:y.url,retries:(w=C.config)==null?void 0:w.retry,method:(_=C.config)==null?void 0:_.method,isOnline:navigator.onLine?"online":"offline"}});const D=C instanceof Error&&C.message||"Network request failed";throw new R(D,"0011"),new xd(C)}}}get peerId(){return this.context.getValue("peerId")}get logger(){return this.context.getValue("logger")}setAuthToken(t,e){const{bearer:r}=e||{};this.authToken=t,this.requests.defaults.headers.common.Authorization=r?`Bearer ${t}`:t}setHeader(t,e){this.requests.defaults.headers.common[t]=e}setRoomName(t){this.roomName=t}setRoomUUID(t){this.roomUUID=t}setOrganizationId(t){this.organizationId=t}}var xM=Object.defineProperty,UM=Object.getOwnPropertyDescriptor,er=(s,t,e,r)=>{for(var i=r>1?void 0:r?UM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&xM(t,e,i),i};class As extends LM{constructor(e,r){super(e,r);p(this,"telemetry");this.telemetry=e.getValue("telemetry"),this.setHeader("x-realtimekit-version",e.getValue("sdkVersion"))}async getICEServers(){if(this.iceServers)return this.iceServers;const{success:e,iceServers:r}=(await this.requests.get("/iceservers")).data;if(e)return(r==null?void 0:r.length)>0&&(this.iceServers=r),r}async getPresignedUrls(e){const r=Pn(this.context,"chat_upload_expiry"),i={roomUUID:this.roomUUID,filename:e,expiry:typeof r=="number"?r:void 0},{get_location:n,put_location:o}=(await this.requests.post("/v2/meetings/chat-upload",i)).data.data;return{getLocation:n,putLocation:o}}async uploadFile(e,r){if(navigator.isReactNative&&"uri"in e)try{await fetch(r,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:{uri:e.uri,name:e.name}})}catch(i){this.logger.error(`sendFileMessage::${i}`)}else await this.fetchClient.put(r,e,{headers:{"Content-Type":e.type}})}async startLivestreaming({manualIngestion:e}){const r=Is(await this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/livestreams`,{manual_ingest:!!e})).data.data;return{playbackUrl:r.playbackUrl,status:r.status,manualIngest:r.manualIngest,ingestionCredentials:r.streamKey?{ingestionServer:r.ingestServer,streamKey:r.streamKey}:null}}async stopLivestreaming(){return this.requests.post(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream/stop`)}async getActiveLivestream(){const e=Is((await this.requests.get(`/v2/meetings/${this.context.getValue("meetingId")}/active-livestream`)).data.data);return{playbackUrl:e.playbackUrl,status:e.status,manualIngest:e.manualIngest,ingestionCredentials:e.streamKey?{ingestionServer:e.ingestServer,streamKey:e.streamKey}:null}}async getUserDetails(){if(this.userDetails)return this.userDetails;const e=(await this.requests.get("v2/internals/participant-details")).data.data;return Is(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...Ef(e),meeting_id:this.context.getValue("meetingId"),allow_multiple_recordings:!!r})).data.data.id}async updateRecording(e,r){return this.requests.put(`v2/recordings/${e}`,{action:r})}async getActiveRecording(){const{status:e,id:r}=(await this.requests.get(`v2/recordings/active-recording/${this.context.getValue("meetingId")}`)).data.data;return{status:e,id:r}}async getActiveTranscript(){const{transcript_download_url:e}=(await this.requests.get(`v2/meetings/${this.context.getValue("meetingId")}/active-transcript`)).data.data;try{return{transcript:(await this.fetchClient.get(e)).data}}catch(r){throw new R("Cant fetch transcript s3 url","1801")}}}er([E.trace("APIClient.getICEServers")],As.prototype,"getICEServers",1),er([E.trace("APIClient.startLivestreaming")],As.prototype,"startLivestreaming",1),er([E.trace("APIClient.stopLivestreaming")],As.prototype,"stopLivestreaming",1),er([E.trace("APIClient.getActiveLivestream")],As.prototype,"getActiveLivestream",1),er([E.trace("APIClient.getUserDetails")],As.prototype,"getUserDetails",1),er([E.trace("APIClient.startRecording")],As.prototype,"startRecording",1),er([E.trace("APIClient.stopRecording")],As.prototype,"updateRecording",1),er([E.trace("APIClient.getActiveRecording")],As.prototype,"getActiveRecording",1),er([E.trace("APIClient.getActiveTranscript")],As.prototype,"getActiveTranscript",1);let ph;function $M(s,t){return ph=new As(s,t),ph}function Pt(){return ph}const Rn={maxInvocations:5,period:1};function Nt(s,t){return function(e,r,i){const n=i.value;let o=0,c=Date.now();return i.value=function(...d){const l=Date.now(),u=t?this[t]:s;if(l-c>u.period*1e3&&(c=l,o=0),o>=u.maxInvocations)throw new R(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var BM=Object.defineProperty,FM=Object.getOwnPropertyDescriptor,Ms=(s,t,e,r)=>{for(var i=r>1?void 0:r?FM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&BM(t,e,i),i};const HM=["text","image","file","custom","poll"],Ud={maxInvocations:180,period:60};let Yt=(LS=class extends Dt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,pl);g(this,_o);p(this,"messages");g(this,se,void 0);g(this,Ai,void 0);g(this,nt,void 0);g(this,qn,void 0);p(this,"maxTextLimit",2e3);f(this,qn,t),f(this,nt,e),f(this,se,r),f(this,Ai,i),this.messages=[]}get telemetry(){return a(this,qn).getValue("telemetry")}setMaxTextLimit(t){this.maxTextLimit=t}async sendMessageInternal(t,e){switch(t.type){case"text":{await this.sendTextMessageInternal(t.message,e);break}case"image":await this.sendImageMessageInternal(t.image,e);break;case"file":await this.sendFileMessageInternal(t.file,e);break;default:this.logger.error("sendMessage::message_type_not_supported",{chat:{messageType:t.type}});break}}async sendTextMessageInternal(t,e){var i,n,o,c,d,l;if(t.length>this.maxTextLimit)throw new R("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,se).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,se).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new R("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,se).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,se).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new R("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new R("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,se).id),r=a(this,Ai).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,se).userId)),a(this,nt).sendMessage(t,zt.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,se).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,se).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,se).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,se).permissions)==null?void 0:d.chatPublic)!=null&&l.files)){this.logger.error("sendImageMessage::permission_denied");return}if(!t){this.logger.error("sendImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(t.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:t.type}});return}try{const u=Pt(),{getLocation:h,putLocation:m}=await u.getPresignedUrls(t.name);await u.uploadFile(t,m);let S=[];e&&e.length>0&&(e.push(a(this,se).id),S=a(this,Ai).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),S.push(a(this,se).userId)),a(this,nt).sendMessage(h,zt.IMAGE,e)}catch(u){throw new R("Error sending image message.","0500",this.logger)}}async sendFileMessageInternal(t,e){var r,i,n,o,c,d;if(e&&e.length>0){if(!((r=a(this,se).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,se).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,se).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,se).permissions)==null?void 0:c.chatPublic)!=null&&d.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!t){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const l=Pt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let m=[];e&&e.length>0&&(e.push(a(this,se).id),m=a(this,Ai).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),m.push(a(this,se).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,nt).sendMessage(S,zt.FILE,e)}catch(l){throw new R("Error sending file message.","0500",this.logger)}}get rateLimits(){return Ud}updateRateLimits(t,e){Ud.maxInvocations=t,Ud.period=e}async sendTextMessage(t,e){return this.sendTextMessageInternal(t,e)}async sendCustomMessage(t,e){var n,o,c,d,l,u,h,m,S,y,w,_,C,D,V;if(e&&e.length>0){if(!((n=a(this,se).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,se).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,se).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,se).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,se).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((S=(m=a(this,se).permissions)==null?void 0:m.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async $=>{try{if(typeof $=="string")return{link:$};const H=Pt(),{getLocation:F,putLocation:Z}=await H.getPresignedUrls($.name);return await H.uploadFile($,Z),{link:F,type:$.type,name:$.name,size:$.size}}catch(H){throw new R("Error sending image message.","0500",this.logger)}},i={...t,files:await Promise.all((w=(y=t.files)!=null?y:[])==null?void 0:w.map(async $=>r($))),images:await Promise.all((C=(_=t.images)!=null?_:[])==null?void 0:C.map(async $=>r($))),videos:await Promise.all((V=(D=t.videos)!=null?D:[])==null?void 0:V.map(async $=>r($)))};a(this,nt).sendMessage(JSON.stringify(i),zt.CUSTOM,e)}async sendImageMessage(t,e){return this.sendImageMessageInternal(t,e)}async sendFileMessage(t,e){return this.sendFileMessageInternal(t,e)}async sendMessage(t,e){return this.sendMessageInternal(t,e)}async editTextMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,se).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,se).permissions)==null?void 0:n.chatPublic)!=null&&o.text)){this.logger.error("editTextMessage::permission_denied");return}if(!e){this.logger.error("editTextMessage::message_can_not_be_empty");return}a(this,nt).editMessage(t,e,zt.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,se).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,se).permissions)==null?void 0:o.chatPublic)!=null&&c.files)){this.logger.error("editImageMessage::permission_denied");return}if(!e){this.logger.error("editImageMessage::required_argument_image_can_not_be_empty");return}if(!["image/gif","image/jpeg","image/png"].includes(e.type)){this.logger.error("sendImageMessage::image_type_not_supported",{chat:{imageType:e.type}});return}try{const d=Pt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,nt).editMessage(t,l,zt.IMAGE)}catch(d){throw new R("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,se).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,se).permissions)==null?void 0:n.chatPublic)!=null&&o.files)){this.logger.error("sendFileMessage::permission_denied");return}if(!e){this.logger.error("sendFileMessage::required_argument_file_can_not_be_empty");return}try{const c=Pt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,nt).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),zt.FILE)}catch(c){throw new R("Error editing file message.","0500",this.logger)}}async editMessage(t,e){switch(e.type){case"text":{this.editTextMessage(t,e.message);break}case"image":{this.editImageMessage(t,e.image);break}case"file":{this.editFileMessage(t,e.file);break}default:{this.logger.error("editMessage::message_type_not_supported",{chat:{messageType:e.type}});break}}}async deleteMessage(t){a(this,nt).deleteMessage(t)}async pin(t){if(!a(this,_o,Xh))throw new R("Can`t pin message without joining room","0505");try{await a(this,nt).setPinState(t,!0)}catch(e){throw new R(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,_o,Xh))throw new R("Can`t unpin message without joining room","0505");try{await a(this,nt).setPinState(t,!1)}catch(e){throw new R(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,nt).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>ro.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,nt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>ro.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,nt).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>ro.formatSocketPeerMessage(o))}},se=new WeakMap,Ai=new WeakMap,nt=new WeakMap,qn=new WeakMap,pl=new WeakSet,tv=function(){return a(this,qn).getValue("connectionHandler")},_o=new WeakSet,Xh=function(){return a(this,pl,tv).socketJoined===!0},LS);Ms([E.trace("Chat.sendTextMessage"),Nt(Ud)],Yt.prototype,"sendTextMessage",1),Ms([E.trace("Chat.sendImageMessage"),Nt({maxInvocations:20,period:60})],Yt.prototype,"sendImageMessage",1),Ms([E.trace("Chat.sendFileMessage"),Nt({maxInvocations:20,period:60})],Yt.prototype,"sendFileMessage",1),Ms([E.trace("Chat.sendMessage"),Nt({maxInvocations:180,period:60})],Yt.prototype,"sendMessage",1),Ms([E.trace("Chat.editTextMessage")],Yt.prototype,"editTextMessage",1),Ms([E.trace("Chat.editImageMessage")],Yt.prototype,"editImageMessage",1),Ms([E.trace("Chat.editFileMessage")],Yt.prototype,"editFileMessage",1),Ms([E.trace("Chat.editMessage")],Yt.prototype,"editMessage",1),Ms([E.trace("Chat.deleteMessage")],Yt.prototype,"deleteMessage",1),Yt=Ms([lt("0500")],Yt);var qM=Object.defineProperty,jM=Object.getOwnPropertyDescriptor,GM=(s,t,e,r)=>{for(var i=r>1?void 0:r?jM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&qM(t,e,i),i};const Dr=(xS=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");g(this,Mi,void 0);f(this,Mi,s),this.chatSocketHandler=t,this.chat=new Yt(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Mi).getValue("telemetry")}get logger(){return a(this,Mi).getValue("logger")}static async init(s,t,e,r){return new Dr(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:HM[s.type]}}static formatSocketPeerMessage(s){const t=s.createdAt*1e3,e={displayName:s.displayName,id:s.chatId,time:t,timeMs:s.createdAtMs,type:s.payloadType,isEdited:s.isEdited,userId:s.userId,targetUserIds:s.targetUserIds,message:"",link:"",name:"",html:"",images:[],videos:[],files:[],size:0,pinned:s.pinned};switch(e.type){case zt.TEXT:{e.message=s.payload;break}case zt.IMAGE:{e.link=s.payload;break}case zt.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case zt.CUSTOM:{const{html:r,images:i,message:n,videos:o,files:c}=JSON.parse(s.payload);e.message=n,e.html=r,e.images=i,e.videos=o,e.files=c;break}}return Dr.formatMessage(e)}async getChatMessages(){if(this.self.config.viewType==="LIVESTREAM")return;const s=await this.chatSocketHandler.getChatMessages();if(!(s!=null&&s.payload))return;const t=hf.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Dr.formatSocketPeerMessage(e))}setupEvents(){a(this,Mi).getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Je.sendMessageToRoom,s=>{if(!s.message)return;const t=Dr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Je.sendMessageToPeers,s=>{const t=Dr.formatSocketPeerMessage(s.message);this.chat.messages=[...this.chat.messages,t],this.chat.emit("chatUpdate",{action:"add",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Je.editMessage,s=>{if(!s.message)return;const t=Dr.formatSocketPeerMessage(s.message),e=this.chat.messages.findIndex(r=>r.id===t.id);e!==-1&&(this.chat.messages[e]=t),this.chat.emit("chatUpdate",{action:"edit",message:t,messages:this.chat.messages})}),this.chatSocketHandler.on(Je.deleteMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId);let e={id:s.chatId};t!==-1&&([e]=this.chat.messages.splice(t,1)),this.chat.emit("chatUpdate",{action:"delete",message:e,messages:this.chat.messages})}),this.chatSocketHandler.on(Je.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=Dr.formatSocketPeerMessage(s.message);t!==-1&&(this.chat.messages[t]=e),this.chat.emit("chatUpdate",{action:"edit",message:e,messages:this.chat.messages}),s.pinned?this.chat.emit("pinMessage",{message:e,messages:this.chat.messages}):this.chat.emit("unpinMessage",{message:e,messages:this.chat.messages})})}},Mi=new WeakMap,xS);let ro=Dr;GM([E.trace("ChatController.setupEvents")],ro.prototype,"setupEvents",1);var WM=Object.defineProperty,JM=Object.getOwnPropertyDescriptor,KM=(s,t,e,r)=>{for(var i=r>1?void 0:r?JM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WM(t,e,i),i};let mh=(US=class extends Dt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,ml);g(this,gl);p(this,"items");g(this,jn,void 0);g(this,Gn,void 0);g(this,ko,void 0);f(this,ko,t),f(this,jn,e),f(this,Gn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,gl,rv))throw new R("Can't create polls without joining room","0705");if(!a(this,jn).permissions.polls.canCreate){this.logger.error("Polls::create::permission_denied");return}if(!t||!e){this.logger.error("Polls::question_and_options_can_not_be_empty",{polls:{hasQuestion:!!t,optionsLength:e==null?void 0:e.length}});return}if(e.length<2){this.logger.error("Polls::there_must_be_at_least_two_options",{polls:{hasQuestion:!!t,optionsLength:e.length}});return}await a(this,Gn).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,jn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,Gn).votePoll(t,e)}},ml=new WeakSet,sv=function(){return a(this,ko).getValue("connectionHandler")},gl=new WeakSet,rv=function(){var t;return((t=a(this,ml,sv))==null?void 0:t.socketJoined)===!0},jn=new WeakMap,Gn=new WeakMap,ko=new WeakMap,US);mh=KM([lt("0700")],mh);var zM=Object.defineProperty,YM=Object.getOwnPropertyDescriptor,QM=(s,t,e,r)=>{for(var i=r>1?void 0:r?YM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&zM(t,e,i),i};const In=($S=class{constructor(s,t,e){p(this,"polls");g(this,qr,void 0);g(this,Wn,void 0);g(this,Oi,void 0);this.polls=new mh(s,t,e),f(this,Wn,t),f(this,qr,s),f(this,Oi,e),this.setupEvents()}get telemetry(){return a(this,qr).getValue("telemetry")}get logger(){return a(this,qr).getValue("logger")}static async init(s,t,e){return new In(s,t,e)}canViewPolls(){return a(this,Wn).permissions.polls.canView}setupEvents(){const s={[Xs.createPoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))},[Xs.updatePoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))},[Xs.votePoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))}},t=()=>{a(this,qr).getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Oi).on(r,s[r])})},e=()=>{a(this,qr).getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Oi).removeListeners(r)})};a(this,Wn).permissions.on("permissionsUpdate",async r=>{var i;r!=null&&r.polls&&((i=r==null?void 0:r.polls)!=null&&i.canView?(await this.getPolls(),t()):(this.polls.items=[],e()))}),this.canViewPolls()&&t()}updatePoll(s){if(!this.canViewPolls())return;const t=this.polls.items.findIndex(e=>e.id===s.id);if(t>-1){const e=JSON.stringify(this.polls.items[t]);this.polls.items[t]=s,e!==JSON.stringify(s)&&this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!1});return}this.polls.items=[...this.polls.items,s],this.polls.emit("pollsUpdate",{polls:this.polls.items,newPoll:!0})}async getPolls(){const s=await a(this,Oi).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=pM.fromBinary(s.payload);this.polls.items=t.map(e=>In.formatSocketServicePoll(e))}static formatSocketServicePoll(s){const t=s.options.map(e=>({count:e.count,text:e.text,votes:e.votes.map(r=>({id:r.userId,name:r.name}))}));return{anonymous:s.anonymous,createdBy:s.createdBy,createdByUserId:s.createdByUserId,hideVotes:s.hideVotes,id:s.pollId,options:t,question:s.question,voted:s.votes}}},qr=new WeakMap,Wn=new WeakMap,Oi=new WeakMap,$S);let wf=In;QM([E.trace("PollController.setupEvents")],wf.prototype,"setupEvents",1);var XM=Object.defineProperty,ZM=Object.getOwnPropertyDescriptor,eO=(s,t,e,r)=>{for(var i=r>1?void 0:r?ZM(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&XM(t,e,i),i},Pf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Pf||{});let gh=(BS=class extends Dt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);g(this,Co);p(this,"selfActiveTab");p(this,"broadcastTabChanges");g(this,Jn,void 0);g(this,Di,void 0);g(this,Ro,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,Jn,t),f(this,Di,e),this.viewType=r,f(this,Ro,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Co,Zh).socketState}get mediaState(){return a(this,Co,Zh).mediaState}get meetingId(){return a(this,Jn).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Di).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new R("User does not have permission to toggle spotlight","0801");this.broadcastTabChanges=t,this.emit("broadcastTabChangesUpdate",this.broadcastTabChanges),this.broadcastTabChanges&&this.assertActiveTabToRoom()}setSelfActiveTab(t,e){var r;this.logger.info("Spotlight::setActiveTab",{spotlight:{currentTab:{id:t.id,type:t.type}}}),this.selfActiveTab=t,e===0&&this.emit("selfTabUpdate",t),(r=a(this,Di).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,Ro).broadcastMessage("spotlight",{userId:a(this,Di).userId,currentTab:this.selfActiveTab})}},Jn=new WeakMap,Co=new WeakSet,Zh=function(){return a(this,Jn).getValue("connectionHandler")},Di=new WeakMap,Ro=new WeakMap,BS);gh=eO([lt("0800")],gh);function tO(s){let t="",e=[""];const r=[e];let i=0,n=0,o=!0,c;for(c of s)c==='"'?(o&&c===t&&(e[i]+=c),o=!o):c===","&&o?c=e[++i]="":c===`
13
+ `&&o?(t==="\r"&&(e[i]=e[i].slice(0,-1)),e=r[++n]=[c=""],i=0):e[i]+=c,t=c;return r}var sO=Object.defineProperty,rO=Object.getOwnPropertyDescriptor,_f=(s,t,e,r)=>{for(var i=r>1?void 0:r?rO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&sO(t,e,i),i};let Nr=(FS=class extends Dt{constructor(t){const e=t.getValue("logger");super(e);p(this,"transcripts");g(this,Io,void 0);f(this,Io,t),this.transcripts=[]}get telemetry(){return a(this,Io).getValue("telemetry")}static async init(t,e){const r=new Nr(t),i=t.getValue("logger");try{e&&r.getActiveTranscript()}catch(n){i.error("Error fetching active transcriptions ",n)}return r}static parseTranscript(t,e=!1){if(!t)return;const[[r,i,n,o,c,d]]=tO(t);return{id:vn(),name:c,peerId:i,userId:n,customParticipantId:o,transcript:d,isPartialTranscript:e,date:new Date(parseInt(r,10)*1e3)}}static parseTranscripts(t){return t?t.split(`
14
+ `).map(e=>Nr.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=Pt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Nr.parseTranscripts(e)}catch(t){}}async onTranscript(t){var r;const e=this.transcripts.filter(({peerId:i})=>i===t.peerId);if((r=e==null?void 0:e.at(-1))!=null&&r.isPartialTranscript){const i=e.at(-1);i.transcript=t.transcript,i.isPartialTranscript=t.isPartialTranscript,this.emit("transcript",i);return}this.transcripts=[...this.transcripts,t],this.emit("transcript",t)}},Io=new WeakMap,FS);_f([E.trace("Ai.getActiveTranscript")],Nr.prototype,"getActiveTranscript",1),Nr=_f([lt("0000")],Nr);var iO=Object.defineProperty,nO=Object.getOwnPropertyDescriptor,aO=(s,t,e,r)=>{for(var i=r>1?void 0:r?nO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&iO(t,e,i),i};const kf=(HS=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");g(this,jr,void 0);g(this,Kn,void 0);p(this,"aiSocketHandler");g(this,Ut,void 0);f(this,Ut,s),this.meta=new gh(s,t,t.config.viewType,e,n),this.ai=r,f(this,jr,t),f(this,Kn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Ut).getValue("telemetry")}get logger(){return a(this,Ut).getValue("logger")}static async init(s,t,e,r,i){const n=await Nr.init(s,t.permissions.transcriptionEnabled);return new kf(s,t,e,n,r,i)}conditionallySetActiveTab(s){var t;s!=null&&s.currentTab&&((t=this.meta.selfActiveTab)==null?void 0:t.id)!==s.currentTab.id&&(this.meta.setSelfActiveTab(s.currentTab,Pf.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Ut).getValue("peerSessionStore").on(k.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Ut).getValue("peerSessionStore").on(k.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Ut).getValue("peerSessionStore").on(k.ROOM_STATE,({createdAt:s,roomUuid:t})=>{const e=this.meta.meetingStartedTimestamp;if(t&&(this.meta.sessionId=t),s&&!e){const r=new Date(s*1e3);this.meta.meetingStartedTimestamp=r,this.meta.emit("meetingStartTimeUpdate",{meetingStartedTimestamp:this.meta.meetingStartedTimestamp})}}),a(this,Ut).getValue("peerSessionStore").on(k.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,jr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Kn).broadcastMessage("spotlight",{userId:a(this,jr).userId,currentTab:this.meta.selfActiveTab})),a(this,Ut).getValue("peerSessionStore").on(k.PEER_JOINED_INTERNAL,async s=>{a(this,jr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Kn).broadcastToPeers("spotlight",[s.id],{userId:a(this,jr).userId,currentTab:this.meta.selfActiveTab})}),a(this,Ut).getValue("peerSessionStore").on(k.ROOM_MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),a(this,Ut).getValue("peerSessionStore").on(k.MESSAGE,s=>{var e,r;let t;if("type"in s){if(s.type!=="spotlight")return;t={...s,...s.payload}}else if("roomMessageType"in s){if(s.roomMessageType!=="spotlight")return;t=s}else return;this.logger.info("Spotlight Assertion Received",{spotlight:{spotlighter:{id:t.userId},currentTab:{id:(e=t.currentTab)==null?void 0:e.id,type:(r=t.currentTab)==null?void 0:r.type}}}),this.conditionallySetActiveTab(t)}),this.aiSocketHandler.on(U.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Nr.parseTranscript(e,r)}catch(d){this.logger.error(`Failed to parse transcript: ${e}`,d)}if(!i){this.logger.warn("Received empty transcript data");return}this.ai.onTranscript(i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},jr=new WeakMap,Kn=new WeakMap,Ut=new WeakMap,HS);let Cf=kf;aO([E.trace("MetaController.setupEvents")],Cf.prototype,"setupEvents",1);const io={},tr={executeWithLock({methodName:s,lockName:t,timeout:e}){return(r,i,n)=>{const o=n.value;return n.value=function(...d){var y,w;const l=(w=(this==null?void 0:this.peerId)||((y=d[0])==null?void 0:y.authToken))!=null?w:"",u=`${t}-${l}`,h=this==null?void 0:this.logger;if(io[u]){const _=new Error(`Unsupported concurrent calls on method: ${s}.`);throw _.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:_.stack},locker:{methodName:s,lockName:u}}),_}io[u]=!0;const m=setTimeout(()=>delete io[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete io[u],clearTimeout(m)}).catch(()=>{delete io[u],clearTimeout(m)}),S},n}}};var oO=Object.defineProperty,cO=Object.getOwnPropertyDescriptor,vi=(s,t,e,r)=>{for(var i=r>1?void 0:r?cO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&oO(t,e,i),i};class Vr extends Dt{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);g(this,Mo);g(this,zn);g(this,es,void 0);g(this,fl,void 0);g(this,oe,void 0);g(this,Ao,void 0);g(this,Ns,void 0);g(this,Ye,void 0);f(this,Ye,e),f(this,es,n),f(this,fl,o),f(this,oe,r),f(this,Ao,i),f(this,Ns,[]),this.setupEvents()}get telemetry(){return a(this,Ye).getValue("telemetry")}get status(){return a(this,Ye).getValue("stageStatus")}setupEvents(){const e={[k.GET_STAGE_REQUESTS]:async n=>{f(this,Ns,n)},[k.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Ns).length,{stageRequests:c}=this.getAccessRequests();(n||c.length>o)&&this.emit("newStageRequest",{count:c.length}),this.emit("stageAccessRequestUpdate",c)}},r=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Ye).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Ye).getValue("peerSessionStore").removeListener(n,o)})};a(this,oe).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,oe).permissions.acceptStageRequests?(r(),a(this,es).getStageRequests()):(i(),f(this,Ns,[]),this.emit("stageAccessRequestUpdate",a(this,Ns))))}),a(this,oe).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!a(this,oe).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new R("You do not have permission to perform this action","2001");const e=a(this,Ao).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Ns,e),{stageRequests:a(this,Ns)}}async requestAccess(){if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new R(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,oe).permissions.stageAccess===G.Allowed){L(this,zn,cu).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,es).requestAccess(),L(this,zn,cu).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");a(this,es).cancelRequestAccess(),L(this,zn,cu).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,oe).roomJoined)throw new R("Can`t grant for participant without joining room");if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!a(this,oe).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new R("You do not have permission to perform this action","2001");return a(this,es).grantAccess(e)}denyAccess(e){if(!a(this,oe).roomJoined)throw new R("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!a(this,oe).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new R("You do not have permission to perform this action","2001");return a(this,es).denyAccess(e)}get peerId(){return a(this,Ye).getValue("peerId")}async join(){const e=a(this,Ye).getValue("viewType");if(this.status==="ON_STAGE")throw new R("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,oe).permissions.stageAccess===G.NotAllowed)throw new R(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Ye).setValue("stageStatus","ON_STAGE",!1),await a(this,es).joinStage(),e===Ws.Livestream){await a(this,Ye).getValue("selfController").joinRoom();return}a(this,Ye).notify("stageStatus"),a(this,oe).audioEnabled&&a(this,Mo,ep).shareMic(a(this,oe).audioTrack),a(this,oe).videoEnabled&&a(this,Mo,ep).shareWebcam(a(this,oe).videoTrack)}async leave(){if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new R(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,oe).setIsPinned(!1),a(this,Ye).setValue("stageStatus","OFF_STAGE",!1),await a(this,es).leaveStage(a(this,oe).userId);try{await a(this,Ye).getValue("peerSessionStore").emitAsync(k.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Ye).notify("stageStatus")}async kick(e){if(!a(this,oe).roomJoined)throw new R("Can`t kick participant without joining room","2005");if(!a(this,oe).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new R("Stage is disabled","2003");if(!a(this,oe).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new R("You do not have permissions for kick","2001");return a(this,es).kick(e)}}es=new WeakMap,fl=new WeakMap,oe=new WeakMap,Ao=new WeakMap,Ns=new WeakMap,Ye=new WeakMap,Mo=new WeakSet,ep=function(){return a(this,Ye).getValue("roomNodeClient")},zn=new WeakSet,cu=async function(e){this.status!==e&&a(this,Ye).setValue("stageStatus",e)},vi([E.trace("Stage.getStageRequests")],Vr.prototype,"getAccessRequests",1),vi([E.trace("Stage.requestAccess")],Vr.prototype,"requestAccess",1),vi([E.trace("Stage.cancelRequestAccess")],Vr.prototype,"cancelRequestAccess",1),vi([E.trace("Stage.grantAccess")],Vr.prototype,"grantAccess",1),vi([E.trace("Stage.denyAccess")],Vr.prototype,"denyAccess",1),vi([tr.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],Vr.prototype,"join",1),vi([E.trace("Stage.leaveStage")],Vr.prototype,"leave",1);function dO(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function fh(s){switch(s){case Ys.UNSPECIFIED:return"OFF_STAGE";case Ys.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Ys.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Ys.OFF_STAGE:return"OFF_STAGE";case Ys.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var lO=Object.defineProperty,uO=Object.getOwnPropertyDescriptor,hO=(s,t,e,r)=>{for(var i=r>1?void 0:r?uO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&lO(t,e,i),i};class Rf{constructor(t,e,r,i,n){p(this,"stage");g(this,Gr,void 0);g(this,fs,void 0);g(this,Wr,void 0);g(this,Oo,0);g(this,vt,void 0);f(this,vt,t),this.stage=new Vr(t,i,n,e,r),f(this,Wr,e),f(this,Gr,i),f(this,fs,n),this.setupEvents()}get telemetry(){return a(this,vt).getValue("telemetry")}get logger(){return a(this,vt).getValue("logger")}setupEvents(){a(this,vt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,Wr).on(U.grantStageAccess,()=>{a(this,Gr).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,Wr).on(U.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,Gr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,Wr).on(U.denyStageAccess,()=>{a(this,Gr).permissions.stageAccess!==G.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,Wr).on(U.getStageRequests,async t=>{var r;if(a(this,Gr).permissions.stageAccess!==G.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,vt).getValue("peerSessionStore").emitAsync(k.GET_STAGE_REQUESTS,e),a(this,Oo)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,Oo,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,fs).joined.toArray().filter(e=>e.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(e=>({displayName:e.name,userId:e.userId,peerId:e.id}))}async setStageStatus(t){this.stage.status!==t&&a(this,vt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=fh(t.stageType),r=a(this,vt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,vt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.join();break;case 2:case 3:this.setStageStatus(r);break;case 0:case 4:default:a(this,vt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,fs).joined.get(t.peerId),r=a(this,fs).viewMode==="ACTIVE_GRID";if(!e){this.logger.warn("err::peerStageStatusUpdate: participant not found");return}switch(t.stageType){case 1:e.setStageStatus("ON_STAGE"),r&&a(this,vt).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:a(this,fs).viewMode,page:a(this,fs).currentPage});break;case 2:e.setStageStatus("ACCEPTED_TO_JOIN_STAGE");break;case 3:e.setStageStatus("REQUESTED_TO_JOIN_STAGE");break;case 0:case 4:default:e.setStageStatus("OFF_STAGE"),r&&a(this,vt).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:a(this,fs).viewMode,page:a(this,fs).currentPage});break}a(this,vt).getValue("peerSessionStore").emit(k.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Gr=new WeakMap,fs=new WeakMap,Wr=new WeakMap,Oo=new WeakMap,vt=new WeakMap,hO([E.trace("Stage.setupEvents")],Rf.prototype,"setupEvents",1);var pO=Object.defineProperty,mO=Object.getOwnPropertyDescriptor,Sh=(s,t,e,r)=>{for(var i=r>1?void 0:r?mO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&pO(t,e,i),i};let no=(qS=class extends kn{constructor(t,e,r,i){const n=t.getValue("logger");super(n);p(this,"name");p(this,"icon");p(this,"id");p(this,"permissions");g(this,Ni,void 0);g(this,lr,void 0);g(this,Do,void 0);g(this,No,void 0);g(this,Vi,void 0);p(this,"active");p(this,"enabledBy");f(this,Do,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,f(this,No,e.component),this.permissions=e.permissions,f(this,Ni,i),f(this,lr,r),this.active=!1,this.enabledBy=""}get component(){return a(this,No)}get telemetry(){return a(this,Do).getValue("telemetry")}set activePluginsStore(t){f(this,lr,t)}activateForSelf(){f(this,Vi,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){f(this,Vi,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;if(!this.active&&(t=this.permissions)!=null&&t.canActivate){if(!a(this,lr))throw new R("Cannot activate plugin: active plugins store is not available yet.","0604");await a(this,lr).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,Ni).id}),this.enabledBy=a(this,Ni).id,this.activateForSelf(),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}})}}async deactivate(){var e;if(!this.active||!((e=this.permissions)!=null&&e.canDeactivate)&&this.enabledBy!==a(this,Ni).id)return;if(!a(this,lr))throw new R("Cannot deactivate plugin: active plugins store is not available yet.","0604");const t=a(this,Vi)?new Date().getTime()-a(this,Vi).getTime():0;await a(this,lr).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Ni=new WeakMap,lr=new WeakMap,Do=new WeakMap,No=new WeakMap,Vi=new WeakMap,qS);Sh([E.trace("Plugin.activatePlugin")],no.prototype,"activate",1),Sh([E.trace("Plugin.deactivatePlugin")],no.prototype,"deactivate",1),no=Sh([lt("0600")],no);class If extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();g(this,$e,void 0);g(this,Li,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");f(this,$e,new kn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,Li,new Map)}emit(e,...r){return a(this,$e).emit(e,...r)}on(e,r){return a(this,$e).on(e,r)}addListener(e,r){return a(this,$e).addListener(e,r)}off(e,r){return a(this,$e).off(e,r)}once(e,r){return a(this,$e).once(e,r)}prependListener(e,r){return a(this,$e).prependListener(e,r)}prependOnceListener(e,r){return a(this,$e).prependOnceListener(e,r)}removeListener(e,r){return a(this,$e).removeListener(e,r)}removeAllListeners(e){return a(this,$e).removeAllListeners(e)}listeners(e){return a(this,$e).listeners(e)}listenerCount(e){return a(this,$e).listenerCount(e)}getMaxListeners(){return a(this,$e).getMaxListeners()}setMaxListeners(e){return a(this,$e).setMaxListeners(e)}eventNames(){return a(this,$e).eventNames()}add(e,r=!0){return this.set(e.id,e,r)}set(e,r,i=!0){const n=super.set(e,r),o=(c,...d)=>{this.emit(c,r,...d)};return a(this,Li).set(e,o),r.on("*",o),i&&a(this,$e).emit(this.onAddEvent,r),n}delete(e,r=!0,i=!1){const n=this.get(e);if(!n)return!1;n.removeListener("*",a(this,Li).get(e));const o=super.delete(e);return i&&n.removeAllListeners(),r&&a(this,$e).emit(this.onDeleteEvent,n),o}clear(e=!0,r=!1){this.forEach(n=>{n.removeListener("*",a(this,Li).get(n.id)),r&&n.removeAllListeners()});const i=super.clear();return e&&a(this,$e).emit(this.onClearEvent),i}toArray(){return Array.from(this.values())}}$e=new WeakMap,Li=new WeakMap;class Af extends If{constructor(t){super({onAddEvent:"pluginAdded",onDeleteEvent:"pluginDeleted"},t)}add(t,e=!0){return super.add(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}var gO=Object.defineProperty,fO=Object.getOwnPropertyDescriptor,SO=(s,t,e,r)=>{for(var i=r>1?void 0:r?fO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&gO(t,e,i),i};let vh=class{constructor(s){p(this,"all");p(this,"active");this.all=new Af(s),this.active=new Af(s)}};vh=SO([lt("0600")],vh);var vO=Object.defineProperty,TO=Object.getOwnPropertyDescriptor,yO=(s,t,e,r)=>{for(var i=r>1?void 0:r?TO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&vO(t,e,i),i};const Mf=(jS=class{constructor(s,t,e,r){g(this,Sl);g(this,Vo);g(this,Lo);g(this,xo);p(this,"plugins");g(this,Ss,void 0);g(this,Yn,void 0);g(this,Jr,void 0);g(this,xi,null);f(this,Jr,s),this.plugins=t,f(this,Yn,e),f(this,Ss,r),this.setupEvents()}get telemetry(){return a(this,Jr).getValue("telemetry")}get logger(){return a(this,Jr).getValue("logger")}static async init(s,t,e,r){var l,u;const i=s.getValue("logger"),n=s.getValue("connectionHandler"),o=new vh(i);let c;n.socketState.state==="connected"?(i.info("Creating active plugins store immediately. Socket is already connected."),c=await r.create(Fu,!0)):i.info("Deferring active plugins store creation until socket connects."),t.forEach(h=>{const m=new no(s,h,c,e);o.all.add(m)});const d=new Mf(s,o,r,c);return c?L(l=d,xo,rp).call(l):L(u=d,Sl,iv).call(u),d}cleanup(){L(this,Vo,tp).call(this)}setupEvents(){this.plugins.all.on("stateUpdate",({active:s,id:t})=>{if(s){this.plugins.active.add(this.plugins.all.get(t));return}this.plugins.active.delete(t)}),a(this,Jr).getValue("peerSessionStore").onAsync(k.SOCKET_SERVICE_ROOM_JOINED,async()=>{var t,e;if(((e=(t=this.plugins.active)==null?void 0:t.toArray())!=null?e:[]).forEach(r=>{r.deactivateForSelf()}),!a(this,Ss)){this.logger.warn("Active plugins store not available yet on ROOM_JOINED. Sync will be performed when store is created.");return}await L(this,Lo,sp).call(this),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")})}},Ss=new WeakMap,Yn=new WeakMap,Jr=new WeakMap,xi=new WeakMap,Sl=new WeakSet,iv=function(){const s=a(this,Jr).getValue("peerSessionStore"),t=async e=>{if(e.state==="connected"&&!a(this,Ss))try{f(this,Ss,await a(this,Yn).create(Fu,!0)),L(this,Vo,tp).call(this),this.plugins.all.toArray().forEach(r=>{r.activePluginsStore=a(this,Ss)}),L(this,xo,rp).call(this),this.logger.info("Active plugins store created after socket connected"),await L(this,Lo,sp).call(this)}catch(r){this.logger.error("Failed to create active plugins store after socket connected, will retry on next reconnect",{error:r})}};s.on(k.SOCKET_STATE_UPDATE,t),f(this,xi,()=>{s.off(k.SOCKET_STATE_UPDATE,t)})},Vo=new WeakSet,tp=function(){a(this,xi)&&(a(this,xi).call(this),f(this,xi,null))},Lo=new WeakSet,sp=async function(){try{await a(this,Yn).refresh(a(this,Ss).name)}catch(t){this.logger.error("Failed to refresh active plugins store, syncing from stale data.",{error:t})}const s=a(this,Ss).getAll();Object.entries(s).forEach(([t,e])=>{if(!e)return;const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store entry.`);return}r.active||(r.enabledBy=e.enabledBy,r.activateForSelf())})},xo=new WeakSet,rp=function(){a(this,Ss).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`Plugin '${t}' not found in plugins.all, ignoring store update.`);return}!e&&r.active&&r.deactivateForSelf(),e&&!r.active&&(r.enabledBy=e.enabledBy,r.activateForSelf())})})},jS);let Of=Mf;yO([E.trace("PluginController.setupEvents")],Of.prototype,"setupEvents",1);class EO{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");g(this,Uo,void 0);this.mediaJoined=!1,this.socketJoined=!1,this.socketJoinAttempted=!1,this.mediaJoinAttempted=!1,this.socketState={state:void 0,reconnected:!1,reconnectionAttempt:void 0},this.mediaState={recv:void 0,send:void 0},f(this,Uo,t)}get joinAttempted(){return this.mediaJoinAttempted||this.socketJoinAttempted}get roomJoined(){return this.mediaJoined&&this.socketJoined}updateSocketConnectionState(t,e){let r;const{reconnected:i}=this.socketState;switch(t){case"connected":r={state:"connected",reconnected:i,reconnectionAttempt:void 0};break;case"disconnected":r={state:"disconnected",reconnected:!1,reconnectionAttempt:0},this.socketJoined=!1;break;case"reconnected":r={state:"connected",reconnected:!0,reconnectionAttempt:void 0};break;case"reconnecting":r={state:"reconnecting",reconnected:i,reconnectionAttempt:0};break;case"reconnectAttempt":r={state:"reconnecting",reconnected:i,reconnectionAttempt:e};break;case"failed":r={state:"failed",reconnected:i,reconnectionAttempt:void 0},this.socketJoined=!1;break}r&&(a(this,Uo).getValue("peerSessionStore").emit(k.SOCKET_STATE_UPDATE,r),this.socketState=r)}}Uo=new WeakMap;var bO=Object.defineProperty,wO=Object.getOwnPropertyDescriptor,ao=(s,t,e,r)=>{for(var i=r>1?void 0:r?wO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&bO(t,e,i),i};const Df="Cannot start recording: another recording is already in progress.";let Ti=(GS=class extends Dt{constructor(t,e){const r=t.getValue("logger");super(r);g(this,Zn);g(this,Qn,void 0);g(this,Xn,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,Xn,t),f(this,Qn,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"}get telemetry(){return a(this,Xn).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,Qn).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new R("User does not have permission to start recording","1001");if((t==null?void 0:t.allowMultiple)!==!0&&(this.recordingState==="STARTING"||this.recordingState==="RECORDING"||this.recordingState==="STOPPING"))throw this.logger.error("Recording::start::recording_in_progress",{recording:{state:this.recordingState}}),new R(Df,"1005");try{const e=Pt(),{recording:r={}}=a(this,Xn).getValue("defaults"),i=await e.startRecording(r,t==null?void 0:t.allowMultiple);this.updateRecordings([...this.recordings,{id:i,state:"STARTING",type:"BROWSER"}])}catch(e){throw this.logger.error("Recording::start::recording_failed_to_start",{error:e}),e instanceof xd&&e.status===409?new R(Df,"1005"):new R("Error while starting recording","1000",this.logger)}}async stop(t){await L(this,Zn,du).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await L(this,Zn,du).call(this,"pause",["RECORDING"],t)}async resume(t){await L(this,Zn,du).call(this,"resume",["PAUSED"],t)}},Qn=new WeakMap,Xn=new WeakMap,Zn=new WeakSet,du=async function(t,e,r){if(!a(this,Qn).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new R("User does not have permission to stop recording","1001");let i=[];if(r!==void 0){const n=this.recordings.find(o=>o.id===r);if(n===void 0)throw new R("Could not find the specified recording","1004");if(e.includes(n.state)){this.logger.error("Recording::stop::recording_not_in_expected_state",{recording:{state:n.state}});return}i.push(n)}else i=this.recordings.filter(n=>e.includes(n.state));i.forEach(async n=>{const o=n.state;t==="stop"&&(n.state="STOPPING",this.emit("recordingUpdate","STOPPING"));try{await Pt().updateRecording(n.id,t)}catch(c){throw this.logger.error("Recording::stop::recording_failed_to_stop",{error:c}),n.state!==o&&(n.state=o,this.emit("recordingUpdate",o)),new R("Error while stopping recording","1000",this.logger)}})},GS);ao([E.trace("Recording.start")],Ti.prototype,"start",1),ao([E.trace("Recording.stop")],Ti.prototype,"stop",1),ao([E.trace("Recording.stop")],Ti.prototype,"pause",1),ao([E.trace("Recording.stop")],Ti.prototype,"resume",1),Ti=ao([lt("1000")],Ti);var PO=Object.defineProperty,_O=Object.getOwnPropertyDescriptor,kO=(s,t,e,r)=>{for(var i=r>1?void 0:r?_O(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&PO(t,e,i),i};class Nf{constructor(t,e,r){p(this,"recording");p(this,"room");g(this,Ui,void 0);f(this,Ui,t),this.recording=new Ti(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,Ui).getValue("telemetry")}get logger(){return a(this,Ui).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case Si.BROWSER:e="BROWSER";break;case Si.COMPOSITE:e="COMPOSITE";break;case Si.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,Ui).getValue("peerSessionStore").on(k.ROOM_STATE,t=>{t.activeRecordings.length!==0?this.recording.updateRecordings(t.activeRecordings.map(e=>{const r=this.getRecordingTypeFromProtoType(e.recordingType);return{id:e.recordingId,state:e.recordingStatus,type:r}})):this.recording.recordings.length&&this.recording.updateRecordings([])}),this.room.on(U.recordingStarted,t=>{let e=!1;const r=[...this.recording.recordings];if(r.forEach(i=>{i.id===t.recordingId&&(e=!0,i.state="RECORDING")}),e===!1){const i=this.getRecordingTypeFromProtoType(t.recordingType);r.push({id:t.recordingId,state:"RECORDING",type:i})}this.recording.updateRecordings(r)}),this.room.on(U.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(U.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Ui=new WeakMap,kO([E.trace("RecordingController.setupEvents")],Nf.prototype,"setupEvents",1);class CO{constructor(t){g(this,$i,void 0);f(this,$i,t)}hasFeature(t){return a(this,$i).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,$i).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,$i).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}$i=new WeakMap;class Th{constructor(t,e,r,i){p(this,"authToken");p(this,"logger");p(this,"features");p(this,"browserSpecs");p(this,"callStats");this.authToken=t,this.logger=e,this.features=r,this.browserSpecs=Te,this.callStats=i}static init(t){return new Th(t.getValue("authToken"),t.getValue("logger"),new CO(t),t.getValue("callstats"))}}class yh{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=Th.init(t);return new yh(e)}}var RO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,Vt=(s,t,e,r)=>{for(var i=r>1?void 0:r?IO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&RO(t,e,i),i};class _t extends kn{constructor(e,r,i=Bd,n=!0){const o=e.getValue("logger");super(o);g(this,je,void 0);g(this,Ee,void 0);g(this,Se,void 0);g(this,ur,void 0);g(this,ts,void 0);g(this,$o,void 0);g(this,Ne,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");f(this,Ne,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,je,new Hf(e,r)),f(this,Ee,new iD(e,a(this,je),void 0,i)),f(this,Se,new uD(e,a(this,je),void 0,i)),f(this,ts,new cD(a(this,Ne),a(this,je))),f(this,ur,new aD(e,a(this,je))),f(this,$o,n),a(this,Ee).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Ee).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,Se).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,Se).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,ts).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Ne).getValue("telemetry")}set context(e){f(this,Ne,e)}async onVisibilityChange(){a(this,Ne).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Ne).getValue("callstats").browserBackgrounded():(a(this,Ne).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Ne).getValue("callstats").audioOn():a(this,Ne).getValue("callstats").audioOff(),r?a(this,Ne).getValue("callstats").videoOn():a(this,Ne).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,je).getAudioAndVideoTrack(a(this,Ee).userSelectedDevice,a(this,Se).userSelectedDevice);i=c.audioTrack,n=c.videoTrack}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio video tracks",{error:c})}if(!i&&e)try{i=await a(this,je).getAudioTrack(!1,a(this,Ee).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,je).getVideoTrack(a(this,Se).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Ne).getValue("callstats").audioOff(),r&&!n&&a(this,Ne).getValue("callstats").videoOff(),await a(this,Ee).setMediaTrack(i),await a(this,Se).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Ne).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Ne).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,ur).currentDevice)!=null&&o.deviceId&&a(this,Ne).getValue("callstats").selectedDevice("SPEAKER",a(this,ur).currentDevice),a(this,je).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,Ee).currentDevice,video:a(this,Se).currentDevice,speaker:a(this,ur).currentDevice}}get permissions(){return a(this,je).permissions}getAllDevices(){return a(this,je).getAvailableDevices()}getDeviceById(e,r){return a(this,je).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Ee).mediaTrack}get audioTrack(){return a(this,Ee).transformedMediaTrack}get audioEnabled(){return a(this,Ee).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,Ee).enableTrack(!1,e):await a(this,Ee).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,Ee).mediaTrack&&!a(this,Ee).isCustomTrack?a(this,Ee).muteTrack():a(this,Ee).disableTrack()}getAudioDevices(e){return a(this,je).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,Ee).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ne).getValue("callstats").selectedDevice("AUDIO",e),this.emit("AUDIO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async setupSpeaker(){const{speaker:e}=this.getCurrentDevices();await a(this,ur).setPreferredSpeaker();const{speaker:r}=this.getCurrentDevices();(e==null?void 0:e.deviceId)!==(r==null?void 0:r.deviceId)&&r&&this.emit("DEVICE_CHANGE",{device:r})}async setSpeakerDevice(e,{saveDevicePreference:r}){await a(this,ur).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ne).getValue("callstats").selectedDevice("SPEAKER",e),this.emit("DEVICE_CHANGE",{device:e})}onVideoTrackChanged(){this.emit("VIDEO_TRACK_CHANGE")}onVideoTrackEnded(){this.emit("VIDEO_TRACK_CHANGE")}get rawVideoTrack(){return a(this,Se).mediaTrack}get videoTrack(){return a(this,Se).transformedMediaTrack}get videoEnabled(){return a(this,Se).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,Se).enableTrack(!1,e):await a(this,Se).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,Se).disableTrack()}getVideoDevices(e){return a(this,je).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,Se).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Ne).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,Se).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,ts).audioMediaTrack,video:a(this,ts).videoMediaTrack}}get screenShareEnabled(){return a(this,ts).trackEnabled}async enableScreenShare(){await a(this,ts).enableScreenShare()}async disableScreenShare(){a(this,ts).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,ts).updateConstraints(e)}getSpeakerDevices(e){return a(this,je).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Ee).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Ee).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Ee).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,Se).addMiddleware(e)}removeVideoMiddleware(e){return a(this,Se).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,Se).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,Se).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Ee).disableTrack(),a(this,Se).disableTrack(),a(this,Se).terminateMiddlewareWebWorker(),a(this,ts).disableScreenShare(),a(this,je).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,$o))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!Bd(c)&&(c.kind==="audioinput"&&((d=this.audioTrack)==null?void 0:d.enabled)===!0?await this.setAudioDevice(c,{saveDevicePreference:!1}):c.kind==="audiooutput"&&(i=!0,await this.setSpeakerDevice(c,{saveDevicePreference:!1})))}),i||(o=e==null?void 0:e.removed)==null||o.forEach(async c=>{var d;if(c.kind==="audiooutput"&&((d=this.getCurrentDevices().speaker)==null?void 0:d.deviceId)===c.deviceId){const l=await this.getSpeakerDevices();(l==null?void 0:l.length)>0&&await this.setSpeakerDevice(l[0],{saveDevicePreference:!1})}})}removeAllTracks(){this.destruct()}removeAudioTrack(){a(this,Ee).disableTrack()}removeVideoTrack(){a(this,Se).disableTrack(),a(this,Se).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}je=new WeakMap,Ee=new WeakMap,Se=new WeakMap,ur=new WeakMap,ts=new WeakMap,$o=new WeakMap,Ne=new WeakMap,Vt([E.trace("MediaHandler.setupStreams")],_t.prototype,"setupStreams",1),Vt([E.trace("MediaHandler.enableAudio")],_t.prototype,"enableAudio",1),Vt([E.trace("MediaHandler.disableAudio")],_t.prototype,"disableAudio",1),Vt([E.trace("MediaHandler.setAudioDevice")],_t.prototype,"setAudioDevice",1),Vt([E.trace("MediaHandler.enableVideo")],_t.prototype,"enableVideo",1),Vt([E.trace("MediaHandler.disableVideo")],_t.prototype,"disableVideo",1),Vt([E.trace("MediaHandler.setVideoDevice")],_t.prototype,"setVideoDevice",1),Vt([E.trace("MediaHandler.updateVideoConstraints")],_t.prototype,"updateVideoConstraints",1),Vt([E.trace("MediaHandler.enableScreenShare")],_t.prototype,"enableScreenShare",1),Vt([E.trace("MediaHandler.disableScreenShare")],_t.prototype,"disableScreenShare",1),Vt([E.trace("MediaHandler.updateScreenshareConstraints")],_t.prototype,"updateScreenshareConstraints",1),Vt([E.trace("MediaHandler.destruct")],_t.prototype,"destruct",1),Vt([E.trace("MediaHandler.onDeviceChange")],_t.prototype,"onDeviceChange",1);function $d(s,t,e){switch(!0){case Te.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case Te.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case Te.isFirefox():switch(t){case"NotFoundError":case"NotReadableError":return"SYSTEM_DENIED";case"NotAllowedError":return"DENIED";case"AbortError":default:return"COULD_NOT_START"}default:return"COULD_NOT_START"}}const AO=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Bd(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=Te._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:AO.some(i=>t==null?void 0:t.includes(i))}async function MO(s,t,e){if(!(t!=null&&t.length))return e;const r=s.getValue("logger"),i=new AudioContext,n=await Promise.all(t==null?void 0:t.map(d=>d(i))),o=i.createMediaStreamSource(new MediaStream([e])),c=i.createMediaStreamDestination();try{let d=o;for(let l=0;l<n.length;l+=1)d.connect(n[l]),d=n[l];d.connect(c)}catch(d){return r.error("getTransformedAudioTrack::middleware_execution_failed",{error:d}),e}return c.stream.getAudioTracks()[0]}const OO=s=>(t,e)=>(s.set(t,e),e),Vf=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Lf=536870912,xf=Lf*2,DO=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<xf?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Lf){for(;e.has(i);)i=Math.floor(Math.random()*xf);return s(e,i)}if(e.size>Vf)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;e.has(i);)i=Math.floor(Math.random()*Vf);return s(e,i)},Uf=new WeakMap,NO=OO(Uf),Fd=DO(NO,Uf),VO=s=>s.method!==void 0&&s.method==="call",LO=s=>s.error===null&&typeof s.id=="number",Hd=((s,t)=>{let e=null;return()=>{if(e!==null)return e;const r=new Blob([t],{type:"application/javascript; charset=utf-8"}),i=URL.createObjectURL(r);return e=s(i),setTimeout(()=>URL.revokeObjectURL(i)),e}})(s=>{const t=new Map([[0,()=>{}]]),e=new Map([[0,()=>{}]]),r=new Map,i=new Worker(s);return i.addEventListener("message",({data:l})=>{if(VO(l)){const{params:{timerId:u,timerType:h}}=l;if(h==="interval"){const m=t.get(u);if(typeof m=="number"){const S=r.get(m);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof m!="undefined")m();else throw new Error("The timer is in an undefined state.")}else if(h==="timeout"){const m=e.get(u);if(typeof m=="number"){const S=r.get(m);if(S===void 0||S.timerId!==u||S.timerType!==h)throw new Error("The timer is in an undefined state.")}else if(typeof m!="undefined")m(),e.delete(u);else throw new Error("The timer is in an undefined state.")}}else if(LO(l)){const{id:u}=l,h=r.get(u);if(h===void 0)throw new Error("The timer is in an undefined state.");const{timerId:m,timerType:S}=h;r.delete(u),S==="interval"?t.delete(m):e.delete(m)}else{const{error:{message:u}}=l;throw new Error(u)}}),{clearInterval:l=>{const u=Fd(r);r.set(u,{timerId:l,timerType:"interval"}),t.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"interval"}})},clearTimeout:l=>{const u=Fd(r);r.set(u,{timerId:l,timerType:"timeout"}),e.set(l,u),i.postMessage({id:u,method:"clear",params:{timerId:l,timerType:"timeout"}})},setInterval:(l,u=0)=>{const h=Fd(t);return t.set(h,()=>{l(),typeof t.get(h)=="function"&&i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}})}),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"interval"}}),h},setTimeout:(l,u=0)=>{const h=Fd(e);return e.set(h,l),i.postMessage({id:null,method:"set",params:{delay:u,now:performance.now(),timerId:h,timerType:"timeout"}}),h}}},`(()=>{"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})}}))})();`),$f=s=>Hd().clearInterval(s),xO=s=>Hd().clearTimeout(s),Bf=(s,t)=>Hd().setInterval(s,t),Ff=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:$f,clearTimeout:xO,setInterval:Bf,setTimeout:(s,t)=>Hd().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class UO{constructor(t){g(this,Bi,void 0);g(this,Bo,void 0);f(this,Bo,t)}get logger(){return a(this,Bo).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Bi))try{$f(a(this,Bi)),f(this,Bi,void 0)}catch(t){this.logger.debug("WorkerTimers::terminateMiddlewareWebWorker::failed")}}async getTransformedVideoTrack(t,e,r){if(!(t!=null&&t.length))return e;const i=document.createElement("canvas"),n=await Promise.all(t==null?void 0:t.map(m=>m({canvas:i,WorkerTimers:Ff})));if(r.disablePerFrameCanvasRendering){const S=i.captureStream().getVideoTracks()[0];return Object.defineProperty(S,"originalSettings",{value:e.getSettings()}),S}const o=document.createElement("video"),c=new MediaStream;c.addTrack(e);const d=i.getContext("2d");o.srcObject=c,o.autoplay=!0,this.terminateMiddlewareWebWorker();const l=async()=>{if(e.enabled===!1||e.readyState==="ended"){this.terminateMiddlewareWebWorker(),o.remove(),i.remove();return}try{d.drawImage(o,0,0);for(let m=0;m<n.length;m+=1)typeof n[m]=="function"&&await n[m](i,d)}catch(m){this.logger.error("getTransformedVideoTrack::middleware_execution_failed",{error:m})}};try{o.play()}catch(m){}o.addEventListener("play",()=>{i.width=o.width||e.getSettings().width,i.height=o.width||e.getSettings().height,f(this,Bi,Bf(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Bi=new WeakMap,Bo=new WeakMap;const $O={qvga:{width:{ideal:320},height:{ideal:240},frameRate:{ideal:30}},vga:{width:{ideal:640},height:{ideal:480},frameRate:{ideal:30}},hd:{width:{ideal:1280},height:{ideal:720},frameRate:{ideal:30}},fhd:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},uhd:{width:{ideal:3840},height:{ideal:2160},frameRate:{ideal:30}}},BO=[[320,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[640,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2}]],[1280,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[1920,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]],[3840,[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]]],FO=(s,t)=>{var d,l,u;const e=(d=s==null?void 0:s.getValue("overrides"))==null?void 0:d.simulcastConfig;if((l=e==null?void 0:e.encodings)!=null&&l.length)return e.encodings;const r="getSettings"in t&&t.getSettings().width||"getConstraints"in t&&t.getConstraints().width||"originalSettings"in t&&((u=t.originalSettings)==null?void 0:u.width),i=BO,n=i.map(([h])=>h).sort((h,m)=>h-m);let o=Number.MAX_VALUE,c=0;return n.forEach((h,m)=>{Math.abs(h-r)<o&&(o=Math.abs(h-r),c=m)}),i[c][1]};var Ae=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Ae||{});const HO=Y_(),An=Is(HO.config.media);function qO(s){var e,r;const t={};return s.audio&&(t.audio={enableStereo:(e=s.audio.enableStereo)!=null?e:!1,enableHighBitrate:(r=s.audio.enableHighBitrate)!=null?r:!1}),t.video=s.video.quality,t}class jO{constructor(t,e){g(this,Fi,void 0);g(this,vl,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,m,S,y,w,_,C;const t=(l=a(this,Fi))==null?void 0:l.screenshare,e=(h=(u=t==null?void 0:t.width)==null?void 0:u.max)!=null?h:1920,r=(S=(m=t==null?void 0:t.height)==null?void 0:m.max)!=null?S:1080,i=(w=(y=t==null?void 0:t.frameRate)==null?void 0:y.max)!=null?w:5,n=(C=(_=t==null?void 0:t.frameRate)==null?void 0:_.ideal)!=null?C:5,o=t==null?void 0:t.displaySurface,c=t==null?void 0:t.selfBrowserSurface;let d={width:{max:e},height:{max:r},frameRate:{ideal:n,max:i}};return o!==void 0&&["monitor","browser","window"].includes(o)&&(d={...d,displaySurface:o}),c!==void 0&&(d={...d,selfBrowserSurface:c}),{audio:!0,video:d}});p(this,"getAudioConstraints",t=>{var n,o,c,d,l,u,h;const e={},r=(n=a(this,Fi))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return Te.isFirefox()||Te.isWebKitBased()?(e.audio={deviceId:t,autoGainControl:(o=r==null?void 0:r.autoGainControl)!=null?o:!0,echoCancellation:(c=r==null?void 0:r.echoCancellation)!=null?c:!0,noiseSuppression:(d=r==null?void 0:r.noiseSupression)!=null?d:!0,channelCount:i},e):(e.audio={autoGainControl:(l=r==null?void 0:r.autoGainControl)!=null?l:!0,echoCancellation:(u=r==null?void 0:r.echoCancellation)!=null?u:!0,noiseSuppression:(h=r==null?void 0:r.noiseSupression)!=null?h:!0,channelCount:i},t&&(e.audio.deviceId={exact:t}),e)});p(this,"getVideoConstraints",t=>{var o,c,d;const e={},r=(o=a(this,Fi))==null?void 0:o.video,i=hP($O);let n=i.vga;if(typeof r=="string"){const l=i[r];l&&(n=l)}else r!==void 0&&(n.height.ideal=r.height.ideal,n.width.ideal=r.width.ideal,n.frameRate.ideal=(d=(c=r.frameRate)==null?void 0:c.ideal)!=null?d:30);return e.video=n,typeof e.video=="boolean"||(t?e.video.deviceId={exact:t}:e.video.facingMode="user"),e});f(this,vl,t),f(this,Fi,e)}getUpdatedVideoConstraints(t){return t}}Fi=new WeakMap,vl=new WeakMap;class Eh extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class GO{constructor(){p(this,"permissions");this.permissions={audio:"NOT_REQUESTED",video:"NOT_REQUESTED",screenshare:"NOT_REQUESTED"}}async getAudioInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audioinput")}async getVideoInputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="videoinput")}async getAudioOutputDevices(t){let e=t;return t||(e=await this.getAvailableDevices()),e.filter(r=>r.kind==="audiooutput")}}var WO=Object.defineProperty,JO=Object.getOwnPropertyDescriptor,ps=(s,t,e,r)=>{for(var i=r>1?void 0:r?JO(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&WO(t,e,i),i};let Lt=(WS=class extends GO{constructor(t,e){super();g(this,ea,void 0);g(this,ss,void 0);g(this,Qe,void 0);f(this,Qe,t),f(this,ss,new jO(t,e)),f(this,ea,new AbortController)}get telemetry(){return a(this,Qe).getValue("telemetry")}get logger(){return a(this,Qe).getValue("logger")}get constraintsBuilder(){return a(this,ss)}async destruct(){var t;(t=a(this,ea))==null||t.abort()}handlePermissionErrors(t,e){const r=$d(t,e.name,e.message);return this.permissions[t]=r,a(this,Qe).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_ERROR,{message:r,constraints:e.constraints,kind:t}),r}async getAudioAndVideoTrack(t,e){var r,i,n,o;try{const c=await this.getAudioInputDevices(),d=await this.getVideoInputDevices(),l=!!(c!=null&&c.find(C=>C.deviceId===t));let u;t&&l?u=t:c&&((r=c[0])!=null&&r.deviceId)&&(u=(i=c[0])==null?void 0:i.deviceId);const h=!!(d!=null&&d.find(C=>C.deviceId===e));let m;e&&h?m=e:d&&((n=d[0])!=null&&n.deviceId)&&(m=(o=d[0])==null?void 0:o.deviceId);const S={audio:a(this,ss).getAudioConstraints(u).audio,video:a(this,ss).getVideoConstraints(m).video};this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(S)});const y=await navigator.mediaDevices.getUserMedia(S);this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(S)});const w=y.getAudioTracks()[0];let _=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",_.label.includes("OBS Virtual")){const D=(await this.getVideoInputDevices()).find(V=>V.label.includes("OBS Virtual"));_=await this.getVideoTrack(D.deviceId)}return a(this,Qe).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Qe).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:w,videoTrack:_}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new R("Couldnt fetch audio and video track","1605")}}async getAudioTrack(t,e){var c,d;let r=await this.getAudioInputDevices();if(!(r!=null&&r.length))throw this.permissions.audio="NO_DEVICES_AVAILABLE",a(this,Qe).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new R("No audio devices available","1606");const i=!!(r!=null&&r.find(l=>l.deviceId===e));let n;e&&i?n=e:(c=r[0])!=null&&c.deviceId&&(n=(d=r[0])==null?void 0:d.deviceId);const o=async l=>{let u;try{r=r.filter(m=>m.deviceId!==l),u=a(this,ss).getAudioConstraints(l),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(u)});const[h]=(await navigator.mediaDevices.getUserMedia(u)).getAudioTracks();return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(u)}),h}catch(h){const m=$d("audio",h.name,h.message),S=new Eh(h.name,h.message,u);if(m==="COULD_NOT_START"){const y=r.shift();if(!y)throw S;this.logger.info("getAudioTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const w=a(this,ss).getAudioConstraints(y.deviceId);return this.logger.info("getAudioTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(w)}),o(y.deviceId)}throw S}};try{const l=await o(n);return l.enabled=!t,this.permissions.audio!=="ACCEPTED"&&(this.permissions.audio="ACCEPTED",a(this,Qe).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new R(l.message,"1601")}}async getVideoTrack(t){var c,d,l;const e=(c=await this.getCurrentDeviceLabel(t))==null?void 0:c.includes("OBS Virtual"),r=await this.getVideoInputDevices();if(!(r!=null&&r.length))throw this.permissions.video="NO_DEVICES_AVAILABLE",a(this,Qe).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new R("No video devices available","1607");const i=!!(r!=null&&r.find(u=>u.deviceId===t));let n;t&&i?n=t:(d=r[0])!=null&&d.deviceId&&(n=(l=r[0])==null?void 0:l.deviceId);const o=async u=>{try{let h=u;const{video:m}=h;e&&typeof m!="boolean"&&(h={video:{deviceId:m.deviceId}}),this.logger.info("getUserMediaWithoutTimeout::requesting_user_media",{constraints:JSON.stringify(h)});const[S]=(await navigator.mediaDevices.getUserMedia(h)).getVideoTracks();if(e&&typeof m!="boolean"&&typeof m.width=="object"){const{width:y,height:w}=S.getSettings(),{ideal:_}=m.width;S.applyConstraints({width:{ideal:_},height:{ideal:Math.floor(w*_/y)},frameRate:m.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),S}catch(h){const m=$d("video",h.name,h.message),S=new Eh(h.name,h.message,u);if(m==="COULD_NOT_START"){const y=r.shift();if(!y)throw S;this.logger.info("getVideoTrack::gum_failed",{constraints:JSON.stringify(u),error:h});const w=a(this,ss).getVideoConstraints(y.deviceId);return this.logger.info("getVideoTrack::retrying_gum_for_next_device",{constraints:JSON.stringify(w)}),o({video:w.video})}throw S}};try{const u=a(this,ss).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Qe).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),h}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new R(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,Qe).getValue("callstats").screenShareRequested();const r=await navigator.mediaDevices.getDisplayMedia(e);return this.logger.info("getDisplayMediaWithoutTimeout::received_display_media",{constraints:JSON.stringify(e)}),r}catch(r){const i=$d("video",r.name,r.message),n=new Eh(r.name,r.message,e),o={video:!0};if(y_(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,ss).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Qe).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.permissions.screenshare,kind:"screenshare"})),{audioTrack:r.getAudioTracks()[0],videoTrack:r.getVideoTracks()[0]}}catch(e){throw e.constraints&&this.handlePermissionErrors("screenshare",e),new R(e.message,"1612")}}async getCurrentDeviceLabel(t){const e=await this.getDevice(t||"default");return e==null?void 0:e.label}async enumerateDevicesWithExternalFirst(){const t=await navigator.mediaDevices.enumerateDevices(),e=i=>{var o;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return Bd(i)?4:n.includes("airpods")||n.includes("airdopes")||n.includes("bluetooth")||n.includes("wireless")||n.includes("headphones")||n.includes("headset")||n.includes("earbuds")||n.includes("usb")||n.includes("external")?0:i.deviceId==="default"||n.includes("default")?1:n.includes("built-in")||n.includes("internal")?2:3},r=i=>{var o;if(i.kind!=="videoinput")return!1;const n=((o=i.label)==null?void 0:o.toLowerCase())||"";return n.includes("front")||n.includes("user")||n.includes("selfie")?!0:!(n.includes("back")||n.includes("rear")||n.includes("environment"))};return t.sort((i,n)=>{var u,h;const o=e(i),c=e(n);if(o!==c)return o-c;const d=i.deviceId==="default"||((u=i.label)==null?void 0:u.toLowerCase().includes("default")),l=n.deviceId==="default"||((h=n.label)==null?void 0:h.toLowerCase().includes("default"));if(d&&!l)return-1;if(!d&&l)return 1;if(i.kind==="videoinput"&&n.kind==="videoinput"){const m=r(i),S=r(n);if(m&&!S)return-1;if(!m&&S)return 1}return 0})}async getAvailableDevices(){try{return await this.enumerateDevicesWithExternalFirst()||[]}catch(t){return this.logger.error("enumerate_devices_failed",{error:t}),[]}}async getAvailableDevicesByKind(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(({kind:e})=>t===e)}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new R("Failed to get available devices by kind","1609")}}async getDevice(t){try{return(await this.enumerateDevicesWithExternalFirst()).filter(r=>r.deviceId===t)[0]}catch(e){throw this.logger.error("enumerate_devices_failed",{error:e}),new R("Failed to get device","1609")}}async onDeviceChange(t){if(Te.supportsDeviceChangeEvent()){let e=await this.getAvailableDevices();navigator.mediaDevices.addEventListener("devicechange",async r=>{var l,u;const i=h=>`${h.kind}-${h.label}-${h.deviceId}-${h.groupId}`,n=new Set(e.map(h=>i(h))),o=await this.getAvailableDevices(),c=new Set(o.map(h=>i(h))),d={added:o.filter(h=>!n.has(i(h))),removed:e.filter(h=>!c.has(i(h))),devices:o};if(e=o,(l=d.added)!=null&&l.length||(u=d.removed)!=null&&u.length){this.logger.info("repopulated_full_device_list",{devices:JSON.stringify(o)});const h=[...d.added,...d.removed];h.some(m=>m.kind==="audioinput")&&a(this,Qe).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(m=>m.kind==="audioinput")),h.some(m=>m.kind==="videoinput")&&a(this,Qe).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(m=>m.kind==="videoinput")),h.some(m=>m.kind==="audiooutput")&&a(this,Qe).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(m=>m.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,ea).signal})}}},ea=new WeakMap,ss=new WeakMap,Qe=new WeakMap,WS);ps([E.trace("WebMediaInterface.destruct")],Lt.prototype,"destruct",1),ps([E.trace("WebMediaInterface.handlePermissionErrors")],Lt.prototype,"handlePermissionErrors",1),ps([E.trace("WebMediaInterface.getAudioAndVideoTrack")],Lt.prototype,"getAudioAndVideoTrack",1),ps([E.trace("WebMediaInterface.getAudioTrack")],Lt.prototype,"getAudioTrack",1),ps([E.trace("WebMediaInterface.getVideoTrack")],Lt.prototype,"getVideoTrack",1),ps([E.trace("WebMediaInterface.getScreenShareTracks")],Lt.prototype,"getScreenShareTracks",1),ps([E.trace("WebMediaInterface.getAvailableDevices")],Lt.prototype,"getAvailableDevices",1),ps([E.trace("WebMediaInterface.getAvailableDevicesByKind")],Lt.prototype,"getAvailableDevicesByKind",1),ps([E.trace("WebMediaInterface.getDevice")],Lt.prototype,"getDevice",1),ps([E.trace("WebMediaInterface.onDeviceChange")],Lt.prototype,"onDeviceChange",1),Lt=ps([lt("1600")],Lt);const Hf=Lt,yi={setItem:(s,t,e)=>{try{localStorage.setItem(s,t)}catch(r){e==null||e.error("LocalStorage::setItem::crashed",{error:r,localStorage:{key:s,value:t}})}},getItem:(s,t)=>{try{return localStorage.getItem(s)}catch(e){t==null||t.error("LocalStorage::getItem::crashed",{error:e,localStorage:{key:s}})}return null}},KO=(s=0)=>new Promise(t=>setTimeout(t,s)),zO=(s,t,e)=>{const r=typeof e=="number"?e:250,i=s.createMediaStreamSource(t),n=s.createAnalyser();n.fftSize=2048,i.connect(n);const o=new Uint8Array(n.fftSize);let c=!1;setTimeout(()=>{c=!0},r);function d(){return c?Promise.resolve(!0):(n.getByteTimeDomainData(o),o.some(l=>l!==128&&l!==0)?Promise.resolve(!1):KO().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},YO=typeof AudioContext!="undefined"?AudioContext:null;class bh{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:YO,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:bh}})}getOrCreate(t){if(!this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.add(t),this._AudioContext&&!this.audioContext))try{this.audioContext=new this._AudioContext}catch(e){}return this.audioContext}release(t){this._audioContextRefContainers.has(t)&&(this._audioContextRefContainers.delete(t),!this._audioContextRefContainers.size&&this.audioContext&&(this.audioContext.close(),this.audioContext=null))}}const qf=new bh,QO=3,XO=250;function ZO(s){const t={},e=qf.getOrCreate(t);let r=QO;function i(){return r-=1,zO(e,s.srcObject,XO).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{qf.release(t)})}async function jf(s,t){const e=new Audio,r=new MediaStream;r.addTrack(t),e.srcObject=r;let i=!1;try{const n=e.play();n&&await n,i=await ZO(e),i&&s.info("checkIfAudioTrackIsSilent::silence_detected")}catch(n){s.error("checkIfAudioTrackIsSilent::failed_to_detect_silence",{error:n})}finally{e.pause(),e.remove()}return i}var eD=Object.defineProperty,tD=Object.getOwnPropertyDescriptor,Gf=(s,t,e,r)=>{for(var i=r>1?void 0:r?tD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&eD(t,e,i),i};let qd=class extends kn{constructor(t,e,r,i){var o;const n=t.getValue("logger");super(n);p(this,"constructorName",this.constructor.name);p(this,"userSelectedDevice");p(this,"mediaInterface");p(this,"isNonPreferredDevice");p(this,"_mediaTrack");p(this,"transformedMediaTrack");p(this,"middlewares",[]);p(this,"currentDevice");p(this,"userPreferredDeviceKey",`Realtimekit::${this.constructorName}::UserDeviceID`);p(this,"setUserPreferredDevice",t=>yi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>yi.getItem(this.userPreferredDeviceKey,this.logger));p(this,"isCustomTrack",!1);p(this,"context");this.context=t,this.mediaInterface=e,r&&this.setMediaTrack(r),this.userSelectedDevice=(o=this.getUserPreferredDevice())!=null?o:void 0,this.isNonPreferredDevice=i,this.onTrackEnded=this.onTrackEnded.bind(this),this.onTrackMuted=this.onTrackMuted.bind(this)}get telemetry(){return this.context.getValue("telemetry")}disableTrack(){var t,e;this.removeMediaTrackListeners(),this.isCustomTrack||(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}async setMediaTrack(t,e=!1){const r=i=>{this.logger.error(`${this.constructorName}.setMediaTrack.error`,{error:i})};try{this.disableTrack()}catch(i){r(i)}this._mediaTrack=await this.conditionallyChangeTrack(t,e),await this.setTransformedTrack();try{this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){r(i)}}get trackEnabled(){return!!this.mediaTrack&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}muteTrack(){if(!this.mediaTrack){this.logger.warn("BaseMediaHandler.muteTrack Tried muting with no track present");return}this.transformedMediaTrack&&(this.transformedMediaTrack.enabled=!1),this.mediaTrack.enabled=!1}async unmuteTrack(){try{this.mediaTrack?this.mediaTrack.enabled=!0:await this.enableTrack(!1)}catch(t){throw this.logger.error(`${this.constructorName}.unmuteTrack.error`,{error:t}),this.disableTrack(),new R("Failed to unmute track","1611")}}getCurrentDeviceId(){var e;const{kind:t}=this.mediaTrack;switch(t){case"audio":{const{deviceId:r}=this.mediaTrack.getSettings();if(r)return r;const i=this.mediaTrack.getConstraints();return this.userSelectedDevice?(i&&typeof i.deviceId=="object"&&"exact"in i.deviceId?i.deviceId.exact:i.deviceId)||((e=i==null?void 0:i.advanced)==null?void 0:e[0].deviceId)||"default":this.mediaTrack.getSettings().deviceId}default:return this.mediaTrack.getSettings().deviceId}}async setCurrentDevice(){var e;if(!this.mediaTrack){this.currentDevice=void 0;return}const t=this.getCurrentDeviceId();((e=this.currentDevice)==null?void 0:e.deviceId)!==t&&(this.currentDevice=await this.mediaInterface.getDevice(t))}async setDevice(t,{saveDevicePreference:e}){if(!t)throw this.logger.warn(`${this.constructorName}.setDevice No device received`),new R("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(Te.isWebKitBased()&&!(Te.isSafari()&&N_.test(Te.getVersion())))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&&await this.setTransformedTrack(),{success:!0,message:"Successfully added the middleware."}}catch(e){return this.logger.error("While adding middleware",{error:e}),this.removeMiddleware(t),{success:!1,message:e==null?void 0:e.message}}}async removeMiddleware(t){const e=this.middlewares.indexOf(t,0);if(e>-1)try{return this.middlewares.splice(e,1),await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed the middleware."}}catch(r){return this.logger.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."}}async removeAllMiddlewares(){var t;if((t=this.middlewares)!=null&&t.length)try{return this.middlewares=[],await this.setTransformedTrack(!0),{success:!0,message:"Successfully removed all the middlewares."}}catch(e){return this.logger.error("While removing all the middlewares",{error:e}),{success:!1,message:e==null?void 0:e.message}}return{success:!1,message:"No middlewares were found. Skipping."}}addMediaTrackListeners(){var t,e,r;this.mediaTrack&&(this.logger.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&&(this.logger.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}`),this.logger.info(`${this.constructorName}.removeMediaTrackListeners`),this.mediaTrack.removeEventListener("ended",this.onTrackEnded),this.mediaTrack.removeEventListener("mute",this.onTrackMuted))}};Gf([E.trace("BaseMediaHandler.unmuteTrack")],qd.prototype,"unmuteTrack",1),qd=Gf([lt("1600")],qd);const Wf=qd;var sD=Object.defineProperty,rD=Object.getOwnPropertyDescriptor,wh=(s,t,e,r)=>{for(var i=r>1?void 0:r?rD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&sD(t,e,i),i};const Ph="[Realtimekit]nonSilentDeviceLabels";class jd extends Wf{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new R("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new R("Non audio device received while setting device!","1603");try{const e=this.trackEnabled;this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getAudioTrack(!e,this.userSelectedDevice))}catch(e){throw this.logger.error("AudioMediaHandler.setDevice.error",{error:e}),this.disableTrack(),new R(e.message,"1604")}}async enableTrack(t,e){if(this.trackEnabled){this.logger.warn("AudioMediaHandler.enableTrack Track already enabled!");return}if(e){this.isCustomTrack=!0,await this.setMediaTrack(e,!0);return}this.isCustomTrack=!1;const r=await this.mediaInterface.getAudioTrack(t,this.userSelectedDevice);await this.setMediaTrack(r)}async setTransformedTrack(t){var e;if(!t&&!((e=this.middlewares)!=null&&e.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await MO(this.context,this.middlewares,this.mediaTrack),this.emit("trackChanged")}catch(r){this.logger.error("AudioMediaHandler.setTransformedTrack",{error:r}),this.transformedMediaTrack=this.mediaTrack}}async onTrackEnded(){this.logger.info("AudioMediaHandler.TrackEnded"),this.emit("trackEnded");const t=this.mediaTrack.enabled;this.disableTrack(),await this.enableTrack(!t),await this.setTransformedTrack(),this.emit("trackChanged")}onTrackMuted(){this.logger.info("AudioMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(t,e=!1){var d;if(!t||this.userSelectedDevice||e)return t;let r=t;const i=await this.mediaInterface.getAudioInputDevices(),n=this.isNonPreferredDevice?i.filter(l=>l&&!this.isNonPreferredDevice(l)):i;if(!(n!=null&&n.length))return r;n.find(l=>l.deviceId===t.getSettings().deviceId)||(r.stop(),this.logger.info("localmediahandler::setupstreams::found_audio_non_preferred"),r=await this.mediaInterface.getAudioTrack(!1,n[0].deviceId));const o=JSON.parse(yi.getItem(Ph,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await jf(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return yi.setItem(Ph,JSON.stringify({devices:l}),this.logger),r}this.logger.info("AudioMediaHandler.conditionallyChangeTrack.DetectedSilentTrack");const c=r.getSettings().deviceId;return n.filter(l=>l.deviceId!==c).some(async l=>{var u;if(r=await this.mediaInterface.getAudioTrack(!1,l.deviceId),!await jf(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return yi.setItem(Ph,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}wh([E.trace("AudioMediaHandler.setTransformedTrack")],jd.prototype,"setTransformedTrack",1),wh([E.trace("AudioMediaHandler.onTrackEnded")],jd.prototype,"onTrackEnded",1),wh([E.trace("AudioMediaHandler.conditionallyChangeTrack")],jd.prototype,"conditionallyChangeTrack",1);const iD=jd;class nD{constructor(t,e){g(this,Hi,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>yi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>yi.getItem(this.userPreferredDeviceKey,this.logger));f(this,Hi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,Hi).getAudioOutputDevices(),r=e==null?void 0:e.find(i=>i.deviceId===t);await this.setupSpeaker(r,{saveDevicePreference:!1})}async setupSpeaker(t,{saveDevicePreference:e}){var n,o;if(!(a(this,Hi)instanceof Hf))return;let r=t;if(t||([r]=(await a(this,Hi).getAvailableDevicesByKind("audiooutput")).filter(d=>!Bd(d))),!r)throw new R("No speaker found","1608");if(((n=this.currentDevice)==null?void 0:n.deviceId)===r.deviceId)return;e&&this.setUserPreferredDevice(r.deviceId),this.currentDevice=r;const i=document.querySelectorAll("audio");(o=i[0])!=null&&o.setSinkId&&i.forEach(async c=>{if(typeof c.sinkId!="undefined"&&this.currentDevice.deviceId&&c.sinkId!==this.currentDevice.deviceId)try{await c.setSinkId(this.currentDevice.deviceId)}catch(d){}})}}Hi=new WeakMap;const aD=nD;class oD extends kn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");g(this,Fo,void 0);f(this,Fo,e),this.mediaInterface=r}get trackEnabled(){return!!this.videoMediaTrack}async enableScreenShare(){var e,r;try{const{audioTrack:i,videoTrack:n}=await this.mediaInterface.getScreenShareTracks();if(this.audioMediaTrack=i,this.videoMediaTrack=n,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",a(this,Fo).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,{message:this.mediaInterface.permissions.screenshare,kind:"screenshare"}))}catch(i){}}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}async updateConstraints(e){if(!this.videoMediaTrack)throw new R("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new R("update constraints not supported for non web clients","1100",this.logger);try{this.videoMediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),this.addMediaTrackListeners()}catch(i){this.logger.error("ScreenShareHandler.updateConstraints.error",{error:i})}}addMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.addEventListener("ended",this.onTrackEnded.bind(this)),Te.isWebKitBased()&&((r=this.videoMediaTrack)==null||r.addEventListener("mute",this.onTrackEnded.bind(this)))}removeMediaTrackListeners(){var e,r;(e=this.videoMediaTrack)==null||e.removeEventListener("ended",this.onTrackEnded),(r=this.videoMediaTrack)==null||r.removeEventListener("mute",this.onTrackEnded)}onTrackEnded(){this.emit("trackEnded")}}Fo=new WeakMap;const cD=oD;var dD=Object.defineProperty,lD=Object.getOwnPropertyDescriptor,Gd=(s,t,e,r)=>{for(var i=r>1?void 0:r?lD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&dD(t,e,i),i};class oo extends Wf{constructor(e,r,i,n){super(e,r,i,n);g(this,ta,void 0);g(this,Ho,{disablePerFrameCanvasRendering:!1});f(this,ta,new UO(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new R("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new R("Non video device received while setting video device!","1603");if(!(this.mediaTrack&&this.mediaTrack.enabled)){this.logger.warn("VideoMediaHandler.setDevice Tried switching device with video disabled",{devices:[e]}),this.currentDevice=e;return}try{this.disableTrack(),await this.setMediaTrack(await this.mediaInterface.getVideoTrack(this.userSelectedDevice))}catch(r){throw this.logger.error("VideoMediaHandler.setDevice.error",{error:r}),this.disableTrack(),new R("Failed to change device","1600",this.logger)}}async enableTrack(e,r){if(this.trackEnabled){this.logger.warn("VideoMediaHandler.enableTrack Track already enabled!");return}if(r){this.isCustomTrack=!0,await this.setMediaTrack(r,!0);return}this.isCustomTrack=!1;const i=await this.mediaInterface.getVideoTrack(this.userSelectedDevice);await this.setMediaTrack(i)}async setTransformedTrack(e){var r;if(!e&&!((r=this.middlewares)!=null&&r.length)){this.transformedMediaTrack=this.mediaTrack;return}try{this.transformedMediaTrack=await a(this,ta).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,Ho)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,Ho,e)}async updateConstraints(e){if(!this._mediaTrack)throw new R("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new R("update constraints not supported for non web clients","1100",this.logger);try{this._mediaTrack.applyConstraints(r.constraintsBuilder.getUpdatedVideoConstraints(e)),await this.setTransformedTrack(),this.addMediaTrackListeners(),await this.setCurrentDevice()}catch(i){this.logger.error("VideoMediaHandler.updateConstraints.error",{error:i})}}terminateMiddlewareWebWorker(){a(this,ta).terminateMiddlewareWebWorker()}async onTrackEnded(){this.logger.info("VideoMediaHandler.TrackEnded"),this.disableTrack(),this.emit("trackEnded")}onTrackMuted(){this.logger.info("VideoMediaHandler.TrackMuted"),this.emit("trackMuted")}async conditionallyChangeTrack(e,r=!1){if(!e||this.userSelectedDevice||r)return e;let i=e;const n=await this.mediaInterface.getVideoInputDevices(),o=this.isNonPreferredDevice?n.filter(c=>!this.isNonPreferredDevice(c)):n;return!(o!=null&&o.length)||window.FAST_RTK||o.find(c=>c.deviceId===e.getSettings().deviceId)||(i.stop(),this.logger.info("localmediahandler::setupstreams::found_video_non_preferred"),i=await this.mediaInterface.getVideoTrack(o[0].deviceId)),i}}ta=new WeakMap,Ho=new WeakMap,Gd([E.trace("VideoMediaHandler.setTransformedTrack")],oo.prototype,"setTransformedTrack",1),Gd([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],oo.prototype,"setVideoMiddlewareGlobalConfig",1),Gd([E.trace("VideoMediaHandler.onTrackEnded")],oo.prototype,"onTrackEnded",1),Gd([E.trace("VideoMediaHandler.conditionallyChangeTrack")],oo.prototype,"conditionallyChangeTrack",1);const uD=oo,Jf=Is(Hu()),ra=class{constructor(t){g(this,Tt,void 0);g(this,qi,void 0);g(this,qo,void 0);g(this,sa,void 0);if(!t)throw new R("Could not load preset.","0904");f(this,Tt,t.config),f(this,qo,t.name),f(this,qi,t.ui||Is(Hu().ui)),f(this,sa,t.permissions.plugins.config)}static fromResponse(t){return new ra(t)}static default(){return new ra(Jf)}static init(t,e=!0){return!t||e?new ra(Jf):new ra(t)}get setupScreen(){return{isEnabled:!0}}get waitingRoom(){return{isEnabled:!0}}get controlBar(){return{isEnabled:!0,elements:{chat:!0,fullscreen:!0,invite:!1,layout:!1,participants:!0,plugins:!0,polls:!0,reactions:!1,screenshare:!0}}}get header(){return{isEnabled:!0,elements:{logo:a(this,qi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,Tt).viewType}get livestreamViewerQualities(){return a(this,Tt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,Tt).maxVideoStreams}get maxScreenShareCount(){return a(this,Tt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,sa)).filter(t=>a(this,sa)[t].disabled)}get designTokens(){return a(this,qi).designTokens}get configDiff(){return a(this,qi).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,Tt))==null?void 0:t.media)==null?void 0:e.video)==null?void 0:r.simulcast)!=null?i:!1}get mediaConstraints(){var t,e,r,i,n,o,c,d,l,u,h,m,S,y,w,_,C,D,V,$,H,F,Z,be;return{audio:{enableStereo:(i=(r=(e=(t=a(this,Tt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:An.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,Tt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:An.audio.enableHighBitrate},video:{quality:(m=(h=(u=(l=a(this,Tt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?m:An.video.quality,frameRate:(_=(w=(y=(S=a(this,Tt))==null?void 0:S.media)==null?void 0:y.video)==null?void 0:w.frameRate)!=null?_:An.video.frameRate},screenshare:{quality:($=(V=(D=(C=a(this,Tt))==null?void 0:C.media)==null?void 0:D.screenshare)==null?void 0:V.quality)!=null?$:An.screenshare.quality,frameRate:(be=(Z=(F=(H=a(this,Tt))==null?void 0:H.media)==null?void 0:F.screenshare)==null?void 0:Z.frameRate)!=null?be:An.screenshare.frameRate}}}get name(){return a(this,qo)}};let _h=ra;Tt=new WeakMap,qi=new WeakMap,qo=new WeakMap,sa=new WeakMap;var hD=Object.defineProperty,pD=Object.getOwnPropertyDescriptor,Kf=(s,t,e,r)=>{for(var i=r>1?void 0:r?pD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&hD(t,e,i),i};class kh extends Dt{constructor(e,r){const i=e.getValue("logger");super(i);g(this,ia,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");g(this,jo,void 0);f(this,ia,r),f(this,jo,e),this.viewerCount=0}get telemetry(){return a(this,jo).getValue("telemetry")}setLivestreamState(e){const r=this.state;this.state=e,r!==e&&this.emitCurrentLivestreamState()}emitCurrentLivestreamState(){this.emit("livestreamUpdate",this.state)}async start(e={manualIngestion:!1}){if(!a(this,ia).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new R("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=Pt(),{playbackUrl:i,ingestionCredentials:n}=await r.startLivestreaming(e);this.playbackUrl=i,this.ingestionCredentials=n,e!=null&&e.manualIngestion&&this.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}catch(r){throw this.logger.error("Recording::stop::livestream_failed_to_start",{error:r}),this.setLivestreamState("IDLE"),new R("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,ia).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new R("User does not have permission to stop livestreaming","1901");if(this.state!=="LIVESTREAMING"&&this.state!=="WAITING_ON_MANUAL_INGESTION")throw this.logger.error("Livestream::stop::inconsistent_state"),new R("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await Pt().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new R("Error while stopping livestream","1900",this.logger)}}}ia=new WeakMap,jo=new WeakMap,Kf([E.trace("livestream.start")],kh.prototype,"start",1),Kf([E.trace("livestream.stop")],kh.prototype,"stop",1);var mD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,fD=(s,t,e,r)=>{for(var i=r>1?void 0:r?gD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&mD(t,e,i),i};class zf{constructor(t,e,r){p(this,"livestream");g(this,na,void 0);g(this,aa,void 0);g(this,hr,void 0);g(this,Vs,void 0);f(this,Vs,t),f(this,aa,e),this.livestream=new kh(t,e),f(this,hr,r),this.setupEvents()}get logger(){return a(this,Vs).getValue("logger")}get telemetry(){return a(this,Vs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=Pt(),{status:e,playbackUrl:r,manualIngest:i,ingestionCredentials:n}=await t.getActiveLivestream();this.livestream.playbackUrl=r,this.livestream.ingestionCredentials=n,e==="LIVE"&&this.livestream.setLivestreamState("LIVESTREAMING"),e==="INVOKED"&&i&&this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION")}setupEvents(){a(this,hr).on(U.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,aa).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,hr).on(U.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,aa).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,hr).on(U.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,hr).on(U.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,hr).on(U.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Vs).getValue("peerSessionStore").on(k.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,na,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Vs).getValue("peerSessionStore").on(k.PEER_CLOSED,t=>{t.id===a(this,na)&&(f(this,na,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Vs).getValue("peerSessionStore").onAsync(k.LEAVE_MEDIA_ROOM,async()=>{if(!this.livestream.playbackUrl){this.logger.info("Fetching livestreaming state on leave stage");try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Failed to fetch livestreaming state on leave stage",{error:t})}}}),a(this,Vs).getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}na=new WeakMap,aa=new WeakMap,hr=new WeakMap,Vs=new WeakMap,fD([E.trace("LivestreamController.setupEvents")],zf.prototype,"setupEvents",1);var SD=Object.defineProperty,vD=Object.getOwnPropertyDescriptor,co=(s,t,e,r)=>{for(var i=r>1?void 0:r?vD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&SD(t,e,i),i};class Mn{constructor({name:t,socketHandler:e,meetingId:r}){g(this,Tl);p(this,"name","");g(this,at,{});g(this,Kr,"");g(this,zr,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,f(this,zr,e),f(this,Kr,r)}async set(t,e,r=!0,i=!1){a(this,at)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,at)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,at)[t]})))}remoteSet(t,e){a(this,zr).storeInsertKeys(a(this,Kr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,at)[e]=r}),a(this,zr).storeInsertKeys(a(this,Kr),this.name,t)}async update(t,e,r=!0){L(this,Tl,nv).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,at)[t]&&delete a(this,at)[t],e)return a(this,zr).storeDeleteKeys(a(this,Kr),this.name,[{key:t}]);r&&(this.listeners[t]&&(this.listeners[t].forEach(i=>i({[t]:void 0})),delete this.listeners[t]),this.listeners["*"]&&this.listeners["*"].forEach(i=>i({[t]:void 0})))}async bulkDelete(t){return t.forEach(({key:e})=>{a(this,at)[e]&&delete a(this,at)[e]}),a(this,zr).storeDeleteKeys(a(this,Kr),this.name,t)}get(t){if(a(this,at)[t])return a(this,at)[t]}getAll(){return a(this,at)}clear(){f(this,at,{})}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get bulkRateLimits(){return this.bulkRateLimitConfig}updateBulkRateLimits(t,e){this.bulkRateLimitConfig.maxInvocations=t,this.bulkRateLimitConfig.period=e}subscribe(t,e){if(this.listeners[t]){this.listeners[t].push(e);return}this.listeners[t]=[e]}unsubscribe(t,e){var r;if(e){this.listeners[t]=((r=this.listeners[t])==null?void 0:r.filter(i=>i!==e))||[];return}this.listeners[t]&&delete this.listeners[t]}populate(t){f(this,at,t)}}at=new WeakMap,Kr=new WeakMap,zr=new WeakMap,Tl=new WeakSet,nv=function(t,e,r=!0){let i;const n=a(this,at)[t],o=Object.prototype.toString.call(e),c=Object.prototype.toString.call(n);if(o!==c){this.set(t,e);return}switch(c){case"[object Array]":i=[...n,...e];break;case"[object Object]":i={...n,...e};break;case"[object Map]":i=new Map([...n,...e]);break;case"[object Set]":i=new Set([...n,...e]);break;default:i=e;break}this.set(t,i,r)},co([Nt(Rn,"rateLimitConfig")],Mn.prototype,"remoteSet",1),co([Nt(Rn,"bulkRateLimitConfig")],Mn.prototype,"bulkSet",1),co([Nt(Rn,"rateLimitConfig")],Mn.prototype,"update",1),co([Nt(Rn,"rateLimitConfig")],Mn.prototype,"delete",1),co([Nt(Rn,"bulkRateLimitConfig")],Mn.prototype,"bulkDelete",1);class TD{constructor(t,e){g(this,Go);g(this,yl);p(this,"stores",new Map);g(this,Yr,void 0);g(this,Qr,"");g(this,Wo,void 0);g(this,vs,new Map);f(this,Yr,e),f(this,Qr,t.getValue("meetingId")),f(this,Wo,t),L(this,yl,av).call(this)}create(t,e=!1){if(V_.includes(t)&&!e)throw new R(`'${t}' is a reserved store name.`,"0601");const r=new Mn({name:t,socketHandler:a(this,Yr),meetingId:a(this,Qr)});return a(this,Yr).storeGetKeys(a(this,Qr),t,[]),new Promise((n,o)=>{const c=setTimeout(()=>{a(this,vs).delete(t),o(Error("Failed"))},3e3);a(this,vs).set(t,{rejectTimeout:c,resolve:n,store:r})})}refresh(t){const e=this.stores.get(t);return e?(e.clear(),a(this,Yr).storeGetKeys(a(this,Qr),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>{a(this,vs).delete(t),n(Error("Store refresh timed out"))},3e3);a(this,vs).set(t,{rejectTimeout:o,resolve:i,store:e})})):Promise.reject(Error(`Store '${t}' does not exist`))}}Yr=new WeakMap,Qr=new WeakMap,Go=new WeakSet,ip=function(){return a(this,Wo).getValue("peerId")},Wo=new WeakMap,vs=new WeakMap,yl=new WeakSet,av=function(){[Qs.storeInsertKeys,Qs.storeGetKeys,Qs.storeDeleteKeys].forEach(t=>{a(this,Yr).on(t,async e=>{var n,o;if(e.pluginId!==a(this,Qr))return;const r=(n=e.storeItems)==null?void 0:n.map(c=>{var d;return{timestamp:c.timestamp,peerId:c.peerId,payload:JSON.parse((d=c.payload)!=null&&d.length?new TextDecoder().decode(c.payload):"{}"),key:c.storeKey}});if(t===Qs.storeGetKeys){const c=a(this,vs).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);if(a(this,vs).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,vs).delete(e.storeName)),!d)return;r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,vs).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===Qs.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,Go,ip)&&i.set(c,l,!1,!0)}),t===Qs.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,Go,ip)&&i.delete(c,!1,!0)}))})})};function Ei(s){var t,e,r,i,n,o,c,d,l,u,h,m,S;return s?{media:{audio:{enabled:s.audioEnabled,trackId:(t=s.audioTrack)==null?void 0:t.id,permission:"mediaPermissions"in s?(e=s.mediaPermissions)==null?void 0:e.audio:null},video:{enabled:s.videoEnabled,trackId:(r=s.videoTrack)==null?void 0:r.id,permission:"mediaPermissions"in s?(i=s.mediaPermissions)==null?void 0:i.video:null},screenshare:{enabled:s.screenShareEnabled,permission:"mediaPermissions"in s?(n=s.mediaPermissions)==null?void 0:n.screenshare:null,audio:{enabled:(c=(o=s.screenShareTracks)==null?void 0:o.audio)==null?void 0:c.enabled,trackId:(l=(d=s.screenShareTracks)==null?void 0:d.audio)==null?void 0:l.id},video:{enabled:(h=(u=s.screenShareTracks)==null?void 0:u.video)==null?void 0:h.enabled,trackId:(S=(m=s.screenShareTracks)==null?void 0:m.video)==null?void 0:S.id}}}}:{}}var yD=Object.defineProperty,ED=Object.getOwnPropertyDescriptor,On=(s,t,e,r)=>{for(var i=r>1?void 0:r?ED(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&yD(t,e,i),i};const bD=.8,wD=1.2;let sr=(JS=class extends Dt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,ji);g(this,Xr);g(this,Gi);g(this,El);g(this,Wi);g(this,Ko);g(this,wl);g(this,Pl);p(this,"id");p(this,"userId");p(this,"name");p(this,"picture");p(this,"isHost");p(this,"customParticipantId");p(this,"flags");p(this,"device");p(this,"videoTrack");p(this,"audioTrack");p(this,"screenShareTracks");p(this,"videoEnabled");p(this,"audioEnabled");p(this,"screenShareEnabled");p(this,"producers");p(this,"manualProducerConfig");g(this,oa,void 0);p(this,"supportsRemoteControl",!1);g(this,ca,void 0);p(this,"presetName");g(this,$t,void 0);g(this,pr,void 0);g(this,Jo,void 0);g(this,Zr,new Map);g(this,mr,1);g(this,bl,Uu(t=>{if(!this.videoTrack)return;const{clientWidth:e,clientHeight:r}=t,{width:i,height:n}=this.videoTrack.getSettings();if(!i||!n)return;const o=n/r,c=i/e,d=Math.max(o,c);d>wD&&a(this,mr)===1?(f(this,mr,0),a(this,$t).getValue("peerSessionStore").emit(k.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,mr)})):d<bD&&a(this,mr)===0&&(f(this,mr,1),a(this,$t).getValue("peerSessionStore").emit(k.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,mr)}))},2e3));f(this,$t,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:m,stageStatus:S,customParticipantId:y,audioMuted:w,audioTrack:_,videoEnabled:C=!1,videoTrack:D,producers:V,metadata:$}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=m,this.manualProducerConfig=R_,f(this,ca,S!=null?S:"ON_STAGE"),this.customParticipantId=y,this.audioEnabled=!w,this.audioTrack=_,this.videoEnabled=C,this.videoTrack=D,this.screenShareTracks={audio:void 0,video:void 0},this.producers=V!=null?V:[],this.presetName=$==null?void 0:$.preset_name,f(this,oa,!1),f(this,pr,r),f(this,Jo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),L(this,Ko,np).call(this)}get stageStatus(){return a(this,ca)}get telemetry(){return a(this,$t).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...Ei(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...Ei(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",L(this,Ko,np)),a(this,Xr,$a)&&(this.on("audioUpdate",L(this,wl,cv)),this.on("screenShareUpdate",L(this,Pl,dv)))}async pin(){if(!a(this,Gi,Jc))throw new R("Can`t pin participant without joining room","1205");if(!a(this,pr).permissions.pinParticipant)throw new R("You do not have permission to pin participants.","1201");return a(this,ji,Wc).pinPeer(this.id)}async unpin(){if(!a(this,Gi,Jc))throw new R("Can`t unpin participant without joining room","1205");if(!a(this,pr).permissions.pinParticipant)throw new R("You do not have permission to unpin participants.","1201");return a(this,ji,Wc).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,oa,t);const r=t?"pinned":"unpinned";(i=a(this,Wi,Kc))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}async disableAudio(){const t=this.id;if(this.logger.info("Participant::disable_audio",{participant:{id:t}}),!a(this,Gi,Jc))throw new R("Can`t disable participant audio without joining room","1205");if(a(this,pr).permissions.canDisableParticipantAudio)return a(this,ji,Wc).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new R("Unauthorized: User does not have permission to disable participant audio.","1201")}async kick(){const t=this.id;if(this.logger.info("Participant::kick",{participant:{id:t}}),!a(this,El,ov))throw new R("Can`t kick participant without joining room","1205");if(a(this,pr).permissions.kickParticipant){await a(this,$t).getValue("peerSessionStore").emitAsync(k.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new R("Unauthorized: User does not have permission to kick participants.","1201")}async disableVideo(){const t=this.id;if(this.logger.info("Participant::disable_video",{participant:{id:t}}),!a(this,Gi,Jc))throw new R("Can`t disable participant video without joining room","1205");if(a(this,pr).permissions.canDisableParticipantVideo)return a(this,ji,Wc).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new R("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,Jo).getUserPermissions(this.userId)}setStageStatus(t){f(this,ca,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,oa)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,Zr).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,bl).call(this,t)),e.observe(t)),a(this,Zr).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Wi,Kc))==null||o.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(n=this.raised)!=null?n:!1)}deregisterVideoElement(t){var e,r,i,n;if(!t){(e=a(this,Wi,Kc))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,Zr).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,Zr).delete(t),(n=a(this,Wi,Kc))==null||n.removeSource(this.id)}updateVideo(t){var e;if(this.videoEnabled){if(this.videoTrack==null)return;const r=(e=t.srcObject)==null?void 0:e.getTracks()[0];if((r==null?void 0:r.id)===this.videoTrack.id)return;const i=new MediaStream;i.addTrack(this.videoTrack),t.srcObject=i}else t.srcObject=void 0;t.style.display=this.videoEnabled?"block":"none"}},oa=new WeakMap,ca=new WeakMap,$t=new WeakMap,ji=new WeakSet,Wc=function(){return a(this,$t).getValue("roomNodeClient")},Xr=new WeakSet,$a=function(){return a(this,$t).getValue("audioPlayback")},Gi=new WeakSet,Jc=function(){return a(this,$t).getValue("connectionHandler").mediaJoined},El=new WeakSet,ov=function(){return a(this,$t).getValue("connectionHandler").socketJoined},pr=new WeakMap,Jo=new WeakMap,Zr=new WeakMap,Wi=new WeakSet,Kc=function(){return a(this,$t).getValue("pip")},mr=new WeakMap,bl=new WeakMap,Ko=new WeakSet,np=function(){Array.from(a(this,Zr).keys()).forEach(this.updateVideo)},wl=new WeakSet,cv=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,Xr,$a))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,Xr,$a))==null||e.removeParticipantTrack(this.id)},Pl=new WeakSet,dv=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,Xr,$a))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,Xr,$a))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},JS);On([E.trace("Participant.disableAudio")],sr.prototype,"disableAudio",1),On([E.trace("Participant.kick")],sr.prototype,"kick",1),On([E.trace("Participant.disableVideo")],sr.prototype,"disableVideo",1),On([E.trace("Participant.getPermissions")],sr.prototype,"getPermissions",1),On([E.trace("Participant.setStageStatus")],sr.prototype,"setStageStatus",1),sr=On([lt("1200")],sr);class lo extends If{constructor(t,e){const{onAddEvent:r="participantJoined",onDeleteEvent:i="participantLeft",onClearEvent:n="participantsCleared"}=e!=null?e:{};super({onAddEvent:r,onDeleteEvent:i,onClearEvent:n},t)}add(t,e=!0){return this.has(t.id)&&Object.is(this.get(t.id),t)===!1&&this.delete(t.id),super.add(t,e)}clear(t=!0,e=!1){return super.clear(t,e)}delete(t,e=!0,r=!1){return super.delete(t,e,r)}}class PD extends kn{constructor(e){super(e);g(this,ei,void 0);f(this,ei,new Map)}__set(e,r){return a(this,ei).set(e,r)}__clear(){return a(this,ei).clear()}get(e){return a(this,ei).get(e)}toArray(){return Array.from(a(this,ei).values())}}ei=new WeakMap;class _D{constructor(){p(this,"_orderedArray");p(this,"_map");this._map=new Map,this._orderedArray=[]}add(t,e){if(!this._map.has(t))return this._map.set(t,{peerId:t,priority:e}),this._orderedArray.splice(Math.max(e-1,0),0,t),this.index(t);const r=this.index(t);this.delete(t);const i=this.add(t,e);return r!==i?i:-1}delete(t){if(this._map.has(t)){const e=this.index(t);this._map.delete(t),this._orderedArray.splice(e,1)}}index(t){return this._map.has(t)?this._orderedArray.indexOf(t):-1}[Symbol.iterator](){return this._orderedArray[Symbol.iterator]()}}class kD{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new _D,this._compulsoryPeers=new Set}add(t,e,r){if(!t)return-1;if(e<0)return this._compulsoryPeers.add(t),0;const i=r.getValue("logger");if(this.compulsoryPeers.includes(t)&&(e>0||e===246267631)){if(i.info("SelectedPeer::removing_compulsory_peer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),e===246267631)return-1}else if(e===229490415)return this.delete(t,r),-1;return this._activeSpeakerPeers.add(t,e)}delete(t,e){const r=e==null?void 0:e.getValue("logger");r==null||r.info("SelectedPeer::deleting_peer_from_selectedPeer",{selectedPeer:{peerId:t}}),this._removeFromCompulsoryPeer(t),this._activeSpeakerPeers.delete(t)}index(t){return this._activeSpeakerPeers.index(t)}get peers(){return Array.from(new Set(this.compulsoryPeers.concat(this.activeSpeakerPeers)))}get compulsoryPeers(){return Array.from(this._compulsoryPeers.values())}get activeSpeakerPeers(){return Array.from(this._activeSpeakerPeers)}_removeFromCompulsoryPeer(t){this._compulsoryPeers.delete(t)}}const Yf=new kD;var CD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,Os=(s,t,e,r)=>{for(var i=r>1?void 0:r?RD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&CD(t,e,i),i};const ID=["ACTIVE_GRID","PAGINATED","MANUAL"];let Qt=(KS=class extends Dt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,zo);g(this,Ji);g(this,da);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");g(this,Ve,void 0);g(this,Ki,void 0);g(this,Ct,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",Yf);f(this,Ve,t),f(this,Ki,e),f(this,Ct,r),this.waitlisted=new lo(i),this.joined=new lo(i),this.videoSubscribed=new lo(i),this.audioSubscribed=new lo(i),this.active=this.videoSubscribed,this.pinned=new lo(i),this.all=new PD(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Ve).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Ve).getValue("telemetry")}setupEvents(){a(this,Ve).getValue("peerSessionStore").on(k.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Ve).getValue("modules").e2ee)==null?void 0:r.enabled)!==!0&&this.emit("media_decode_error",{reason:`Got encrypted media for participantId ${e}, but encryption wasn't enabled in init.defaults`,code:"1702"})});const t=a(this,Ve).getValue("audioPlayback");t&&this.audioSubscribed.on("participantLeft",e=>{t.removeParticipantTrack(e.id)})}get count(){return this.joined.size}get maxActiveParticipantsCount(){var t;return(t=a(this,Ve))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new R("0 <= Max active participants count limit <= 24","1203");a(this,Ve).setValue("maxPreferredStreams",t),a(this,da,lu)&&a(this,Ve).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}get pageCount(){if(this.viewMode==="PAGINATED"){const t=this.selectedPeers.compulsoryPeers.length,e=this.joined.toArray().filter(r=>r.stageStatus==="ON_STAGE");return Math.ceil((e.length-t)/Math.max(this.maxActiveParticipantsCount-t,1))}return 0}acceptWaitingRoomRequest(t){var r,i;if(!a(this,Ji,zc))throw new R("Can`t accept waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;return a(this,Ct).acceptWaitingRoomRequest([e])}async acceptAllWaitingRoomRequest(t){const e=t.map(r=>{var i,n;return(n=(i=this.waitlisted.get(r))==null?void 0:i.userId)!=null?n:r});return a(this,Ct).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,Ji,zc))throw new R("Can`t reject waiting room request without joining room","1205");const e=(i=(r=this.waitlisted.get(t))==null?void 0:r.userId)!=null?i:t;a(this,Ct).rejectWaitingRoomRequest([e])}async setViewMode(t){if(this.logger.info("Participants::set_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),!(r=>ID.includes(r))(t))throw this.logger.error("Participants::setViewMode::invalid_view_mode",{pageNavigation:{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}}),new R(`Invalid view mode: ${t}. Try ACTIVE_GRID, PAGINATED or MANUAL.`,"1207");if(this.viewMode===t){this.logger.info("Participants::setViewMode::view_mode_same_as_previous");return}this.viewMode=t,t==="PAGINATED"?(this.currentPage=1,a(this,Ve).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Ve).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Ve).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})),this.emit("viewModeChanged",{viewMode:t,currentPage:this.currentPage,pageCount:this.pageCount})}async subscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new R("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!0},this.audioSubscribed.has(i.id)||this.audioSubscribed.add(i)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!0},this.videoSubscribed.has(i.id)||this.videoSubscribed.add(i)))}),a(this,Ve).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new R("MANUAL subscription mode was not activated.","1206");t.forEach(r=>{const i=this.joined.get(r);i&&(e.includes("audio")&&(i.manualProducerConfig={...i.manualProducerConfig,audio:!1},i.manualProducerConfig.screenshareAudio||this.audioSubscribed.delete(i.id)),e.includes("video")&&(i.manualProducerConfig={...i.manualProducerConfig,video:!1},i.manualProducerConfig.screenshareVideo||this.videoSubscribed.delete(i.id)),e.includes("screenshareAudio")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareAudio:!1},i.manualProducerConfig.audio||this.audioSubscribed.delete(i.id)),e.includes("screenshareVideo")&&(i.manualProducerConfig={...i.manualProducerConfig,screenshareVideo:!1},i.manualProducerConfig.video||this.videoSubscribed.delete(i.id)))}),a(this,Ve).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}getPeerIdsForCurrentPage(){this.logger.info("Participants::getPeerIdsForCurrentPage()",{pageNavigation:{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount,maxActiveParticipantsCount:this.maxActiveParticipantsCount}});const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(c=>this.joined.has(c)),r=Array.from(this.pinned.keys()).filter(c=>!e.includes(c)),i=Array.from(this.joined.toArray().filter(c=>c.stageStatus==="ON_STAGE").map(c=>c.id)),n=Math.max((this.currentPage-1)*(this.maxActiveParticipantsCount-e.length-r.length)),o=this.currentPage*(this.maxActiveParticipantsCount-e.length-r.length);return e.concat(r,i.slice(n,o))}async setPage(t){if(this.logger.info("Participants::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 this.logger.error("Participants::invalid_page_number"),new R(`Invalid page: ${t}. Page must be an integer and greater than 0 and less than or equal to .pageCount`,"1202");this.currentPage=t,a(this,Ve).getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.viewMode,page:t}),this.emit("pageChanged",{viewMode:this.viewMode,currentPage:this.currentPage,pageCount:this.pageCount})}}async disableAllAudio(t){if(this.logger.info("Participants::disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),!a(this,da,lu))throw new R("Can`t disable all audio without joining room","1205");if(a(this,Ki).permissions.canAllowParticipantAudio)return a(this,zo,ap).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new R("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,da,lu))throw new R("Can`t disable all video without joining room","1205");if(a(this,Ki).permissions.canAllowParticipantVideo)return a(this,zo,ap).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new R("Unauthorized: User does not have permission to disable peer video.","1201")}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Ve).getValue("viewType")!=="LIVESTREAM"&&!a(this,Ji,zc))throw new R("Can`t kick all without joining room","1205");if(!a(this,Ki).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new R("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,Ct).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,Ji,zc))throw new R("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new R("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,Ct).broadcastToMeetings(t,r.meetingIds,e);else{let i=[];"participantIds"in r?i=r.participantIds:i=this.joined.toArray().filter(n=>{var o;return(o=r.presetNames)==null?void 0:o.includes(n.presetName)}).map(n=>n.id),await a(this,Ct).broadcastToPeers(t,i,e)}else await a(this,Ct).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,Ct).getRoomPeers(t,e,r)).peers.map(rr.formatSocketPeerMessage)}async updatePermissions(t,e){const r=this.joined.toArray().filter(n=>t.includes(n.id)).map(n=>n.userId),i=[...new Set(r)];if(!i.length)throw new R("Cannot update permissions, no valid userIDs found","1204");a(this,Ct).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,Ct).getRoomPeersNonPaginated()}},Ve=new WeakMap,zo=new WeakSet,ap=function(){return a(this,Ve).getValue("roomNodeClient")},Ji=new WeakSet,zc=function(){var t;return((t=a(this,Ve).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},da=new WeakSet,lu=function(){var t;return((t=a(this,Ve).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ki=new WeakMap,Ct=new WeakMap,KS);Os([E.trace("Participants.setViewMode")],Qt.prototype,"setViewMode",1),Os([E.trace("Participants.setPage")],Qt.prototype,"setPage",1),Os([E.trace("Participants.disableAllAudio")],Qt.prototype,"disableAllAudio",1),Os([E.trace("Participants.disableAllVideo")],Qt.prototype,"disableAllVideo",1),Os([E.trace("Participants.kickAll")],Qt.prototype,"kickAll",1),Os([E.trace("Participants.broadcastMessage"),Nt(Rn,"rateLimitConfig")],Qt.prototype,"broadcastMessage",1),Os([E.trace("Participants.getAllJoinedPeers"),Nt({maxInvocations:10,period:60})],Qt.prototype,"getAllJoinedPeers",1),Os([E.trace("Participant.updatePermissions"),Nt({maxInvocations:1e3,period:60})],Qt.prototype,"updatePermissions",1),Os([E.trace("Participants.getParticipantsInMeetingPreJoin")],Qt.prototype,"getParticipantsInMeetingPreJoin",1),Qt=Os([lt("1200")],Qt);var AD=Object.defineProperty,MD=Object.getOwnPropertyDescriptor,bi=(s,t,e,r)=>{for(var i=r>1?void 0:r?MD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&AD(t,e,i),i};const Qf=(zS=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",Yf);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);g(this,rs,{mode:"ACTIVE_GRID",page:0});g(this,Ts,!1);g(this,la,!1);p(this,"updateConsumerSpatialLayers",Uu(()=>{const s={},t=new Map(this.maxSpatialLayerUpdates);this.maxSpatialLayerUpdates.clear(),Array.from(t.entries()).forEach(([e,r])=>{s[r]===void 0&&(s[r]={layer:r,consumerIds:[]}),s[r].consumerIds.push(e)}),Object.keys(s).forEach(e=>{const r=s[e];this.logger.log(`Switching max spatial layer to ${r.layer}`,{consumerIds:r.consumerIds}),this.roomNodeClient.switchConsumersToLayer(r.consumerIds,r.layer)})},2e3));p(this,"updateConsumers",async(s,t)=>{this.logger.info(`updateConsumers: Starting consumer updates - AddProducers: ${s.length}, RemoveProducers: ${t.length}, ConsumersSyncing: ${a(this,Ts)}`);try{s.length!==0&&(this.logger.info(`updateConsumers: Creating consumers for ${s.length} producers: [${s.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.createConsumers(s),this.logger.info("updateConsumers: Successfully created consumers."))}catch(e){this.logger.error("updateConsumers: Error creating consumers",{error:e})}try{t.length!==0&&(this.logger.info(`updateConsumers: Closing consumers for ${t.length} producers: [${t.map(e=>e.producerId).join(", ")}]`),await this.roomNodeClient.closeConsumers(t),this.logger.info("updateConsumers: Successfully closed consumers."))}catch(e){this.logger.error("updateConsumers: Error closing consumers",{error:e})}this.logger.info("updateConsumers: Completed consumer updates.")});this.context=s,this.roomSocketHandler=e,this.participants=new Qt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=hs,t.config.viewType!=="CHAT"&&this.setupEventsGlobal(),this.setupEvents()}get roomNodeClient(){return this.context.getValue("roomNodeClient")}get mediaJoined(){var s;return((s=this.roomNodeClient)==null?void 0:s.mediaJoined)===!0}get pip(){return this.context.getValue("pip")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}setupEvents(){this.roomSocketHandler.on(U.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(k.SOCKET_PEERS,s=>{const t=this.participants.joined.size>0;this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.joined.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",t&&this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount}),s==null||s.forEach(e=>{e.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(e))})}),this.roomSocketHandler.on(this.events.peerJoinedBroadcast,({participant:s})=>{this.logger.info("PEER_INFO:::MEDIA_JOIN",{participant:{id:s.peerId,maskedName:[...(s==null?void 0:s.displayName)||""].map((t,e)=>e%2?"*":t).join("")}}),this.onParticipantMediaJoined(s.peerId,s.producerStates)}),this.roomSocketHandler.on(this.events.selfJoinComplete,({participants:s,selectedPeers:t,roomState:e})=>{s.forEach(({peerId:n,producerStates:o})=>this.onParticipantMediaJoined(n,o));const{audioPeers:r,compulsoryPeers:i}=t!=null?t:{};e.pinnedPeerIds.length!==0&&this.onParticipantPinned(e.pinnedPeerIds[0]),this.computeActivateParticipants(r!=null?r:[],i),this.logger.info("selfJoinComplete: Emitting UPDATE_ACTIVE with createAllConsumers=true"),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(k.MAX_SPATIAL_LAYER_CHANGE,({peerId:s,maxSpatialLayer:t})=>{const e=this.videoPeerConsumerMap.get(s);e&&(this.maxSpatialLayerUpdates.set(e,t),this.updateConsumerSpatialLayers())}),this.context.getValue("peerSessionStore").on(k.NEW_PRODUCER,({peerId:s,producer:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{producer:{id:t==null?void 0:t.producerId,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}},participant:{id:s}});return}e.producers.push(t),this.logger.info("ParticipantController::NEW_PRODUCER::producer_added_to_participant",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"not_initialized",appData:{screenShare:t==null?void 0:t.screenShare}}}),(t==null?void 0:t.kind)==="audio"&&this.participants.audioSubscribed.get(s)||(t==null?void 0:t.kind)==="video"&&this.participants.videoSubscribed.get(s)||t!=null&&t.screenShare?(this.logger.info(`NEW_PRODUCER: scheduling syncConsumer (AUTO mode) - Producer: ${t.producerId}, Peer: ${s}, Kind: ${t.kind}, ScreenShare: ${t.screenShare}, ConsumersSyncing: ${a(this,Ts)}, VideoSub: ${t.kind==="video"?this.participants.videoSubscribed.has(s):"N/A"}, AudioSub: ${t.kind==="audio"?this.participants.audioSubscribed.has(s):"N/A"}`),this.scheduleSyncConsumers({source:"NEW_PRODUCER_AUTO"})):this.logger.info("ParticipantController::NEW_PRODUCER::not_consuming_producer_auto",{producer:{id:t==null?void 0:t.producerId,peerId:s,kind:t==null?void 0:t.kind,status:"UNKNOWN",appData:{screenShare:t==null?void 0:t.screenShare}}})}),this.context.getValue("peerSessionStore").on(k.PRODUCER_CLOSED,({peerId:s,producerId:t})=>{const e=this.participants.joined.get(s);if(!e){this.logger.warn("ParticipantController::NEW_PRODUCER::participant not found",{participant:{id:s}});return}e.producers=e.producers.filter(r=>r.producerId!==t)}),this.context.getValue("peerSessionStore").on(k.PRODUCER_TOGGLE,({peerId:s,producerId:t,paused:e,kind:r})=>{const i=this.participants.joined.get(s);if(i){r==="audio"&&i.setAudioEnabled(!e);const n=i.producers.find(o=>o.producerId===t);n&&(n.pause=e),r==="video"&&this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}}),this.roomSocketHandler.on(this.events.globalPeerPinBroadcast,s=>{let t;if(s&&(t=s.participantId),!this.mediaJoined)return;const e=t;this.onParticipantPinned(e);const r=this.participants.joined.get(e);r&&(this.logger.info(`globalPeerPinBroadcast: Scheduling audio/video consumer sync for pinned participant ${e} - ProducerCount: ${r.producers.length}, ConsumersSyncing: ${a(this,Ts)}, ProducerIds: [${r.producers.map(i=>i.producerId).join(", ")}]`),this.scheduleSyncConsumers({source:"GLOBAL_PEER_PIN"}))}),this.roomSocketHandler.on(this.events.selectedPeer,({audioPeers:s,compulsoryPeers:t})=>{this.mediaJoined&&this.onSelectedPeers(t.concat(s))}),this.roomSocketHandler.on(this.events.selectedPeerDiff,({entries:s})=>{if(!this.mediaJoined)return;const t=s.map(e=>({peerId:e.peerId,priority:e.priority}));this.updateActiveParticipantsWithPriorities(t,!0)})}waitingRoomRequestHandler(s){const t=s.requests.filter(r=>!this.participants.waitlisted.toArray().find(i=>i.userId===r.userId)),e=this.participants.waitlisted.toArray().filter(r=>!s.requests.find(i=>i.userId===r.userId));t.forEach(r=>this.participants.waitlisted.add(new sr(this.context,{id:r.peerId,displayName:r.displayName,audioMuted:!0,videoEnabled:!1,audioTrack:void 0,videoTrack:void 0,stageStatus:"OFF_STAGE",userId:r.userId,flags:{},isHost:!1,customParticipantId:r.customParticipantId,picture:r.picture,metadata:{preset_name:r.presetName}},this.self,this.roomSocketHandler))),e.forEach(r=>this.participants.waitlisted.delete(r.id))}get maxPreferredStreams(){return this.participants.maxActiveParticipantsCount}selectPagePeers(s){const{compulsoryPeers:t}=this.selectedPeers,e=t.filter(d=>this.participants.joined.has(d)),r=Array.from(this.participants.pinned.keys()).filter(d=>!e.includes(d)),i=Array.from(this.participants.joined.toArray().filter(d=>d.stageStatus==="ON_STAGE").map(d=>d.id)),n=Math.max((s-1)*(this.maxPreferredStreams-e.length-r.length)),o=s*(this.maxPreferredStreams-e.length-r.length);return e.concat(r,i.slice(n,o))}selectActivePeers(s){const t=new Map,e=Array.from(this.participants.joined.toArray().filter(u=>u.stageStatus==="ON_STAGE").map(u=>(t.set(u.id,!0),u.id))),r=this.selectedPeers.peers,i=this.participants.pinned.toArray().reduce((u,h)=>(h.stageStatus!=="ON_STAGE"?this.participants.pinned.delete(h.id):u.push(h.id),u),[]),n=this.self.stageStatus==="ON_STAGE"?1:0,o=s-n,c=new Set(r.concat(i).filter(u=>u!==this.self.id&&t.has(u)));let d=Array.from(c);const l=o-c.size;if(l>=0){const u=e.filter(h=>!c.has(h)&&h!==this.self.id).slice(0,l);d=Array.from(c).concat(u)}else d=d.slice(0,o);return d}updateMediaSubscribedMaps(s,t){const{page:e}=t!=null?t:{};s&&a(this,rs).mode!==s&&(a(this,rs).mode=s),e&&a(this,rs).page!==e&&(a(this,rs).page=e);const{mode:r,page:i}=a(this,rs);switch(r){case"PAGINATED":{if(!i)return;const n=this.selectPagePeers(i),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMap(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o),this.logger.debug("ParticipantController::updateActive::updating_current_page_peers",{peerIds:n});break}case"ACTIVE_GRID":{const n=this.selectActivePeers(this.participants.maxActiveParticipantsCount),o=this.selectActivePeers(this.participants.maxActiveParticipantsCount+4);this.updateParticipantsMapMinReplacement(this.participants.videoSubscribed,n),this.updateParticipantsMap(this.participants.audioSubscribed,o);break}case"MANUAL":break;default:throw new Error(`View mode ${s} not supported`)}}async scheduleSyncConsumers({source:s}){var e,r,i;const t=((e=a(this,rs))==null?void 0:e.mode)==="PAGINATED"&&!a(this,Ts)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,rs))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,Ts)}, Delay: ${t}, Page: ${(i=a(this,rs))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var l,u,h,m,S;if(((h=(u=(l=this.context.getValue("connectionHandler"))==null?void 0:l.mediaState)==null?void 0:u.recv)==null?void 0:h.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,Ts)){f(this,la,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,Ts,!0),f(this,la,!1);let s=[];this.participants.videoSubscribed.forEach(y=>{var C,D;const w=this.participants.joined.get(y.id),_=(D=(C=y.producers)==null?void 0:C.filter(V=>V.kind==="video"))!=null?D:[];w&&(_!=null&&_.length)&&_.forEach(V=>{var F,Z,be,Ge;const $=((Z=(F=w.manualProducerConfig)==null?void 0:F.video)!=null?Z:!0)&&V.kind==="video"&&!V.screenShare,H=((Ge=(be=w.manualProducerConfig)==null?void 0:be.screenshareVideo)!=null?Ge:!0)&&V.kind==="video"&&V.screenShare;($||H)&&(V.pause||s.push(V))})}),this.participants.audioSubscribed.forEach(y=>{var C,D;const w=this.participants.joined.get(y.id),_=(D=(C=y.producers)==null?void 0:C.filter(V=>V.kind==="audio"))!=null?D:[];w&&(_!=null&&_.length)&&_.forEach(V=>{var F,Z,be,Ge;const $=((Z=(F=w.manualProducerConfig)==null?void 0:F.audio)!=null?Z:!0)&&V.kind==="audio"&&!V.screenShare,H=((Ge=(be=w.manualProducerConfig)==null?void 0:be.screenshareAudio)!=null?Ge:!0)&&V.kind==="audio"&&V.screenShare;($||H)&&s.push(V)})}),s=C_(s,y=>y.producerId);const t=new Map;s.forEach(y=>{t.set(y.producerId,y)});const e=(m=this.roomNodeClient)==null?void 0:m.getConsumers();let r=s.filter(y=>!(e!=null&&e.has(y.producerId)));s.filter(y=>!y.consumer&&(e==null?void 0:e.has(y.producerId))).forEach(y=>{const w=e.get(y.producerId);w&&(this.logger.info(`syncConsumers: remapping existing consumer ${w.id} to producer ${y.producerId}`),this.context.getValue("peerSessionStore").emit(k.NEW_CONSUMER,{id:w.id,appData:w.appData,peerId:w.peerId}))});let n=[],o=Array.from((S=e==null?void 0:e.values())!=null?S:[]).map(y=>y.peerId);o=k_(o),o==null||o.forEach(y=>{var _;const w=this.participants.joined.get(y);if(!w){this.logger.warn(`Peer with ${y} doesn't exist in joined list but producers of it are being consumed.`);return}(_=w.producers)!=null&&_.length&&w.producers.forEach(C=>{const D=C.consumer&&e.has(C.consumer.id);!t.has(C.producerId)&&(e.has(C.producerId)||D)&&n.push(C)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(y=>y.producerId).join(", ")}], RemoveProducers: ${n.length} [${n.map(y=>y.producerId).join(", ")}]`.substring(0,5e3));const c=35,d=35;r.length>c&&(this.logger.warn(`syncConsumers: Too many remote producers to create consumers: ${r.length}. Only adding ${c} in this run.`),r=r.slice(0,c),this.scheduleSyncConsumers({source:"SOFT_CAPPED_CREATE_CONSUMERS"})),n.length>d&&(this.logger.warn(`syncConsumers: Too many remote producers to close consumers: ${n.length}. Only removing ${d} in this run.`),n=n.slice(0,d),this.scheduleSyncConsumers({source:"SOFT_CAPPED_REMOVE_CONSUMERS"}));try{r.length>0||n.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${n.length}.`),await this.updateConsumers(r,n),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(y){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:y})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,Ts,!1)}a(this,la)&&(this.logger.info("syncConsumers: Resync required, calling syncConsumers again."),this.syncConsumers())}computeActivateParticipants(s,t){const e=s.map((i,n)=>({peerId:i,priority:n+1})),r=t==null?void 0:t.map((i,n)=>({peerId:i,priority:-(n+1)}));e.push(...r!=null?r:[]),e.length>0&&this.updateActiveParticipantsWithPriorities(e)}createParticipantObjFromSocketPeer(s){const t=Qf.formatSocketPeerMessage(s);return new sr(this.context,{...t,isHost:!1,videoEnabled:!1,audioMuted:!0,videoTrack:void 0,audioTrack:void 0},this.self,this.roomSocketHandler)}updatePipSource(s,t){var e,r;t?(e=this.pip)==null||e.enableSource(s):(r=this.pip)==null||r.disableSource(s)}onParticipantMediaJoined(s,t){if(!this.mediaJoined||s===this.self.id)return;const e=this.participants.joined.get(s);if(!e){this.logger.warn(`Received media.peerJoinedBroadcast for non-existent peer ${s}`);return}this.logger.info("PEER_INFO:::SOCKET_ON_MEDIA_JOIN",{participant:{id:e.id,maskedName:[...(e==null?void 0:e.name)||""].map((r,i)=>i%2?"*":r).join("")}}),this.logger.info(`onParticipantMediaJoined: peer ${s} has joined media room. Processing.`),t.forEach(r=>{r.kind===zs.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===zs.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===zs.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}updateParticipantsMapMinReplacement(s,t){const e=Array.from(s.keys()),r=new Map(s),i=new Set(t),n=[];e.forEach((o,c)=>{(!i.has(o)||!this.participants.joined.get(o))&&n.push(c)}),t.forEach(o=>{if(s.get(o))return;if(e.length<t.length){e.push(o);return}const c=n.shift();e[c]=o}),n.forEach(o=>{e.splice(o,1)}),Array.from(s.keys()).forEach(o=>{s.delete(o,!i.has(o))}),e.forEach(o=>{if(!this.participants.joined.get(o)){this.logger.warn("updateActiveParticipants::participant_not_in_joined_list",{participant:{id:o}});return}s.add(this.participants.joined.get(o),!r.get(o))}),s.emit("participantsUpdate")}updateParticipantsMap(s,t){Array.from(s.keys()).forEach(r=>{t.includes(r)||s.delete(r,!0)}),t.forEach(r=>{s.get(r)||s.add(this.participants.joined.get(r),!0)}),s.emit("participantsUpdate")}updatePinnedParticipants(){this.participants.pinned.forEach(s=>{s.setIsPinned(!1),this.participants.pinned.delete(s.id)})}setupEventsGlobal(){this.roomSocketHandler.on(U.joinRoom,({peer:s})=>{s.waitlisted||(this.logger.info("Processing socket join",{peers:s.peerId}),this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(s)),this.logger.info("Processed socket join",{peers:s.peerId}))}),this.roomSocketHandler.on(U.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(k.SOCKET_SERVICE_ROOM_JOINED,()=>{this.self.permissions.acceptWaitingRequests&&this.roomSocketHandler.getWaitingRoomRequests()}),this.self.permissions.on("permissionsUpdate",s=>{const{acceptWaitingRequests:t}=s;t!==void 0&&(t?this.roomSocketHandler.getWaitingRoomRequests():this.participants.waitlisted.clear())}),this.context.getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,()=>{this.logger.info("Socket disconnected — keeping participants visible for seamless reconnection")}),this.context.getValue("peerSessionStore").on(k.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(k.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(k.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(k.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(k.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(k.MESSAGE,async({payload:s,type:t,timestamp:e})=>{t!=="spotlight"&&this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(k.LOW_CONSUMER_SCORE,({peerId:s,score:t,kind:e})=>{const r=this.participants.joined.get(s);r&&(r.emit("poorConnection",{score:t,kind:e}),this.participants.emit("poorConnection",{participantId:s,score:t,kind:e}))}),this.context.getValue("peerSessionStore").on(k.CONSUMER_SCORE_UPDATE,({score:s,kind:t,appData:e,peerId:r,scoreStats:i})=>{var c;const n=t==="video"&&((c=e==null?void 0:e.screenShare)!=null?c:!1),o=this.participants.joined.get(r);o&&(o.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}),this.participants.emit("mediaScoreUpdate",{kind:t,isScreenshare:n,score:s,participantId:r,scoreStats:i}))}),this.context.getValue("peerSessionStore").onAsync(k.KICK_PEER,async({peerId:s})=>{const t=this.participants.joined.get(s);this.roomNodeClient.kick(s),await this.roomSocketHandler.kick(s),t?t.emit("kicked"):this.participants.joined.emit("kicked",{id:s})}),this.context.getValue("peerSessionStore").on(k.UPDATE_ACTIVE,({viewMode:s,page:t,createAllConsumers:e}={})=>{this.logger.info(`UPDATE_ACTIVE event received - viewMode: ${a(this,rs).mode}, page: ${t}, CreateAllConsumers: ${e}`),e&&(this.logger.info(`UPDATE_ACTIVE viewMode: ${s}, Page: ${t}, Removing existing subscriptions.`),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear()),this.updateMediaSubscribedMaps(s,{page:t}),this.scheduleSyncConsumers({source:"UPDATE_ACTIVE"})})}async onParticipantPinned(s){if(!s){this.self.isPinned&&this.self.setIsPinned(!1),this.participants.pinned.size!==0&&this.updatePinnedParticipants();return}if(s===this.self.id){this.participants.pinned.size!==0&&this.updatePinnedParticipants(),this.self.setIsPinned(!0);return}const t=this.participants.joined.get(s);this.self.isPinned&&this.self.setIsPinned(!1),this.updatePinnedParticipants(),t.setIsPinned(!0),this.participants.pinned.add(t)}async onParticipantSocketJoined(s){var t,e,r;this.logger.info(`onParticipantSocketJoined: peer ${s.id} has joined socket edge. Processing.`),this.self.id!==s.id&&!((t=s.flags)!=null&&t.recorder)&&!((e=s.flags)!=null&&e.hidden_participant)&&!((r=s.flags)!=null&&r.hiddenParticipant)&&(this.participants.videoSubscribed.delete(s.id),this.participants.audioSubscribed.delete(s.id),this.participants.joined.add(s),this.participants.waitlisted.delete(s.id),s.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(k.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(k.PEER_JOINED_INTERNAL,s)}async onParticipantLeave(s){const t=this.participants.joined.get(s);this.participants.joined.delete(s,!0,!0),this.participants.pinned.delete(s,!0,!0),this.participants.waitlisted.delete(s,!0,!0),this.roomNodeClient&&this.roomNodeClient.closeConsumers(t==null?void 0:t.producers),t&&t.stageStatus==="REQUESTED_TO_JOIN_STAGE"&&this.context.getValue("peerSessionStore").emit(k.UPDATE_STAGE_REQUESTS,{request:{displayName:t.name,userId:t.userId,peerId:t.id},add:!1});const{currentPage:e}=this.participants,r=this.maxPreferredStreams*(e-1),i=this.participants.videoSubscribed.get(s);this.participants.viewMode==="MANUAL"?this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e}):r===0?this.participants.setViewMode("ACTIVE_GRID"):this.participants.joined.size<=r?e===2?this.participants.setViewMode("ACTIVE_GRID"):this.participants.setPage(e-1):i&&this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:e})}processMedia(s){var h;const t=this.roomNodeClient.getConsumers(),{peerId:e,kind:r,appData:i,track:n,producerId:o,rtpReceiver:c,paused:d,localId:l}=(h=t.get(s))!=null?h:{};if(!e)return this.logger.warn("processMedia::Peer ID is undefined",{consumer:{id:s,kind:r,peerId:e,appData:{supportsRemoteControl:!!(i!=null&&i.supportsRemoteControl),screenShare:!!(i!=null&&i.screenShare)},remotelyPaused:d,producerId:o}}),{};const u=i;return r==="video"&&u.screenShare!==!0&&this.videoPeerConsumerMap.set(e,s),this.logger.info("ParticipantController::processMedia",{consumer:{id:s,peerId:e,kind:r,appData:u,remotelyPaused:d,producerId:o}}),this.consumerPeerMap.set(s,{type:r,peerId:e,appData:u,remotelyPaused:d,producerId:o}),{peerId:e,kind:r,appData:u,remotelyPaused:d,track:n,producerId:o,rtpReceiver:c,localId:l}}processConsumerClosed(s){const{peerId:t,type:e,appData:r,remotelyPaused:i,producerId:n}=this.consumerPeerMap.get(s)||{},o=this.participants.joined.get(t);if(this.logger.info("ParticipantController::processConsumerClosed",{consumer:{id:s,peerId:t,appData:r,kind:e,remotelyPaused:i,producerId:n}}),this.consumerPeerMap.delete(s),e==="video"&&r.screenShare!==!0&&this.videoPeerConsumerMap.delete(t),!o)return;const c=o.producers.find(l=>l.producerId===n);c&&(c.consumer={id:s,peerId:t,kind:void 0,appData:r,paused:i,producerId:n,rtpReceiver:void 0,localId:void 0});const d=[];r&&r.screenShare?(o.setScreenShareEnabled(!1),this.context.getValue("callstats").consumerSharedMediaState(s,{screen:!1}),o.screenShareTracks.video&&d.push(o.screenShareTracks.video.id),o.screenShareTracks.audio&&d.push(o.screenShareTracks.audio.id),o.screenShareTracks={audio:void 0,video:void 0}):e==="audio"?(o.setAudioEnabled(!1),o.audioTrack&&d.push(o.audioTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!1}),o.audioTrack=void 0):e==="video"&&(o.setVideoEnabled(!1),this.updatePipSource(o.id,!1),o.videoTrack&&d.push(o.videoTrack.id),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1}),o.videoTrack=void 0),r.e2ee&&d.forEach(l=>{this.context.getValue("peerSessionStore").emit(k.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:l})})}processConsumerResumed(s){var m;const t=this.processMedia(s),{peerId:e,kind:r,appData:i,track:n,remotelyPaused:o,producerId:c,rtpReceiver:d,localId:l}=t;if(!e)return;this.logger.info("ParticipantController::processConsumerResumed",{consumer:{id:s,peerId:e,kind:r,appData:i,remotelyPaused:o,producerId:c}});const u=this.participants.joined.get(e);if(!u)return;const h=u.producers.find(S=>S.producerId===c);if(h&&(h.consumer={id:s,peerId:e,kind:r,appData:i,paused:o,producerId:c,rtpReceiver:d,localId:l}),i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_CONSUMER,{peerId:e,rtpReceiver:d,track:n}),i.screenShare){r==="video"?u.screenShareTracks.video=n:r==="audio"&&(u.screenShareTracks.audio=n),u.setScreenShareEnabled(!0),(m=this.context)==null||m.getValue("callstats").consumerSharedMediaState(s,{screen:!0});return}r==="video"?(u.videoTrack=n,u.setVideoEnabled(!0),this.updatePipSource(u.id,!0),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!0})):r==="audio"&&(u.audioTrack=n,u.setAudioEnabled(u.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:u.audioEnabled}))}processConsumerPaused(s){this.logger.info(`ParticipantController::processConsumerPaused called for consumerId: ${s}`);const{peerId:t,kind:e,track:r,appData:i,remotelyPaused:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processConsumerPaused",{consumer:{id:s,peerId:t,kind:e,appData:i,remotelyPaused:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);u&&(u.consumer={id:s,peerId:t,kind:e,appData:i,paused:n,producerId:o,rtpReceiver:c,localId:d}),r&&i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_INACTIVE_CONSUMER,{peerId:t,trackId:r.id}),e==="video"?(l.videoTrack=r,l.setVideoEnabled(!1),this.updatePipSource(l.id,!1),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!1})):e==="audio"&&(l.audioTrack=r,l.setAudioEnabled(l.audioEnabled),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:l.audioEnabled}))}processNewConsumer(s){const{peerId:t,kind:e,remotelyPaused:r,track:i,appData:n,producerId:o,rtpReceiver:c,localId:d}=this.processMedia(s);if(!t)return;this.logger.info("ParticipantController::processNewConsumer",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});const l=this.participants.joined.get(t);if(!l)return;const u=l.producers.find(h=>h.producerId===o);if(u&&(u.consumer={id:s,peerId:t,kind:e,appData:n,paused:r,producerId:o,rtpReceiver:c,localId:d}),n.screenShare){e==="video"?l.screenShareTracks.video=i:e==="audio"&&(l.screenShareTracks.audio=i),(!r||this.self.permissions.isRecorder)&&l.setScreenShareEnabled(!0),n.supportsRemoteControl&&(l.supportsRemoteControl=!0),this.participants.broadcastMessage("screenshareConsumerCreated",{producerId:o,peerId:t,screenShare:!0,consumerId:s,consumerPeerId:this.self.id}),this.logger.info("ParticipantController::newScreenshareConsumer::screenshareConsumerCreated",{consumer:{id:s,peerId:t,kind:e,remotelyPaused:r,appData:n,producerId:o}});return}e==="video"?(l.videoTrack=i,r||(l.setVideoEnabled(!0),this.updatePipSource(l.id,!0)),this.context.getValue("callstats").consumerSharedMediaState(s,{video:!r})):e==="audio"&&(l.audioTrack=i,r||l.setAudioEnabled(!0),this.context.getValue("callstats").consumerSharedMediaState(s,{audio:!r})),!r&&n.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=fh(s.stageType);return{id:s.peerId,userId:s.userId,name:s.displayName,displayName:s.displayName,stageType:t,customParticipantId:s.customParticipantId,presetId:s.presetId,picture:s.displayPictureUrl,waitlisted:s.waitlisted,stageStatus:t,metadata:{preset_name:(e=s.flags)==null?void 0:e.presetName},recorderType:(r=s.flags)==null?void 0:r.recorderType,flags:{hiddenParticipant:(i=s.flags)==null?void 0:i.hiddenParticipant,hidden_participant:(n=s.flags)==null?void 0:n.hiddenParticipant,recorder:((o=s.flags)==null?void 0:o.recorderType)!==void 0&&((c=s.flags)==null?void 0:c.recorderType)!=="NONE"}}}async onSelectedPeers(s,t){this.participants.viewMode==="ACTIVE_GRID"&&this.computeActivateParticipants(s,t)}updateActiveParticipantsWithPriorities(s,t=!1){if(this.participants.viewMode==="MANUAL")return;if(!this.mediaJoined){this.logger.warn("Skipped::ParticipantController::updateActiveParticipantsWithPriorities",{roomJoined:this.mediaJoined});return}s.forEach(r=>{this.selectedPeers.add(r.peerId,r.priority,this.context)});const e=this.selectedPeers.activeSpeakerPeers.at(0);e!==void 0&&e!==this.participants.lastActiveSpeaker&&(this.participants.lastActiveSpeaker=e,this.participants.emit("activeSpeaker",{peerId:e,volume:1})),t&&this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},rs=new WeakMap,Ts=new WeakMap,la=new WeakMap,zS);let rr=Qf;bi([E.trace("ParticipantController.setupEvents")],rr.prototype,"setupEvents",1),bi([E.trace("ParticipantController.setupEvents")],rr.prototype,"setupEventsGlobal",1),bi([E.trace("ParticipantController.processMedia")],rr.prototype,"processMedia",1),bi([E.trace("ParticipantController.processConsumerClosed")],rr.prototype,"processConsumerClosed",1),bi([E.trace("ParticipantController.processConsumerResumed")],rr.prototype,"processConsumerResumed",1),bi([E.trace("ParticipantController.processConsumerPaused")],rr.prototype,"processConsumerPaused",1),bi([E.trace("ParticipantController.processNewConsumer")],rr.prototype,"processNewConsumer",1);const Me=Is(Hu().permissions),kl=class extends Dt{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);g(this,yt);g(this,Y,void 0);g(this,ua,void 0);g(this,ha,void 0);g(this,_l,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&Cr(a(this,Y).chat.private,r.private),r.public&&Cr(a(this,Y).chat.public,r.public),this.emit("chatUpdate")),i&&Cr(a(this,Y).connectedMeetings,i),c){const m=y=>{switch(y){case Ir.NONE:return G.Allowed;case Ir.ALLOWED:return G.Allowed;case Ir.NOT_ALLOWED:return G.NotAllowed;case Ir.CAN_REQUEST:return G.CanRequest;default:return}},S={audio:void 0,video:void 0,screenshare:void 0};(l=c.audio)!=null&&l.canProduce&&(S.audio={canProduce:m(c.audio.canProduce)}),(u=c.video)!=null&&u.canProduce&&(S.video={canProduce:m(c.video.canProduce)}),(h=c.screenshare)!=null&&h.canProduce&&(S.screenshare={canProduce:m(c.screenshare.canProduce)}),Cr(a(this,Y).media,S)}n&&(Cr(a(this,Y).plugins,n),this.emit("pluginsUpdate")),o&&(Cr(a(this,Y).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Cr(a(this,Y),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new R("Could not load preset permissions.","0904");f(this,ha,e),f(this,ua,i),f(this,Y,r),n&&this.setupEvents()}setupEvents(){a(this,ha).getValue("peerSessionStore").on(k.UPDATE_PERMISSIONS,a(this,_l))}static init(e,r,i){let n;return i?n=new kl(e,i,r,!0):n=new kl(e,Me,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,Y))==null?void 0:e.stageEnabled)||a(this,ua)===Ws.Webinar||a(this,ua)===Ws.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,Y))==null?void 0:e.acceptStageRequests)||((r=a(this,Y))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,Y))==null?void 0:e.stageAccess)===G.NotAllowed?G.NotAllowed:((r=a(this,Y))==null?void 0:r.stageAccess)===G.CanRequest?G.CanRequest:((i=a(this,Y))==null?void 0:i.stageAccess)===G.Allowed||a(this,Y).media.audio.canProduce===G.Allowed||a(this,Y).media.video.canProduce===G.Allowed||a(this,Y).media.screenshare.canProduce===G.Allowed?G.Allowed:a(this,Y).media.audio.canProduce===G.CanRequest||a(this,Y).media.video.canProduce===G.CanRequest||a(this,Y).media.screenshare.canProduce===G.CanRequest?G.CanRequest:G.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.acceptWaitingRequests)!=null?r:Me.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===G.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,Y))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===G.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.disableParticipantAudio)!=null?r:Me.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canAcceptProductionRequests)!=null?r:Me.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.disableParticipantVideo)!=null?r:Me.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.kickParticipant)!=null?r:Me.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.pinParticipant)!=null?r:Me.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canRecord)!=null?r:Me.canRecord}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.waitingRoomType)!=null?r:Me.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.plugins)!=null?r:Me.plugins}get polls(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.polls)!=null?r:Me.polls}get canProduceVideo(){var r;const e=(r=a(this,Y).media.video.canProduce)!=null?r:Me.media.video.canProduce;return this.stageEnabled&&(a(this,yt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,yt,Gt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,yt,Gt)==="OFF_STAGE"||a(this,yt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceScreenshare(){var r;const e=(r=a(this,Y).media.screenshare.canProduce)!=null?r:Me.media.screenshare.canProduce;return this.stageEnabled&&(a(this,yt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,yt,Gt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,yt,Gt)==="OFF_STAGE"||a(this,yt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get canProduceAudio(){var r;const e=(r=a(this,Y).media.audio.canProduce)!=null?r:Me.media.audio.canProduce;return this.stageEnabled&&(a(this,yt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,yt,Gt)==="ON_STAGE")&&e===G.CanRequest?G.Allowed:this.stageEnabled&&(a(this,yt,Gt)==="OFF_STAGE"||a(this,yt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===G.Allowed?G.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Me.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,Y))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Me.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.connectedMeetings)!=null?r:Me==null?void 0:Me.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.hiddenParticipant)!=null?r:Me.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,Y).showParticipantList)!=null?e:Me.showParticipantList}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,Y))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Me.canChangeParticipantPermissions}get canEditDisplayName(){var e;return(e=a(this,Y).canEditDisplayName)!=null?e:!1}get isRecorder(){return a(this,Y).isRecorder}get canSpotlight(){return a(this,Y).canSpotlight}get canLivestream(){return a(this,Y).canLivestream}get transcriptionEnabled(){return a(this,Y).transcriptionEnabled}};let Ch=kl;Y=new WeakMap,ua=new WeakMap,ha=new WeakMap,_l=new WeakMap,yt=new WeakSet,Gt=function(){return a(this,ha).getValue("stageStatus")};class Xf extends Dt{constructor(e,r){super(r);p(this,"localMediaHandler");g(this,Bt,void 0);f(this,Bt,e)}async updatePermission(){var d,l;const e=(u,h)=>{this.mediaPermissions[u]=h;const m={message:this.mediaPermissions[u],kind:u};h==="DENIED"?a(this,Bt).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_ERROR,m):a(this,Bt).getValue("peerSessionStore").emit(k.MEDIA_PERMISSION_UPDATE,m)};if(Te.getName()==="firefox")return;const r="microphone",i="camera",n=await((d=navigator==null?void 0:navigator.permissions)==null?void 0:d.query({name:r})),o=await((l=navigator==null?void 0:navigator.permissions)==null?void 0:l.query({name:i})),c=(u,h)=>{switch(h){case"granted":e(u,"ACCEPTED");break;case"denied":e(u,"DENIED");break;case"prompt":e(u,"NOT_REQUESTED");break}this.localMediaHandler.repopulateAvailableDevices()};n&&(n.onchange=()=>c("audio",n.state)),o&&(o.onchange=()=>c("video",o.state))}async populateMediaPermissionsInCallstats({message:e,kind:r}){var i,n,o,c;switch(r){case"audio":{(i=a(this,Bt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,Bt))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,Bt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,Bt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,Bt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(Te.init(),i&&f(this,Bt,i),!this.localMediaHandler)try{let m=!0;if((n=i==null?void 0:i.getValue("defaults"))!=null&&n.mediaHandler)m=!1,this.localMediaHandler=i.getValue("defaults").mediaHandler.localMediaHandler;else if(navigator.RNLocalMediaHandlerImpl){const{RNLocalMediaHandlerImpl:S}=navigator;this.localMediaHandler=await S.init(e)}else this.localMediaHandler=new _t(i,e.constraints,(o=i==null?void 0:i.getValue("defaults"))==null?void 0:o.isNonPreferredDevice,(c=i==null?void 0:i.getValue("defaults"))==null?void 0:c.autoSwitchAudioDevice);if(i==null||i.getValue("peerSessionStore").on(k.MEDIA_PERMISSION_UPDATE,async S=>{if(this.populateMediaPermissionsInCallstats({message:S.message,kind:S.kind}),S.message==="NOT_REQUESTED")switch(S==null?void 0:S.kind){case"audio":this.rawAudioTrack&&(this.logger.info("Disabling audio due to media permission update"),this.disableAudio());break;case"video":this.rawVideoTrack&&(this.logger.info("Disabling video due to media permission update"),this.disableVideo());break;default:break}this.emit("mediaPermissionUpdate",S)}),i==null||i.getValue("peerSessionStore").on(k.MEDIA_PERMISSION_ERROR,async S=>{const{kind:y,message:w,constraints:_}=S;this.populateMediaPermissionsInCallstats({message:w,kind:y}),y==="audio"?(this.logger.info(`Disabling audio due to media permission error skipping: ${this.localMediaHandler.audioUpdateInProgress}`),this.localMediaHandler.audioUpdateInProgress===!1&&this.disableAudio()):y==="video"&&(this.logger.info(`Disabling video due to media permission error skipping: ${this.localMediaHandler.videoUpdateInProgress}`),this.localMediaHandler.videoUpdateInProgress===!1&&this.disableVideo()),this.logger.error("SelfController::mediaPermissionError",{error:{message:w},constraints:_,mediaPermissionsErrors:{kind:y,message:w}}),this.emit("mediaPermissionError",S),this.emit("mediaPermissionUpdate",{message:w,kind:y})}),m){this.logger.info(`Setting up SelfMedia streams using media handler. audio:${(d=e==null?void 0:e.audio)!=null?d:!0} video:${(l=e==null?void 0:e.video)!=null?l:!0}`);const S=this.localMediaHandler.setupStreams({video:(u=e==null?void 0:e.video)!=null?u:!0,audio:(h=e==null?void 0:e.audio)!=null?h:!0});r||await S}}catch(m){this.logger.error("Self::init::Failed To Setup Streams",{error:{name:m.name,message:m.message}})}}set context(e){f(this,Bt,e),this.localMediaHandler.context=e}get audioTrack(){return this.localMediaHandler.audioTrack}get rawAudioTrack(){return this.localMediaHandler.rawAudioTrack}get mediaPermissions(){return this.localMediaHandler.permissions}async addAudioMiddleware(e){return this.localMediaHandler.addAudioMiddleware(e)}async removeAudioMiddleware(e){return this.localMediaHandler.removeAudioMiddleware(e)}async removeAllAudioMiddlewares(){return this.localMediaHandler.removeAllAudioMiddlewares()}get videoTrack(){return this.localMediaHandler.videoTrack}get rawVideoTrack(){return this.localMediaHandler.rawVideoTrack}async addVideoMiddleware(e){return this.localMediaHandler.addVideoMiddleware(e)}async setVideoMiddlewareGlobalConfig(e={disablePerFrameCanvasRendering:!1}){return this.localMediaHandler.setVideoMiddlewareGlobalConfig(e)}async removeVideoMiddleware(e){return this.localMediaHandler.removeVideoMiddleware(e)}async removeAllVideoMiddlewares(){return this.localMediaHandler.removeAllVideoMiddlewares()}get screenShareTracks(){return this.localMediaHandler.screenShareTracks}get audioEnabled(){return this.localMediaHandler.audioEnabled}get videoEnabled(){return this.localMediaHandler.videoEnabled}get screenShareEnabled(){return this.localMediaHandler.screenShareEnabled}async enableAudio(){await this.localMediaHandler.enableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableVideo(){await this.localMediaHandler.enableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}async disableAudio(){this.localMediaHandler.disableAudio(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}async enableScreenShare(){await this.localMediaHandler.enableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableScreenShare(){await this.localMediaHandler.disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}async disableVideo(){await this.localMediaHandler.disableVideo(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}getCurrentDevices(){return this.localMediaHandler.getCurrentDevices()}async getAudioDevices(){return await this.localMediaHandler.getAudioDevices()}async getVideoDevices(){return await this.localMediaHandler.getVideoDevices()}async getSpeakerDevices(){return await this.localMediaHandler.getSpeakerDevices()}getDeviceById(e,r){let i;return r==="audio"?i="audioinput":r==="video"?i="videoinput":r==="speaker"&&(i="audiooutput"),this.localMediaHandler.getDeviceById(e,i)}async setDevice(e){switch(e.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(e,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(e,{saveDevicePreference:!0})}catch(r){}finally{this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}this.emit("deviceUpdate",{device:e})}}Bt=new WeakMap;var OD=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,ft=(s,t,e,r)=>{for(var i=r>1?void 0:r?DD(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&OD(t,e,i),i};let Ke=(YS=class extends Xf{constructor(t,e,r,i,n){const o=t.getValue("logger");super(t,o);g(this,gr);g(this,Ze);g(this,ga);g(this,Be);g(this,Yo);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");g(this,pa,void 0);g(this,Et,void 0);g(this,ma,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");g(this,Xe,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");g(this,fa,new Set);g(this,Sa,new Set);f(this,Xe,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=e.customParticipantId,this.waitlistStatus="none",f(this,Et,r),f(this,pa,i),this.hidden=!1,f(this,ma,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=Te.isElectron(),this.device=Te.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),L(this,Yo,op).call(this)}get telemetry(){return a(this,Xe).getValue("telemetry")}get stageStatus(){return a(this,Xe).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,Ze,gt).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,Xe).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var m,S,y,w,_,C;let c=(S=(m=t.getValue("defaults"))==null?void 0:m.audio)!=null?S:!0,d=(w=(y=t.getValue("defaults"))==null?void 0:y.video)!=null?w:!0;r.canProduceAudio!=="ALLOWED"&&(c=!1),r.canProduceVideo!=="ALLOWED"&&(d=!1);const l=new Ke(t,e,r,i,n),u=qO(i.mediaConstraints);Cr(u,(_=t.getValue("defaults"))==null?void 0:_.mediaConfiguration);const h=(C=t.getValue("defaults"))==null?void 0:C.mediaHandler;return h&&(h.context=t),await l.init({audio:c,video:d,constraints:u},o,t),l.setupEvents(),l}cleanupEvents(){this.removeAllListeners("videoUpdate"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("VIDEO_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_CHANGE"),this.localMediaHandler.removeAllListeners("DEVICE_LIST_UPDATED"),this.localMediaHandler.removeAllListeners("SCREENSHARE_TRACK_CHANGE"),this.localMediaHandler.removeAllListeners("SCREENSHARE_ENDED"),this.localMediaHandler.removeAllListeners("AUDIO_TRACK_SILENT"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_AUDIO"),this.localMediaHandler.removeAllListeners("FORCE_MUTE_VIDEO"),a(this,Et).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",L(this,Yo,op));const t=a(this,ga,uu);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...Ei(this)}),a(this,Be,We)&&this.audioEnabled)try{await a(this,Ze,gt).shareMic(this.audioTrack)}catch(e){this.logger.error("Self::setupEvents::Error while sharing mic",{error:e}),this.localMediaHandler.disableAudio()}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}),this.localMediaHandler.on("VIDEO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::VIDEO_TRACK_CHANGE",{...Ei(this)}),a(this,Be,We)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,Be,We))try{await a(this,Ze,gt).shareWebcam(this.videoTrack)}catch(e){this.logger.error("Self::setupEvents::failed shareWebcam",{error:e}),this.videoEnabled&&await this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}),this.localMediaHandler.on("DEVICE_CHANGE",async({device:e})=>{var r;this.emit("deviceUpdate",{device:e}),e.kind==="audiooutput"&&typeof HTMLAudioElement.prototype.setSinkId=="function"&&((r=a(this,ga,uu))==null||r.setSpeakerDevice(e.deviceId))}),this.localMediaHandler.on("DEVICE_LIST_UPDATED",e=>{this.emit("deviceListUpdate",e)}),this.localMediaHandler.on("SCREENSHARE_TRACK_CHANGE",async()=>{if(!a(this,Be,We)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,Ze,gt).shareScreen(this.screenShareTracks)}catch(e){this.logger.error("Self::setupEvents::Error while sharing screen",{error:e}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.logger.info("Self::setupEvents::SCREENSHARE_TRACK_CHANGE",{...Ei(this)}),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}),this.localMediaHandler.on("SCREENSHARE_ENDED",async()=>{this.logger.log("Disabling screenshare due to SCREENSHARE_ENDED"),await this.disableScreenShare(),this.logger.info("Self::setupEvents::SCREENSHARE_ENDED",{...Ei(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,Xe))==null||e.getValue("callstats").mediaTrackMuted("AUDIO")}),this.localMediaHandler.on("FORCE_MUTE_AUDIO",()=>{this.disableAudio()}),this.localMediaHandler.on("FORCE_MUTE_VIDEO",async()=>{var e;a(this,Be,We)&&await a(this,Ze,gt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,Xe))==null||e.getValue("callstats").videoOff()}),a(this,Et).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,Et).canProduceAudio!==G.Allowed&&(this.disableAudio(),this.logger.info(`Disabled audio due to dynamic preset change: canProduceAudio: ${this.permissions.canProduceAudio}`)),(i=e==null?void 0:e.media)!=null&&i.video&&a(this,Et).canProduceVideo!==G.Allowed&&(this.disableVideo(),this.logger.info(`Disabled video due to dynamic preset change: canProduceVideo: ${this.permissions.canProduceVideo}`)),(n=e==null?void 0:e.media)!=null&&n.screenshare&&a(this,Et).canProduceScreenshare!==G.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,Et)}get config(){return a(this,pa)}get roomJoined(){var t;return a(this,pa).viewType===Ws.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Xe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,Be,We)}setName(t){if(!t)throw new R("Name cannot be empty.","1103");this.name=t}async setupTracks(t={}){t.forceReset,await this.disableAudio(),await this.disableVideo(),this.localMediaHandler.removeAudioTrack(),this.localMediaHandler.removeVideoTrack(),t.audio&&await this.enableAudio(),t.video&&await this.enableVideo()}async destructMediaHandler(){return this.localMediaHandler.destruct()}async removeDocumentEventListeners(){return this.localMediaHandler.removeDocumentEventListeners()}async enableAudio(t){var e;if(this.permissions.canProduceAudio!==G.NotAllowed&&!(a(this,Et).canProduceAudio===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,Xe))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,Be,We)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,Ze,gt).shareMic(this.audioTrack)}catch(r){this.logger.error("Self::enableAudio::Error while sharing mic",{error:r}),this.localMediaHandler.disableAudio()}if(!this.audioEnabled)return}this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}}async enableVideo(t){var e;if(a(this,Et).canProduceVideo!==G.NotAllowed&&!(a(this,Et).canProduceVideo===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,Xe))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,Be,We)&&this.stageStatus==="ON_STAGE")try{await a(this,Ze,gt).shareWebcam(this.videoTrack)}catch(r){this.logger.error("Self::enableVideo::Error while sharing video",{error:r}),this.videoEnabled&&this.localMediaHandler.disableVideo()}this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),this.logger.info("Self.enableVideo",{...Ei(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new R("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,Be,We))throw new R("Can`t enable screenshare without joining room","1105");if(a(this,Et).canProduceScreenshare!==G.NotAllowed&&!(a(this,Et).canProduceScreenshare===G.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.screenShareEnabled&&(await this.localMediaHandler.enableScreenShare(),this.screenShareTracks.audio||this.screenShareTracks.video)){try{await a(this,Ze,gt).shareScreen(this.screenShareTracks)}catch(t){this.logger.error("Self::enableScreenShare::Error while sharing screen",{error:t}),this.screenShareEnabled&&await this.localMediaHandler.disableScreenShare()}this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks})}}async updateScreenshareConstraints(t){if(!this.localMediaHandler.updateScreenshareConstraints)throw new R("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,Be,We)&&a(this,Ze,gt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,Xe))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,Be,We)&&await a(this,Ze,gt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,Xe))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,Be,We)&&await a(this,Ze,gt).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,ma,t);const r=t?"pinned":"unpinned";(i=a(this,gr,fn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,ma)}async pin(){if(!a(this,Be,We))throw new R("Can`t pin participants without joining room","1105");return this.show(),a(this,Ze,gt).pinPeer(this.id)}async unpin(){if(!a(this,Be,We))throw new R("Can`t unpin participants without joining room","1105");return a(this,Ze,gt).pinPeer(null)}async hide(){if(!a(this,Be,We))throw new R("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,Be,We))throw new R("Can`t toggle participant tile without joining room","1105");this.hidden=!1,this.emit("toggleTile",{hidden:this.hidden})}async setDevice(t){var r,i,n;if(!t)throw new R("No device selected","1104");const e=this.getCurrentDevices();switch(t.deviceId&&(((r=e==null?void 0:e.audio)==null?void 0:r.deviceId)===t.deviceId||((i=e==null?void 0:e.video)==null?void 0:i.deviceId)===t.deviceId||((n=e==null?void 0:e.speaker)==null?void 0:n.deviceId)===t.deviceId)&&this.logger.warn("Self.setDevice.setting_to_in_use_device",{devices:[t]}),t.kind){case"audioinput":try{await this.localMediaHandler.setAudioDevice(t,{saveDevicePreference:!0})}catch(o){a(this,Be,We)&&await a(this,Ze,gt).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack})}break;case"audiooutput":await this.localMediaHandler.setSpeakerDevice(t,{saveDevicePreference:!0});break;case"videoinput":try{await this.localMediaHandler.setVideoDevice(t,{saveDevicePreference:!0})}catch(o){a(this,Be,We)&&await a(this,Ze,gt).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack})}break}}cleanUpTracks(){var t,e,r,i;(t=this.audioTrack)==null||t.stop(),(e=this.rawAudioTrack)==null||e.stop(),(r=this.videoTrack)==null||r.stop(),(i=this.rawVideoTrack)==null||i.stop()}playAudio(){var t;return(t=a(this,ga,uu))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,fa).add(t):a(this,Sa).add(t),this.updateVideo(t),e||(i=a(this,gr,fn))==null||i.addSource(this.id,t,this.videoEnabled,this.isPinned,this.name,this.picture,(r=this.raised)!=null?r:!1))}deregisterVideoElement(t,e=!1){if(!t){a(this,gr,fn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,fa).delete(t):(a(this,Sa).delete(t),a(this,gr,fn).removeSource(this.id))}updateVideo(t,e=!1){var r,i,n;if(this.videoEnabled){if(this.videoTrack==null)return;const o=(r=t.srcObject)==null?void 0:r.getTracks()[0];if((o==null?void 0:o.id)===this.videoTrack.id)return;const c=new MediaStream;c.addTrack(this.videoTrack),t.srcObject=c,e||(i=a(this,gr,fn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,gr,fn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},pa=new WeakMap,Et=new WeakMap,ma=new WeakMap,Xe=new WeakMap,gr=new WeakSet,fn=function(){return a(this,Xe).getValue("pip")},Ze=new WeakSet,gt=function(){return a(this,Xe).getValue("roomNodeClient")},ga=new WeakSet,uu=function(){return a(this,Xe).getValue("audioPlayback")},Be=new WeakSet,We=function(){var t;return((t=a(this,Xe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},fa=new WeakMap,Sa=new WeakMap,Yo=new WeakSet,op=function(){Array.from(a(this,Sa)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,fa)).forEach(t=>this.updateVideo(t,!0))},YS);ft([E.trace("Self.cleanupEvents")],Ke.prototype,"cleanupEvents",1),ft([E.trace("Self.setupEvents")],Ke.prototype,"setupEvents",1),ft([E.trace("Self.setupTracks")],Ke.prototype,"setupTracks",1),ft([E.trace("Self.destructMediaHandler")],Ke.prototype,"destructMediaHandler",1),ft([E.trace("Self.removeDocumentEventListeners")],Ke.prototype,"removeDocumentEventListeners",1),ft([tr.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],Ke.prototype,"enableAudio",1),ft([tr.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],Ke.prototype,"enableVideo",1),ft([E.trace("Self.updateVideoConstraints")],Ke.prototype,"updateVideoConstraints",1),ft([E.trace("Self.enableScreenShare"),tr.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],Ke.prototype,"enableScreenShare",1),ft([E.trace("Self.updateScreenshareConstraints")],Ke.prototype,"updateScreenshareConstraints",1),ft([tr.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],Ke.prototype,"disableAudio",1),ft([tr.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],Ke.prototype,"disableVideo",1),ft([tr.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],Ke.prototype,"disableScreenShare",1),ft([E.trace("Self.setDevice")],Ke.prototype,"setDevice",1),Ke=ft([lt("1100")],Ke);class Rh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Rh)}}class Ih extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Ih)}}class Ah{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);g(this,Qo,void 0);this.log=e,f(this,Qo,{info:e&&t?t.info:()=>{}})}get size(){return this.pendingTasks.size}async push(t,e,r){if(e=e!=null?e:t.name,typeof t!="function")throw new TypeError("given task is not a function");if(e)try{Object.defineProperty(t,"name",{value:e})}catch(i){}return new Promise((i,n)=>{const o={id:this.nextTaskId++,task:t,metadata:r,name:e,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:c=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),i(c);const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)},reject:c=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),n(c),!this.stopping)){const[d]=this.pendingTasks.values();d&&!d.executedAt&&this.execute(d)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){this.stopping=!0;for(const t of this.pendingTasks.values())t.reject(new Rh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Ih)}get(t){return Array.from(this.pendingTasks.values())[t]}dump(){const t=Date.now();let e=0;return Array.from(this.pendingTasks.values()).map(r=>({idx:e++,task:r.task,name:r.name,enqueuedTime:r.executedAt?r.executedAt-r.enqueuedAt:t-r.enqueuedAt,executionTime:r.executedAt?t-r.executedAt:0}))}async execute(t){if(t.executedAt)throw new Error("task already being executed");t.executedAt=Date.now();try{const e=this.pendingTasks.size,r=await t.task(),i=Date.now();a(this,Qo).info(`AwaitQueue.push(${t.name})_timings`,{awaitQueueTask:{id:t.id,metadata:t.metadata,queueSizeAtStart:e,execTime:(i-t.executedAt)/1e3,taskStartTime:(t.executedAt-t.enqueuedAt)/1e3}}),t.resolve(r)}catch(e){t.reject(e)}}}Qo=new WeakMap;function ND(s,t){const e=new Error(t);return e.name=s,e}class uo extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,uo):this.stack=new Error(t).stack}}class kt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,kt):this.stack=new Error(t).stack}}class Lr extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,kt):this.stack=new Error(t).stack}}const Zf=s=>new Promise(t=>setTimeout(t,s));async function eS(s,t){return new Promise(async(e,r)=>{const{strategy:i,maxRetryCount:n,delayTime:o}={strategy:"linear",maxRetryCount:3,delayTime:10,...t};let c=0,d,l=!1;const u=h=>{l=!0,r(h)};for(;c<n;){try{const h=await s(c,u);return e(h)}catch(h){if(d=h,l)break;if(c<n)i==="linear"?await Zf(o*(c+1)):i==="exponential"&&await Zf(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function VD(s){return s.map(t=>({channels:t.channels,clockRate:t.clockRate,mimeType:t.mimeType,sdpFmtpLine:t.sdpFmtpLine}))}function LD(s){return s.map(t=>({uri:t.uri}))}function Wd(s){return{codecs:VD(s.codecs),headerExtensions:LD(s.headerExtensions?s.headerExtensions:[])}}function xD(s){const t=RTCRtpReceiver.getCapabilities("audio"),e=RTCRtpReceiver.getCapabilities("video"),r=RTCRtpSender.getCapabilities("audio"),i=RTCRtpSender.getCapabilities("video");s&&(e.codecs=e.codecs.filter(({mimeType:d})=>s===d),i.codecs=i.codecs.filter(({mimeType:d})=>s===d));const n={audio:Wd(t),video:Wd(e)};return{sender:{audio:Wd(r),video:Wd(i)},receiver:n}}class UD{constructor(t){g(this,et,void 0);p(this,"events");f(this,et,t),this.events=hs}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,et).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:cC.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,et).sendMessagePromise(this.events.createWebRTCTransport,Lk.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=$g.fromBinary(e),o={sdp:i==null?void 0:i.sdp,type:i.type};return{transportId:r,answer:o,producerIds:n}}async produce(t){var n,o;const e=(await a(this,et).sendMessagePromise(this.events.produce,wC.toBinary(t))).payload,r=nR.fromBinary(e);return{answer:{sdp:(n=r==null?void 0:r.description)==null?void 0:n.sdp,type:(o=r==null?void 0:r.description)==null?void 0:o.type},producerId:r.producerId}}async consume(t){const e=(await a(this,et).sendMessagePromise(this.events.consume,SC.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=rR.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,et).sendMessagePromise(this.events.closeProducer,AC.toBinary(t))).payload,{description:r}=hR.fromBinary(e);return r}async closeConsumer(t){return(await a(this,et).sendMessagePromise(this.events.closeConsumer,OC.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,et).sendMessagePromise(this.events.updateConsumersSimulcastConfig,EC.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,et).sendMessagePromise(this.events.hostControlPeer,UC.toBinary(r))).payload;if(!i)return!1;const{status:n}=TR.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,et).sendMessagePromise(this.events.hostControlAllPeers,BC.toBinary(e))).payload;if(!r)return!1;const{status:i}=ER.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,et).sendMessagePromise(U.kickAll,Gg.toBinary(t))}async kickPeer(t){a(this,et).sendMessagePromise(U.kick,of.toBinary(t))}async changeDisplayName(t){const e=(await a(this,et).sendMessagePromise(this.events.changeDisplayName,LC.toBinary(t))).payload;if(!e)return!1;const{status:r}=wR.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,et).sendMessagePromise(this.events.selfJoinComplete,lC.toBinary(t))).payload;return Qu.fromBinary(e)}async audioActivity(t){a(this,et).sendMessage(this.events.audioActivity,Uk.toBinary(t))}}et=new WeakMap;var Ds=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Ds||{});class Jd extends dt.EventEmitter{constructor(e){super();g(this,Xo,void 0);f(this,Xo,e),this.setMaxListeners(1/0)}get logger(){return a(this,Xo).getValue("logger")}safeEmit(e,...r){const i=this.listenerCount(e);try{return this.emit(e,...r)}catch(n){return this.logger.error(`EnhancedEventEmitter:: safeEmit() | event listener ${e} threw an error`,{error:n}),Boolean(i)}}async safeEmitAsPromise(e,...r){const i={}.EVENT_PROMISE_TIMEOUT?parseInt({}.EVENT_PROMISE_TIMEOUT,10):1e4;return this.safeEmitAsPromiseWithTimeout(e,i,...r)}async safeEmitAsPromiseWithTimeout(e,r,...i){return new Promise((n,o)=>{setTimeout(o,r,"event request timeout");try{this.emit(e.toString(),...i,n,o)}catch(c){this.logger.error(`EnhancedEventEmitter:: safeEmitAsPromise() | event listener for event ${e.toString()} threw an error [event:%s]:%o`,{error:c}),o(c)}})}}Xo=new WeakMap;class Mh extends Jd{constructor(){super(...arguments);p(this,"_sendWebStream",new MediaStream);p(this,"_sendScreenShareStream",new MediaStream);p(this,"_direction");p(this,"pc");p(this,"_transportReady",!1);p(this,"_mapMidTransceiver",new Map);p(this,"enableHighBitrate",!1);p(this,"enableStereo",!1);p(this,"enableDtx",!0)}get midTransceiverMap(){return this._mapMidTransceiver}close(){if(this.logger.debug(`${this.name}::close()`),this.pc)try{this.pc.close()}catch(e){this.logger.error(`${this.name}::pc.close()`,{error:e})}}async restartIce(){this.logger.debug(`${this.name}::restartIce()`);const e=await this.pc.createOffer({iceRestart:!0});return this.logger.debug(`[SDP] ${this.name}::restartIce() | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),{offerSdp:e,callback:async i=>{this.logger.info(`[SDP] ${this.name}::restartIce() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}init({direction:e,iceServers:r,iceTransportPolicy:i,additionalSettings:n,proprietaryConstraints:o,onTrackHandler:c}){this.logger.debug("HandlerInterface::init()"),this._direction=e,this.pc=new RTCPeerConnection({iceServers:r||[],iceTransportPolicy:i||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...n},o),c&&this.pc.addEventListener("track",d=>{c(d)}),this._addEventListeners()}async connect(){this.pc.addTransceiver("audio",{direction:"sendonly"}),this.pc.addTransceiver("video",{direction:"sendonly",...this._direction==="send"?{sendEncodings:[{rid:"f",scaleResolutionDownBy:1},{rid:"h",scaleResolutionDownBy:2},{rid:"q",scaleResolutionDownBy:4}]}:{}});const e=await this.pc.createOffer();return await this.pc.setLocalDescription(e),this.logger.info(`[SDP] connect offer: ${JSON.stringify(e)}`),{offerSdp:e,callback:async i=>{this.logger.debug(`[SDP] ${this.name}::connect() | calling pc.setRemoteDescription() [answer:${JSON.stringify(i)}]`),await this.pc.setRemoteDescription(i)}}}async getTransportStats(){return this.pc.getStats()}_assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}_assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}async getReceiverStats(e){this._assertRecvDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.receiver.getStats()}async stopSending(e){this._assertSendDirection(),this.logger.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 i=await this.pc.createOffer();return this.logger.debug(`[SDP] stopSending() | calling pc.setLocalDescription() [offer:${JSON.stringify(i)}]`),await this.pc.setLocalDescription(i),{offerSdp:i,callback:async o=>{this.logger.debug(`[SDP] stopSending() | calling pc.setRemoteDescription() [answer:${JSON.stringify(o)}]`),await this.pc.setRemoteDescription(o),this.midTransceiverMap.delete(e)}}}async replaceTrack(e,r){this._assertSendDirection(),r?this.logger.debug(`replaceTrack() [localId:${e}, track.id:${r.id}]`):this.logger.debug(`replaceTrack() [localId:${e}, no track]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");await i.sender.replaceTrack(r)}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{c<=r?o.active=!0:o.active=!1}),await i.sender.setParameters(n)}async setRtpEncodingParameters(e,r){this._assertSendDirection(),this.logger.debug(`setRtpEncodingParameters() [localId:${e}, params:${JSON.stringify(r)}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters();n.encodings.forEach((o,c)=>{n.encodings[c]={...o,...r}}),await i.sender.setParameters(n)}getSenderStats(e){this._assertSendDirection();const r=this.midTransceiverMap.get(e);if(!r)throw new Error("associated RTCRtpTransceiver not found");return r.sender.getStats()}_addEventListeners(){this.pc.addEventListener("icecandidate",e=>{e.candidate&&this.emit("@icecandidate",{candidate:e.candidate})}),this.pc.addEventListener("iceconnectionstatechange",()=>{switch(this.pc.iceConnectionState){case"checking":this.emit("@connectionstatechange","connecting");break;case"connected":case"completed":this.emit("@connectionstatechange","connected"),this._transportReady=!0;break;case"failed":this.emit("@connectionstatechange","failed");break;case"disconnected":this.emit("@connectionstatechange","disconnected");break;case"closed":this.emit("@connectionstatechange","closed");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("negotiationneeded",()=>{this.emit("@negotiationneeded",{}),this.logger.debug("negotiationneeded")}),this.pc.addEventListener("icegatheringstatechange",()=>{switch(this.pc.iceGatheringState){case"gathering":this.logger.debug("icegatheringstatechange | gathering"),this.emit("@icegatheringstatechange","gathering");break;case"complete":this.logger.debug("icegatheringstatechange | complete"),this.emit("@icegatheringstatechange","complete");break;default:this.logger.warn("unknown state");break}}),this.pc.addEventListener("icecandidateerror",e=>{this.logger.warn("icecandidateerror",{error:{code:e.errorCode,message:e.errorText}})}),this.pc.addEventListener("datachannel",e=>{this.logger.info("data channel created: ",{rtcChannel:{label:e.channel.label}});const{channel:r}=e;r.onopen=()=>{this.logger.info("data channel open: ",{rtcChannel:{label:e.channel.label}}),this.safeEmit("dc_open",e.channel)},r.onclose=()=>{this.logger.warn("data channel closed: ",{rtcChannel:{label:e.channel.label}})},r.onerror=()=>{this.logger.error("data channel error: ",{rtcChannel:{label:e.channel.label}})}}),this.addCustomEventListeners()}addCustomEventListeners(){}}class Oh extends Mh{static createFactory(t){return()=>new Oh(t)}get name(){return"Chrome74"}init({direction:t,iceServers:e,iceTransportPolicy:r,additionalSettings:i,proprietaryConstraints:n,onTrackHandler:o}){this._direction=t,this.pc=new RTCPeerConnection({iceServers:e||[],iceTransportPolicy:r||"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",sdpSemantics:"unified-plan",...i},n),o&&this.pc.addEventListener("track",c=>{o(c)}),this._addEventListeners()}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection();const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e});if(!navigator.isReactNative){this.logger.debug("creating new transceiver");const d=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`senders available params: ${JSON.stringify(d)}`);const l=[];r&&r.length&&r.forEach(u=>{var m;const h=d.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.debug(`codecOption.parameters:${JSON.stringify(u.parameters)}`);const S=((m=h.sdpFmtpLine)==null?void 0:m.split(";"))||[];S.push(...u.parameters);const y=Array.from(new Set(S).values());h.sdpFmtpLine=y.join(";")}l.push(h)}),this.logger.info(`selected codecs: ${JSON.stringify(l)}`),n.setCodecPreferences(l)}const o=await this.pc.createOffer();if(await this.pc.setLocalDescription(o),r&&r.findIndex(({name:d})=>d==="opus")>=0){const{enableDtx:d,enableStereo:l}=this,u=this.enableHighBitrate?l?128e3:64e3:l?64e3:32e3;o.sdp=o.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${d?"usedtx=1;":""}${l?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${u}`),o.sdp+=`a=rtcp-fb:111 nack\r
15
+ `}this.midTransceiverMap.set(n.mid,n);const c=async d=>(this.logger.debug(`[SDP] send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(d)}]`),await this.pc.setRemoteDescription(d),n.mid);return this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer: ${JSON.stringify(o,void 0,2)}]`),{offerSdp:o,callback:c,sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.addEventListener("datachannel",t=>{const{channel:e}=t;e.onmessage=r=>{this.safeEmit("datachannel",t.channel,String.fromCharCode(...new Uint8Array(r.data)))}})}}var tS={},Kd={},$D={get exports(){return Kd},set exports(s){Kd=s}},sS=$D.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(s){return s.encoding?"rtpmap:%d %s/%s/%s":s.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(s){return s.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(s){return s.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(s){return"extmap:%d"+(s.direction?"/%s":"%v")+(s["encrypt-uri"]?" %s":"%v")+" %s"+(s.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(s){return s.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(s){var t="candidate:%s %d %s %d %s %d typ %s";return t+=s.raddr!=null?" raddr %s rport %d":"%v%v",t+=s.tcptype!=null?" tcptype %s":"%v",s.generation!=null&&(t+=" generation %d"),t+=s["network-id"]!=null?" network-id %d":"%v",t+=s["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(s){var t="ssrc:%d";return s.attribute!=null&&(t+=" %s",s.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(s){return s.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(s){return s.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(s){return"imageattr:%s %s %s"+(s.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(s){return"simulcast:%s %s"+(s.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(s){return"ts-refclk:%s"+(s.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(s){var t="mediaclk:";return t+=s.id!=null?"id=%s %s":"%v%s",t+=s.mediaClockValue!=null?"=%s":"",t+=s.rateNumerator!=null?" rate=%s":"",t+=s.rateDenominator!=null?"/%s":"",t}},{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(sS).forEach(function(s){var t=sS[s];t.forEach(function(e){e.reg||(e.reg=/(.*)/),e.format||(e.format="%s")})}),function(s){var t=function(c){return String(Number(c))===c?Number(c):c},e=function(c,d,l,u){if(u&&!l)d[u]=t(c[1]);else for(var h=0;h<l.length;h+=1)c[h+1]!=null&&(d[l[h]]=t(c[h+1]))},r=function(c,d,l){var u=c.name&&c.names;c.push&&!d[c.push]?d[c.push]=[]:u&&!d[c.name]&&(d[c.name]={});var h=c.push?{}:u?d[c.name]:d;e(l.match(c.reg),h,c.names,c.name),c.push&&d[c.push].push(h)},i=Kd,n=RegExp.prototype.test.bind(/^([a-z])=(.*)/);s.parse=function(c){var d={},l=[],u=d;return c.split(/(\r\n|\r|\n)/).filter(n).forEach(function(h){var m=h[0],S=h.slice(2);m==="m"&&(l.push({rtp:[],fmtp:[]}),u=l[l.length-1]);for(var y=0;y<(i[m]||[]).length;y+=1){var w=i[m][y];if(w.reg.test(S))return r(w,u,S)}}),d.media=l,d};var o=function(c,d){var l=d.split(/=(.+)/,2);return l.length===2?c[l[0]]=t(l[1]):l.length===1&&d.length>1&&(c[l[0]]=void 0),c};s.parseParams=function(c){return c.split(/;\s?/).reduce(o,{})},s.parseFmtpConfig=s.parseParams,s.parsePayloads=function(c){return c.toString().split(" ").map(Number)},s.parseRemoteCandidates=function(c){for(var d=[],l=c.split(" ").map(t),u=0;u<l.length;u+=3)d.push({component:l[u],ip:l[u+1],port:l[u+2]});return d},s.parseImageAttributes=function(c){return c.split(" ").map(function(d){return d.substring(1,d.length-1).split(",").reduce(o,{})})},s.parseSimulcastStreamList=function(c){return c.split(";").map(function(d){return d.split(",").map(function(l){var u,h=!1;return l[0]!=="~"?u=t(l):(u=t(l.substring(1,l.length)),h=!0),{scid:u,paused:h}})})}}(tS);var Dh=Kd,BD=/%[sdv%]/g,FD=function(s){var t=1,e=arguments,r=e.length;return s.replace(BD,function(i){if(t>=r)return i;var n=e[t];switch(t+=1,i){case"%%":return"%";case"%s":return String(n);case"%d":return Number(n);case"%v":return""}})},ho=function(s,t,e){var r=t.format instanceof Function?t.format(t.push?e:e[t.name]):t.format,i=[s+"="+r];if(t.names)for(var n=0;n<t.names.length;n+=1){var o=t.names[n];t.name?i.push(e[t.name][o]):i.push(e[t.names[n]])}else i.push(e[t.name]);return FD.apply(null,i)},HD=["v","o","s","i","u","e","p","c","b","t","r","z","a"],qD=["i","c","b","a"],jD=function(s,t){t=t||{},s.version==null&&(s.version=0),s.name==null&&(s.name=" "),s.media.forEach(function(n){n.payloads==null&&(n.payloads="")});var e=t.outerOrder||HD,r=t.innerOrder||qD,i=[];return e.forEach(function(n){Dh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(ho(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(ho(n,o,c))})})}),s.media.forEach(function(n){i.push(ho("m",Dh.m[0],n)),r.forEach(function(o){Dh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(ho(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(ho(o,c,d))})})})}),i.join(`\r
16
16
  `)+`\r
17
- `},wi=ev,jD=qD,Kd=jD,Pi=wi.parse;wi.parseParams,wi.parseFmtpConfig,wi.parsePayloads,wi.parseRemoteCandidates,wi.parseImageAttributes,wi.parseSimulcastStreamList;class zd extends Mh{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new zd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,m)=>{var $;const v=Pi(h),y=v.media[v.media.length-1],w=y.rtp.filter(x=>m.some(H=>H.name===x.codec)),R=y.fmtp.filter(x=>w.some(H=>H.payload===x.payload)),P=($=y.rtcpFb)==null?void 0:$.filter(x=>w.some(H=>H.payload===x.payload)),N=w.map(x=>x.payload);return v.media[v.media.length-1].rtp=w,v.media[v.media.length-1].fmtp=R,v.media[v.media.length-1].rtcpFb=P,v.media[v.media.length-1].payloads=N.join(" "),Kd(v)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:m}=this,v=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${m?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${v}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Nh extends Mh{static createFactory(t){return()=>new Nh(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var m;const h=o.codecs.find(v=>v.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const v=((m=h.sdpFmtpLine)==null?void 0:m.split(";"))||[];v.push(...u.parameters);const y=[...new Set(v).values()];h.sdpFmtpLine=y.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,m=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${m}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function GD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class WD extends Wd{constructor(e,r){var i;super(e);g(this,xs);g(this,ec);g(this,Cl);g(this,Rl);p(this,"rtpReceiver");p(this,"id");p(this,"localId");p(this,"producerId");p(this,"producingTransportId");p(this,"mimeType");p(this,"track");p(this,"peerId");p(this,"appData");p(this,"transceiver");g(this,Zo,void 0);g(this,zi,void 0);g(this,Ls,void 0);g(this,kl,void 0);this.id=r.id,this.localId=r.localId,f(this,Zo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ls,!1),this.producerId=r.producerId,this.track=r.track,f(this,zi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,V(this,Cl,dS).call(this),f(this,kl,e)}get closed(){return a(this,Ls)}get kind(){return this.track.kind}get paused(){return a(this,zi)}close(e,r){a(this,Ls)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,xs,li)),f(this,Ls,!0),r&&(V(this,Rl,lS).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ls))throw new _t("closed");return a(this,Zo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,xs,li)),a(this,Ls)){this.logger.error("consumer::pause() | Consumer closed",a(this,xs,li));return}f(this,zi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,xs,li)),a(this,Ls)){this.logger.error("Consumer::resume() | Consumer closed",a(this,xs,li));return}f(this,zi,!1),this.track.enabled=!0,this.safeEmit("resume")}}Zo=new WeakMap,zi=new WeakMap,Ls=new WeakMap,kl=new WeakMap,xs=new WeakSet,li=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},ec=new WeakSet,cp=function(){this.logger.debug('Consumer::track "ended" event',a(this,xs,li)),this.safeEmit("trackended")},Cl=new WeakSet,dS=function(){this.track.addEventListener("ended",V(this,ec,cp).bind(this))},Rl=new WeakSet,lS=function(){try{this.track.removeEventListener("ended",V(this,ec,cp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,xs,li),error:e})}};class JD extends Wd{constructor(e,r){var i,n;super(e);g(this,Bt);p(this,"id");p(this,"localId");g(this,ys,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,Sa,void 0);g(this,Ta,void 0);g(this,Yi,void 0);g(this,is,!1);g(this,at,void 0);g(this,ti,void 0);g(this,ya,void 0);g(this,Il,void 0);this.id=r.id,this.localId=r.localId,f(this,at,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,ti,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,ya,void 0),f(this,Sa,r.stopTracks),f(this,Ta,r.disableTrackOnPause),f(this,Yi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,ys,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Il,e)}get closed(){return a(this,is)}get track(){return a(this,at)}get paused(){return a(this,ti)}get maxSpatialLayer(){return a(this,ya)}async close(e){if(a(this,is))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Bt,_s)),f(this,is,!0),this._destroyTrack(),e===po){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,ys).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,is))throw new _t("closed");return a(this,ys).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Bt,_s)),a(this,is)&&this.logger.error("Producer::pause() | Producer closed",a(this,Bt,_s)),f(this,ti,!0),a(this,at)&&a(this,Ta)&&(a(this,at).enabled=!1),a(this,Yi)&&a(this,ys).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Bt,_s)),a(this,is)){this.logger.error("Producer::resume() | Producer closed",a(this,Bt,_s));return}f(this,ti,!1),a(this,at)&&a(this,Ta)&&(a(this,at).enabled=!0),a(this,Yi)&&a(this,ys).replaceTrack(this.localId,a(this,at)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Bt,_s)),a(this,is)){if(e&&a(this,Sa))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Bt,_s),error:r})}throw new _t("closed")}else if(e&&e.readyState==="ended")throw new _t("track ended");if(e===a(this,at)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Bt,_s));return}(!a(this,Yi)||!a(this,ti))&&await a(this,ys).replaceTrack(this.localId,e),this._destroyTrack(),f(this,at,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,is))throw new _t("closed");if(this.kind!=="video")throw new uo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,ys).setMaxSpatialLayer(this.localId,e),f(this,ya,e)}async setRtpEncodingParameters(e){if(a(this,is))throw new _t("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,ys).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Bt,_s)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,at)&&a(this,at).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,at))try{a(this,at).removeEventListener("ended",this._onTrackEnded),a(this,Sa)&&a(this,at).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Bt,_s),error:r})}}}ys=new WeakMap,Sa=new WeakMap,Ta=new WeakMap,Yi=new WeakMap,is=new WeakMap,at=new WeakMap,ti=new WeakMap,ya=new WeakMap,Il=new WeakMap,Bt=new WeakSet,_s=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function sv(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Vh(s){return Math.random().toString(36).substring(2,2+s)}const Yd=1;function rv(s){const t=s;return delete t.payload._bolt,t}function KD(s){return s.payload&&sv(s.payload)}function zD(s){var t,e;return KD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const Ea=class extends ct.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");g(this,si,new Map);g(this,Al,void 0);g(this,Qi,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=Ea.createErrorResponse(e,r):n=Ea.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=Ea.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=Ea.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});p(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,h=(l+1)*n;c.push(r.slice(u,h))}const d=Sn();for(let l=0;l<o;l+=1){const u=c[l],m=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,Qi).debug(`Sending message chunk over dc: ${m}`),this.channel.send(m)}}else a(this,Qi).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,si).has(e.id)||a(this,si).set(e.id,[]);const r=a(this,si).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,si).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,si).delete(e.id);const c=JSON.parse(o);if(!c.payload||!sv(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});p(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(a(this,Qi).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(rv(e)):i.resolve(rv(e)),!0):!1});p(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Vh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Al,e),f(this,Qi,e.getValue("logger")),this.channel=r,this.queue=new Map}};let _i=Ea;si=new WeakMap,Al=new WeakMap,Qi=new WeakMap,p(_i,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Vh(8),type:"REQUEST",version:Yd}}}}),p(_i,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:Yd}}}}),p(_i,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Vh(8),type:"NOTIFY",version:Yd}}}}),p(_i,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Yd}}}));const po="transport closed",ba=class extends Wd{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,R,P;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"datachannels");p(this,"connected",!1);p(this,"eventsDCReadyPromise");p(this,"eventsDCReadyPromiseResolver");p(this,"eventsDCFailureTimer");p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");g(this,Xi,void 0);f(this,Xi,e);const m=e.getValue("logger");m.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const v=GD(l,{});delete v.iceServers,delete v.iceTransportPolicy,delete v.bundlePolicy,delete v.rtcpMuxPolicy,delete v.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ah(m,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(R=h==null?void 0:h.enableStereo)!=null?R:!1,this.handler.enableDtx=(P=h==null?void 0:h.enableDtx)!=null?P:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(N=>{const $=setTimeout(()=>{m.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),N(!1)},y);this.once("connected",()=>{clearTimeout($),N(!0)}),this.once("disconnect",()=>{clearTimeout($),N(!1)}),this.once("close",()=>{clearTimeout($),N(!1)})}),this.eventsDCReadyPromise=new Promise(N=>{this.eventsDCReadyPromiseResolver=N}),this.handler.on("@connectionstatechange",N=>{N!==this.connectionState&&(this.logger.debug(`connection state changed to ${N}`),this.connectionState=N,N==="connected"&&(this.connected=!0,this.emit("connected")),N==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(N==="failed"||N==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",N))}),this.handler.on("@icecandidate",({candidate:N})=>{this.closed||this.safeEmit("icecandidate",N)}),this.handler.on("dc_open",N=>{let $=this.datachannels.get(N.label);$||($||($=new _i(a(this,Xi),N,N.label,this.serverId),this.datachannels.set(N.label,$)),this.eventsDCFailureTimer=setTimeout(()=>{N.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",N.label))},5e3))}),this.handler.on("datachannel",(N,$)=>{N.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const x=this.datachannels.get(N.label);if(!x){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:N.label,message:$}});return}try{const H=JSON.parse($);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:H.id,count:H.count,chunkIndex:H.chunkIndex,chunk:H.chunk,transprtId:this.serverId}});const F=x.processMessage(H);if(!F)return;this.logger.debug(`datachannel message with id:${H.id} on transport:${this.serverId}complete - ${JSON.stringify(F)}`),this.emit(`datachannel:${N.label}`,x.label,F)}catch(H){this.logger.error("error parsing message",{error:H})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",e))}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(po).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(po)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new _t("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new _t("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new uo("not a sending Transport");if(r.readyState==="ended")throw new _t("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Lr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:m,localId:v,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:R,sender:P,mid:N}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:$,producerId:x}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:N},codecOptions:c,producingTransportId:this.serverId}),H=await R($);return{producerId:x,localId:H,rtpSender:P}},"Transport.produce");return this.createProducerObject({id:m,localId:v,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new JD(a(this,Xi),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new _t("closed");if(this.direction!=="recv")throw new uo("not a receiving transport");if(!await this.transportConnectionPromise)throw new Lr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(m=>l.push(m)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=Pi(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=Pi(e.sdp);return n.media=n.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:Kd(n)}}static parseHeaderExtensionMappings(e){const r=Pi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=Pi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:Kd(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=ba.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=ba.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=ba.setCodecAndFmtpMappings(c,i,n),c=ba.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=Pi(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return n}),r.sdp=Kd(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:m}=e,v=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,R)=>{const P=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${v} producingPeerId: ${n}`),this.consumerTrackEvents.delete(v),y.isTimedout=!0,R(y)},5e3),N=(x,H)=>{try{if(x.readyState==="ended")clearTimeout(P),R(y);else{const F=x;F.enabled=!0,this.handler.midTransceiverMap.set(H.mid,H);const Z=new WD(a(this,Xi),{id:r,localId:H.mid,transceiver:H,track:F,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:H.receiver,mimeType:m});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(H.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(P),w(Z)}}catch(F){this.logger.warn("error while creating consumer:",F),clearTimeout(P),R(y)}},$=this.unknownTracksMap.get(v);$?(this.logger.info(`track event already received [trackId: ${$.track.id}] [mid: ${$.transceiver.mid}]`),this.unknownTracksMap.delete(v),N($.track,$.transceiver)):(this.logger.info(`Registering onTrack handler for key ${v} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(v,N))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw DD("DC_NOT_READY",`${e} datachannel not ready`);const n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let Lh=ba;Xi=new WeakMap;function YD(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Tp.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}class QD{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,fr,void 0);g(this,Zi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,fr,t),f(this,Zi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,Zi).debug(`Device::constructor() | handler given: ${e}`);else if(e=YD(a(this,Zi)),e)a(this,Zi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Oh.createFactory(a(this,fr));break;case"Safari12":this.handlerFactory=Nh.createFactory(a(this,fr));break;case"Firefox60":this.handlerFactory=zd.createFactory(a(this,fr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=zd.createFactory(a(this,fr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=Sn();return new Lh(a(this,fr),{id:e,...t,handlerFactory:this.handlerFactory})}}fr=new WeakMap,Zi=new WeakMap;const XD=2e3;class ZD extends ct.EventEmitter{constructor(e,r){super();g(this,ka);g(this,ic);g(this,Ml);g(this,nc);g(this,Ol);g(this,Dl);g(this,Nl);g(this,Vl);g(this,Ll);g(this,ac);g(this,ri);p(this,"context");g(this,wa,void 0);g(this,et,void 0);g(this,tt,void 0);g(this,tc,void 0);g(this,sc,void 0);g(this,en,void 0);g(this,Pa,void 0);g(this,rc,void 0);g(this,_a,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,tn,void 0);g(this,Us,"all");this.context=e,f(this,en,r),f(this,wa,new QD(e)),f(this,Pa,new xD(r)),f(this,rc,hs),a(this,ka,uu).mediaState={send:{state:Ds.NEW},recv:{state:Ds.NEW}},Pn(this.context,"forceRelay")&&f(this,Us,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Us)}`),V(this,ic,dp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,en)}get socketHandler(){return a(this,Pa)}get sendTransport(){return a(this,et)}get recvTransport(){return a(this,tt)}get events(){return a(this,rc)}set sendTransportConnectedCallback(e){f(this,tc,e)}set recvTransportConnectedCallback(e){f(this,sc,e)}async setupTransports(e){await V(this,Ml,uS).call(this,e);let r,i;e.send&&(r=V(this,nc,lp).call(this,a(this,et)).then(n=>{try{a(this,tc).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=V(this,nc,lp).call(this,a(this,tt)).then(n=>{try{a(this,sc).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,et);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,et).close(),a(this,et).removeAllListeners(),f(this,et,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,tt);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,tt))==null||r.close(),(i=a(this,tt))==null||i.removeAllListeners(),f(this,tt,void 0)}V(this,ic,dp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}wa=new WeakMap,et=new WeakMap,tt=new WeakMap,tc=new WeakMap,sc=new WeakMap,en=new WeakMap,Pa=new WeakMap,rc=new WeakMap,_a=new WeakMap,tn=new WeakMap,Us=new WeakMap,ka=new WeakSet,uu=function(){return this.context.getValue("connectionHandler")},ic=new WeakSet,dp=function(){f(this,tn,{send:void 0,recv:void 0})},Ml=new WeakSet,uS=async function(e){var o,c,d,l,u,h,m,v;Pn(this.context,"forceRelay")&&f(this,Us,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Us)}`);const n=await wt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&V(this,Dl,pS).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(m=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?m:!1,enableDtx:!1},iceTransportPolicy:a(this,Us)}),e.recv&&V(this,Nl,mS).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(v=this.context.getValue("modules").e2ee)==null?void 0:v.enabled},iceTransportPolicy:a(this,Us)})},nc=new WeakSet,lp=async function(e){const{id:r,serverId:i,direction:n}=e;V(this,Vl,gS).call(this,e);try{return await Zf(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Lr("Cannot reconnect closed transport");await V(this,Ol,hS).call(this,e)}catch(l){if(l instanceof Lr){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},Ol=new WeakSet,hS=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,en).isConnected)throw new Lr("Socket is not connected");if(e.connectionState==="closed")throw new Lr("Transport is closed");try{await e.connect(n=>V(this,Ll,fS).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,_a).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Lr(n.message):n}},Dl=new WeakSet,pS=function(e){var r,i;if(a(this,et)&&a(this,et).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,et))==null?void 0:r.id,serverId:(i=a(this,et))==null?void 0:i.serverId,type:"send"}});return}f(this,et,a(this,wa).createTransport({...e,direction:"send"})),V(this,ri,Ba).call(this,{state:Ds.NEW,direction:"send",sfuSessionId:a(this,et).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,et))},Nl=new WeakSet,mS=function(e){var r,i;if(a(this,tt)&&a(this,tt).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,tt))==null?void 0:r.id,serverId:(i=a(this,tt))==null?void 0:i.serverId,type:"recv"}});return}f(this,tt,a(this,wa).createTransport({...e,direction:"recv"})),V(this,ri,Ba).call(this,{state:Ds.NEW,direction:"recv",sfuSessionId:a(this,tt).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,tt))},Vl=new WeakSet,gS=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{V(this,ri,Ba).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{V(this,ri,Ba).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,tn)[r];c!==void 0&&(clearTimeout(c),a(this,tn)[r]=void 0)};switch(n){case"connected":o(),a(this,_a).lastConnectionTime=performance.now();break;case"disconnected":a(this,tn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await V(this,ac,up).call(this,e.direction)},XD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await V(this,ac,up).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,zD(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},Ll=new WeakSet,fS=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?Ks.SUBSCRIBER:Ks.PUBLISHER},producers:[]};return a(this,Pa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},ac=new WeakSet,up=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,en).isConnected&&a(this,_a).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Us,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,et)}),this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,tt)}),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,et):a(this,tt);V(this,ri,Ba).call(this,{state:Ds.CONNECTED,direction:e,sfuSessionId:r.serverId})},ri=new WeakSet,Ba=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,ka,uu).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(k.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,ka,uu).mediaState[i]})};class e1{constructor(t,e,r,i,n){g(this,xl,void 0);g(this,ns,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,xl,t),f(this,ns,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,m={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...m})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ns).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(m){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ns).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ns).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:Ks.SUBSCRIBER}};return a(this,ns).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,Bk.toBinary(r)),a(this,ns).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ns).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ns).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:Ks.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=pR.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ns).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}xl=new WeakMap,ns=new WeakMap;class xh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Pi(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var h,m;const c=xh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Ks.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(m=n[0])==null?void 0:m.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function t1(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}class s1 extends ZD{constructor(e,r){super(e,r);g(this,cc);g(this,$l);g(this,Bl);g(this,Fl);g(this,Hl);g(this,ii,void 0);g(this,ni,void 0);g(this,Ca,void 0);g(this,oc,void 0);g(this,$s,void 0);g(this,Ul,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,vr,[]);g(this,Ra,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,oc,new xh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,Ca).clear(),f(this,$s,new e1(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,ii)}get consumers(){return a(this,ni)}get producerIdToConsumerIdMap(){return a(this,Ca)}get logger(){return this.context.getValue("logger")}reset(){f(this,ii,new Map),f(this,ni,new Map),f(this,Ca,new Map)}async createProducer(e,r){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,V(this,$l,vS).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,o),V(this,Bl,SS).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,Ul).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var n;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(n=this.context.getValue("modules").e2ee)!=null&&n.enabled&&this.context.getValue("peerSessionStore").emit(k.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,ii).entries()).map(([,e])=>e.close()))}async closeAllProducersLocally(){var r;const e=(r=this.sendTransport)==null?void 0:r.handler;await Promise.all(Array.from(a(this,ii).values()).map(async i=>{try{if(e){const n=e.midTransceiverMap.get(i.localId);n&&(await n.sender.replaceTrack(null),n.direction="inactive")}}catch(n){this.logger.warn("closeAllProducersLocally: failed to deactivate transceiver",{producer:{id:i.id,kind:i.kind,appData:i.appData},error:n})}await i.close(po)}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Ra)||clearTimeout(a(this,Ra)),f(this,vr,a(this,vr).concat(e)),await V(this,cc,hp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,$s))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,$s).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,ni).keys()))}async switchConsumersToLayer(e,r){a(this,$s).switchConsumersToLayer(e,r)}}ii=new WeakMap,ni=new WeakMap,Ca=new WeakMap,oc=new WeakMap,$s=new WeakMap,Ul=new WeakMap,vr=new WeakMap,Ra=new WeakMap,cc=new WeakSet,hp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,vr).splice(0,a(this,vr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,V(this,Fl,TS).bind(this),a(this,$s).negotiate.bind(a(this,$s)));if(o.forEach(V(this,Hl,yS).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,vr,a(this,vr).concat(d)),f(this,Ra,setTimeout(V(this,cc,hp).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=t1(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},$l=new WeakSet,vS=function(e){return a(this,oc).create(e)},Bl=new WeakSet,SS=function(e,r){e.on("close",async(i,n)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==po){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Ks.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),n({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),a(this,ii).set(e.id,e)},Fl=new WeakSet,TS=async function(e){try{return await this.recvTransport.canConsume(),await a(this,$s).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Hl=new WeakSet,yS=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,ni).delete(e.id),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:e.id})}),a(this,ni).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(k.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};const Jl=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,ql);g(this,jl);g(this,dc,void 0);g(this,lc,void 0);g(this,uc,void 0);g(this,Ia,void 0);g(this,Aa,void 0);g(this,Ma,void 0);g(this,hc,void 0);g(this,pc,void 0);g(this,Oa,void 0);g(this,Ct,void 0);g(this,Es,void 0);g(this,bs,!1);g(this,sn,0);g(this,rn,0);g(this,Sr,[]);g(this,mc,void 0);f(this,Ia,t),f(this,Ct,t),f(this,dc,e),f(this,lc,r),f(this,uc,i),f(this,Aa,n),f(this,Ma,o),f(this,hc,c),f(this,pc,d),f(this,Oa,l),f(this,mc,u),f(this,Es,t/2)}get voiceDetected(){return a(this,bs)}processAudioChunk(t){var o,c;const e=V(o=Jl,Gl,wS).call(o,t),r=V(c=Jl,Wl,PS).call(c,t);return V(this,ql,ES).call(this,e),e/a(this,Es)>a(this,Oa)&&e>a(this,Ct)&&r>a(this,dc)?(f(this,sn,a(this,sn)+1),f(this,rn,a(this,uc)),a(this,sn)>=a(this,lc)&&f(this,bs,!0)):(f(this,sn,0),a(this,rn)>0?f(this,rn,a(this,rn)-1):a(this,bs)&&f(this,bs,!1),a(this,bs)||V(this,jl,bS).call(this,e)),{energy:e,isVoice:a(this,bs)}}reset(){f(this,bs,!1),f(this,sn,0),f(this,rn,0),f(this,Ct,a(this,Ia)),f(this,Es,a(this,Ia)/2),f(this,Sr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Ct),backgroundNoiseEnergy:a(this,Es),energyRatioThreshold:a(this,Oa)}}};let mo=Jl;dc=new WeakMap,lc=new WeakMap,uc=new WeakMap,Ia=new WeakMap,Aa=new WeakMap,Ma=new WeakMap,hc=new WeakMap,pc=new WeakMap,Oa=new WeakMap,Ct=new WeakMap,Es=new WeakMap,bs=new WeakMap,sn=new WeakMap,rn=new WeakMap,Sr=new WeakMap,mc=new WeakMap,ql=new WeakSet,ES=function(t){a(this,bs)?f(this,Ct,a(this,Ma)*a(this,Ct)+(1-a(this,Ma))*t):f(this,Ct,a(this,Aa)*a(this,Ct)+(1-a(this,Aa))*a(this,Es)),f(this,Ct,Math.max(a(this,hc),Math.min(a(this,pc),a(this,Ct))))},jl=new WeakSet,bS=function(t){if(t<a(this,Ct)*1.2)if(a(this,Sr).push(t),a(this,Sr).length>a(this,mc)&&a(this,Sr).shift(),a(this,Sr).length>=10){const e=[...a(this,Sr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Es,e[r])}else f(this,Es,.95*a(this,Es)+.05*t)},Gl=new WeakSet,wS=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Wl=new WeakSet,PS=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(mo,Gl),g(mo,Wl);class iv{constructor(t){p(this,"RNAudioSampleHandler");g(this,gc,void 0);f(this,gc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,gc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}gc=new WeakMap;class nv{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,fc,void 0);f(this,fc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,fc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}fc=new WeakMap;class r1{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const i1=60,n1=400,Tc=class{constructor(t,e){g(this,Kl);g(this,zl);g(this,Tr,void 0);g(this,yr,void 0);g(this,Er,void 0);g(this,vc,void 0);g(this,Da,void 0);g(this,Na,void 0);g(this,ai,void 0);g(this,nn,void 0);g(this,Va,void 0);g(this,an,void 0);g(this,br,void 0);g(this,Bs,void 0);this.reportRequest=e,f(this,an,t),f(this,Na,new mo);const{isReactNative:r}=navigator;f(this,br,r?new iv(a(this,an)):new nv(a(this,an))),f(this,Bs,r?r1:Bf)}get logger(){return a(this,an).getValue("logger")}set producerId(t){f(this,Er,t)}set audioTrack(t){f(this,vc,t),a(this,br)instanceof nv&&(a(this,br).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Er)}`),a(this,Tr)&&a(this,Bs).clearInterval(a(this,Tr)),f(this,Tr,a(this,Bs).setInterval(async()=>{var i;if(!a(this,vc)||!a(this,Er))return;const{energy:t}=V(this,Kl,_S).call(this),e=V(i=Tc,Sc,pp).call(i,t);let r=.9;a(this,Va)!==e&&a(this,Va)?r=.9:e?r=.3:r=.5,f(this,Da,(a(this,Da)||0)*(1-r)+t*r)},i1)),a(this,yr)&&a(this,Bs).clearInterval(a(this,yr)),f(this,yr,a(this,Bs).setInterval(V(this,zl,kS).bind(this),n1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Er)}`),a(this,Tr)&&(a(this,Bs).clearInterval(a(this,Tr)),f(this,Tr,void 0)),a(this,yr)&&(a(this,Bs).clearInterval(a(this,yr)),f(this,yr,void 0))}catch(t){}a(this,Na).reset(),a(this,br)instanceof iv&&a(this,br).stop()}};let go=Tc;Tr=new WeakMap,yr=new WeakMap,Er=new WeakMap,vc=new WeakMap,Da=new WeakMap,Na=new WeakMap,ai=new WeakMap,nn=new WeakMap,Va=new WeakMap,an=new WeakMap,br=new WeakMap,Bs=new WeakMap,Kl=new WeakSet,_S=function(){var o;const{samples:t}=a(this,br),{energy:e,isVoice:r}=a(this,Na).processAudioChunk(t),i=V(o=Tc,Yl,CS).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,ai)||i<a(this,ai))&&f(this,ai,i),(!a(this,nn)||i>a(this,nn))&&f(this,nn,i),{energy:(i-a(this,ai))/(a(this,nn)-a(this,ai))*10||0,isVoice:r})},Sc=new WeakSet,pp=function(t){return t<5},zl=new WeakSet,kS=function(t=a(this,Da)){var r;if(!a(this,Er)||!t)return;const e={producerId:a(this,Er),energy:Math.round(t),silent:V(r=Tc,Sc,pp).call(r,t)};f(this,Va,e.silent),this.reportRequest(e)},Yl=new WeakSet,CS=function(t){const e=Math.log10(t);return Math.round(e)},g(go,Sc),g(go,Yl);var a1=Object.defineProperty,o1=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?o1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&a1(t,e,i),i};class ae{constructor(t,e){g(this,wr);g(this,Xl);g(this,Zl);g(this,eu);g(this,wc);g(this,tu);g(this,su);g(this,bt);g(this,ln);g(this,ru);g(this,iu);g(this,nu);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,yc,void 0);g(this,Ec,void 0);g(this,ht,void 0);g(this,q,void 0);g(this,Ql,void 0);g(this,Et,void 0);g(this,on,void 0);g(this,cn,void 0);g(this,dn,void 0);g(this,bc,void 0);g(this,Ft,null);g(this,Fs,void 0);g(this,pt,void 0);g(this,Rt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,ht,r),f(this,on,!1),f(this,q,new s1(t,r)),f(this,Et,a(this,q).events),f(this,Fs,new Set),f(this,pt,new Map),f(this,cn,!1),f(this,dn,new Ah(t.getValue("logger"))),f(this,Rt,new go(this.context,a(this,q).socketHandler.audioActivity.bind(a(this,q).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,bc,xu(async()=>{if(!a(this,wr,vn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Ec),a(this,yc),!0);o&&(this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,wr,vn).mediaJoined}set mediaJoined(t){a(this,wr,vn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,q).closeAllProducers(),a(this,q).closeAllConsumers(),a(this,pt).clear(),a(this,Fs).clear(),f(this,Ft,null),t&&a(this,dn).stop(),a(this,q).stopAllTransports(),a(this,q).reset(),t&&f(this,dn,new Ah)}async joinRoom(t,e,r=!1,i={}){a(this,wr,vn).mediaJoinAttempted=!0,f(this,on,!0);try{return await a(this,dn).push(()=>V(this,Xl,RS).call(this,t,e,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_FAILED),{roomJoined:!1,error:n}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Ft)?a(this,Ft):(f(this,Ft,(async()=>{try{await V(this,wc,mp).call(this,t,e,r,i)}catch(n){throw f(this,Ft,null),n}})()),a(this,Ft))}getConsumers(){return a(this,q).consumers}getProducers(){return a(this,q).producers}async leaveRoom(){a(this,q).stopAllTransports(),f(this,cn,!1),a(this,wr,vn).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,ht).sendMessagePromise(a(this,Et).leaveRoom,uC.toBinary(t)).then(r=>{var i;(i=ZC.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,q).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,q).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await a(this,q).closeConsumers(e)}async _shareWebcam(t){var u,h,m,v;const e=Ie.WEBCAM,r=V(this,bt,Wt).call(this,e);if(r){const y=await r;if(a(this,q).producers.has(y)){const w=a(this,q).producers.get(y);if(!w.closed)return await w.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=V(this,nu,VS).call(this,t),n=Pn(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((v=(m=this.context)==null?void 0:m.getValue("theme"))!=null&&v.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=BO(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,pt).delete(e)},l=a(this,q).createProducer(i,d);return V(this,ln,Yc).call(this,e,l.then(y=>y.id)),l.then(y=>y.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,pt).delete(Ie.SCREENSHARE_VIDEO),a(this,pt).delete(Ie.SCREENSHARE_AUDIO)},o=a(this,q).createProducer(i,n);V(this,ln,Yc).call(this,Ie.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,q).createProducer(d,l),V(this,ln,Yc).call(this,Ie.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new _t("track undefined");const e=V(this,bt,Wt).call(this,Ie.MIC);if(e){const o=await e;if(a(this,q).producers.has(o)){const c=a(this,q).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Rt)&&(a(this,Rt).audioTrack=t,a(this,Rt).producerId=o,a(this,Rt).start());return}await a(this,q).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=V(this,iu,NS).call(this,t),i=()=>{a(this,pt).delete(Ie.MIC)},n=a(this,q).createProducer(r,i);V(this,ln,Yc).call(this,Ie.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Rt)&&(a(this,Rt).audioTrack=o.track,a(this,Rt).producerId=o.id,a(this,Rt).start())})}catch(e){throw new C(e)}}async pauseMic(){var i;const t=await V(this,bt,Wt).call(this,Ie.MIC),e=a(this,q).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,Rt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,ht).sendMessage(a(this,Et).toggleProducer,Ad.toBinary(r))}async pauseWebcam(){const t=await V(this,bt,Wt).call(this,Ie.WEBCAM),e=a(this,q).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,ht).sendMessage(a(this,Et).toggleProducer,Ad.toBinary(r))}async resumeMic(){const t=await V(this,bt,Wt).call(this,Ie.MIC),e=a(this,q).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,ht).sendMessage(a(this,Et).toggleProducer,Ad.toBinary(r))}async resumeWebcam(t=Ie.WEBCAM){const e=await V(this,bt,Wt).call(this,t),r=a(this,q).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,ht).sendMessage(a(this,Et).toggleProducer,Ad.toBinary(i))}async disableWebcam(){const t=Ie.WEBCAM,e=await V(this,bt,Wt).call(this,t);V(this,ru,DS).call(this,t),e&&await a(this,q).closeProducer(e)}async disableMic(){var e;const t=await V(this,bt,Wt).call(this,Ie.MIC);t&&await a(this,q).closeProducer(t),(e=a(this,Rt))==null||e.stop(),a(this,pt).delete(Ie.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await V(this,bt,Wt).call(this,Ie.SCREENSHARE_VIDEO),e=await V(this,bt,Wt).call(this,Ie.SCREENSHARE_AUDIO);t&&await a(this,q).closeProducer(t),e&&await a(this,q).closeProducer(e),a(this,Fs).clear(),a(this,pt).delete(Ie.SCREENSHARE_VIDEO),a(this,pt).delete(Ie.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await V(this,bt,Wt).call(this,Ie.WEBCAM);await a(this,q).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await V(this,bt,Wt).call(this,Ie.SCREENSHARE_VIDEO);await a(this,q).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,q).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,q).socketHandler.kickPeer(e)}kickAll(){a(this,q).socketHandler.kickAll()}async muteAll(t){if(!await a(this,q).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,q).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,q).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,q).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,ht).sendMessagePromise(a(this,Et).globalPinPeer,_C.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,q).producers.get(t.producerId)&&a(this,Fs).add(t.consumerPeerId),a(this,Fs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,q).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,ht).on(a(this,Et).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=IR.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===zs.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(k.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===zs.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,ht).on(a(this,Et).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=Yg.fromBinary(t);if(c)return;const d=i===zs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(Yg.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?k.MUTE_SELF:k.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(k.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(u.pause(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,ht).on(a(this,Et).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Qu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Fs).delete(e),a(this,q).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(k.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,ht).on(a(this,Et).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=OR.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(k.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,q).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,q).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,q).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,ht).on(a(this,Et).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,on)&&!a(this,cn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_DISCONNECTED),a(this,bc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,q).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(k.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,q).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(k.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}yc=new WeakMap,Ec=new WeakMap,ht=new WeakMap,q=new WeakMap,Ql=new WeakMap,Et=new WeakMap,on=new WeakMap,cn=new WeakMap,dn=new WeakMap,bc=new WeakMap,Ft=new WeakMap,Fs=new WeakMap,pt=new WeakMap,Rt=new WeakMap,wr=new WeakSet,vn=function(){return this.context.getValue("connectionHandler")},Xl=new WeakSet,RS=async function(t,e,r,i){var o;f(this,Ec,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,wr,vn).mediaState)!=null?o:{};(d==null?void 0:d.state)===Ds.CONNECTED&&(c==null?void 0:c.state)===Ds.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — partial reset (producers only)"),await a(this,q).closeAllProducersLocally(),a(this,pt).clear(),a(this,Fs).clear(),f(this,Ft,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Ft)?await a(this,Ft):await V(this,wc,mp).call(this,t,e,r,i,n),V(this,eu,AS).call(this,e);const{joined:c,error:d}=await V(this,Zl,IS).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{f(this,Ft,null)}},Zl=new WeakSet,IS=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,q).socketHandler.notifySelfJoinComplete();return f(this,yc,t.roomUuid),f(this,cn,!0),f(this,on,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},eu=new WeakSet,AS=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...Te.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},wc=new WeakSet,mp=async function(t,e,r,i,n=!1){try{const o=V(this,tu,MS).call(this);await V(this,su,OS).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,q).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},tu=new WeakSet,MS=function(){const t=LD("video/VP8");return f(this,Ql,t),t},su=new WeakSet,OS=async function(t,e,r,i){await Zf(async(n,o)=>{if(!a(this,ht).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,q).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},bt=new WeakSet,Wt=function(t){return a(this,pt).get(t)},ln=new WeakSet,Yc=function(t,e){return a(this,pt).set(t,e)},ru=new WeakSet,DS=function(t){return a(this,pt).delete(t)},iu=new WeakSet,NS=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},nu=new WeakSet,VS=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},de([E.trace("MediaNodeClient.reset")],ae.prototype,"reset",1),de([E.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1),de([E.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),de([E.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1),de([E.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1),de([E.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),de([E.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1),de([E.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),de([E.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1),de([E.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1),de([E.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1),de([E.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),de([E.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1),de([E.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),de([E.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),de([E.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1),de([E.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),de([E.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1),de([E.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),de([E.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),de([E.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1),de([E.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),de([E.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1),de([E.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),de([E.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1),de([E.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1),de([E.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1),de([E.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function av(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new ae(s,t);return s.setValue("roomNodeClient",r),r}function c1(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var d1=Object.defineProperty,l1=Object.getOwnPropertyDescriptor,ki=(s,t,e,r)=>{for(var i=r>1?void 0:r?l1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&d1(t,e,i),i};const ov=(Yv=class{constructor(s,t,e,r){g(this,It);p(this,"self");p(this,"authToken");g(this,La,void 0);p(this,"viewType");g(this,ws,void 0);g(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,La,i),f(this,ws,e),this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=wt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Je.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:A_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(m){l.error("Callstats:: initialization failed",{error:m})}},0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new ov(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===G.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,It,os).shareMic(s),this.self.audioEnabled||a(this,It,os).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===G.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,It,os).shareWebcam(t),this.self.videoEnabled||a(this,It,os).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===G.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,It,os))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,ee).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),a(this,It,os).reset({resetTransportQueue:!0}))}setupEvents(){a(this,ee).getValue("peerSessionStore").on(k.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,La).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),wt().setHeader("tracing-id",t),Rr.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ws).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ws).on(Ld.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(k.UPDATE_PERMISSIONS,t.patch)})}),a(this,ws).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ws).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ws).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(k.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(k.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,ee).getValue("peerSessionStore").on(k.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(k.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(k.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(k.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{this.logger.info("Joining socket room.");const{peer:t}=await a(this,ws).joinRoom(this.self);this.logger.info("Joined socket room."),a(this,ws).socket.flush();const e=fh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new C("Check the network and try again.","0002")}try{this.logger.info("Joining media room."),await this.joinMediaRoom(s),this.logger.info("Joined media room."),a(this,ee).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Lr&&t.message==="ice connection failed"?new C("A firewall or network restriction may be blocking the connection.","0014"):new C("Check the network and try again.","0014")}}async leaveRoom(s="left"){var t;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).setValue("roomNodeClient",void 0),a(this,ee).notify("stageStatus"),(t=a(this,ee).getValue("roomSocketHandler"))==null||t.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===Ws.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}av(a(this,ee),{socket:a(this,La),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,It,os))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Ws.Webinar)&&a(this,It,os)&&(a(this,It,os).mediaJoined&&s!=="disconnected"&&await a(this,It,os).leaveRoom(),!(s==="stageLeft"&&t===Ws.Livestream)&&(a(this,It,os).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},La=new WeakMap,ws=new WeakMap,ee=new WeakMap,It=new WeakSet,os=function(){return a(this,ee).getValue("roomNodeClient")},Yv);let xr=ov;ki([E.trace("SelfController.resetSelf")],xr.prototype,"resetSelf",1),ki([E.trace("SelfController.setupEvents")],xr.prototype,"setupEvents",1),ki([E.trace("SelfController.joinRoom")],xr.prototype,"joinRoom",1),ki([E.trace("SelfController.leaveRoom")],xr.prototype,"leaveRoom",1),ki([E.trace("SelfController.joinMediaRoom")],xr.prototype,"joinMediaRoom",1),ki([E.trace("SelfController.leaveMediaRoom")],xr.prototype,"leaveMediaRoom",1),ki([E.trace("SelfController.init")],xr,"init",1);class u1{constructor(t){g(this,Pc,void 0);f(this,Pc,t)}on(t,e){let r;t===U.roomPeerCount?r=Zg.fromBinary.bind(Zg):r=mf.fromBinary.bind(mf),a(this,Pc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Pc=new WeakMap;class h1{constructor(t,e){g(this,_c,void 0);g(this,kc,void 0);f(this,_c,e),f(this,kc,t)}get logger(){return a(this,kc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=Xu.fromBinary.bind(Xu),i=Xu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,_c).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}_c=new WeakMap,kc=new WeakMap;var p1=Object.defineProperty,m1=Object.getOwnPropertyDescriptor,Uh=(s,t,e,r)=>{for(var i=r>1?void 0:r?m1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&p1(t,e,i),i};class Qd{constructor(t,e){g(this,Pr,void 0);g(this,xa,void 0);f(this,Pr,e),f(this,xa,t)}get logger(){return a(this,xa).getValue("logger")}get telemetry(){return a(this,xa).getValue("telemetry")}getPolls(){return a(this,Pr).sendMessagePromise(Xs.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Pr).sendMessage(Xs.createPoll,oM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Pr).sendMessage(Xs.votePoll,dM.toBinary(r))}on(t,e){let r,i;switch(t){case Xs.updatePoll:case Xs.createPoll:case Xs.votePoll:{r=lh.fromBinary.bind(lh),i=lh.create();break}}a(this,Pr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Pr).removeListeners(t)}}Pr=new WeakMap,xa=new WeakMap,Uh([E.trace("PollSocketHandler.getPolls")],Qd.prototype,"getPolls",1),Uh([E.trace("PollSocketHandler.createPoll")],Qd.prototype,"createPoll",1),Uh([E.trace("PollSocketHandler.votePoll")],Qd.prototype,"votePoll",1);var g1=Object.defineProperty,f1=Object.getOwnPropertyDescriptor,v1=(s,t,e,r)=>{for(var i=r>1?void 0:r?f1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&g1(t,e,i),i};class cv{constructor(t,e){p(this,"socket");g(this,Ht,void 0);f(this,Ht,t),this.socket=e,this.handleSocketEvents(),a(this,Ht).setValue("roomSocketHandler",this)}get telemetry(){return a(this,Ht).getValue("telemetry")}get logger(){return a(this,Ht).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(U.joinRoom,oI.toBinary(e));try{const{peer:n}=Cn.fromBinary((await r).payload);a(this,Ht).getValue("connectionHandler").socketJoined=!0,a(this,Ht).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,Ht).getValue("peerSessionStore").emit(k.ROOM_STATE,d),a(this,Ht).getValue("peerSessionStore").emit(k.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return GI.fromBinary((await this.socket.sendMessagePromise(U.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(U.getRoomPeersInfo,QR.toBinary(n));i=th.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(U.getRoomPeersInfo);t=th.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(U.getRoomPeersInfo);t=th.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(U.getPeerInfo,sf.toBinary({peerId:t}));e=Cn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=tf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=tf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=df.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=df.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(U.broadcastMessage,to.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(U.broadcastToEntity,to.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(U.broadcastToEntity,to.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,dI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,of.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,Gg.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,QI.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,ZI.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Ld.updateUserPreset,R0.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=to.fromBinary(t);a(this,Ht).getValue("peerSessionStore").emit(k.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(U.broadcastToEntity,({payload:t})=>{try{const e=to.fromBinary(t);a(this,Ht).getValue("peerSessionStore").emit(k.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=Cn.fromBinary.bind(Cn),i=Cn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?cf.fromBinary(n,o):{requests:[]},i=cf.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=Sf.fromBinary.bind(Sf);break}case Ld.updateUserPreset:{r=uf.fromBinary.bind(uf);break}case hs.peerJoinedBroadcast:case Mr.peerJoinedBroadcast:{r=Kg.fromBinary.bind(Kg);break}case hs.selfJoinComplete:case Mr.selfJoinComplete:{r=Yu.fromBinary.bind(Yu);break}case hs.globalPeerPinBroadcast:case Mr.globalPeerPinBroadcast:{r=Qg.fromBinary.bind(Qg);break}case hs.selectedPeer:case Mr.selectedPeer:{r=zu.fromBinary.bind(zu);break}case hs.selectedPeerDiff:case Mr.selectedPeerDiff:{r=Jg.fromBinary.bind(Jg);break}case hs.leaveRoom:case Mr.leaveRoom:{r=Qu.fromBinary.bind(Qu);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Ld.getUserPresets,E0.toBinary(e)),i=_0.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}Ht=new WeakMap,v1([E.trace("RoomSocketHandler.joinRoom")],cv.prototype,"joinRoom",1);class S1{constructor(t){g(this,At,void 0);f(this,At,t)}async getStageRequests(){const{payload:t}=await a(this,At).sendMessagePromise(U.getStageRequests);return t?dh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,At).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,At).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,At).sendMessage(U.grantStageAccess,QA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,At).sendMessage(U.denyStageAccess,ZA.toBinary(e))}joinStage(){return a(this,At).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,At).sendMessagePromise(U.leaveStage,ff.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,At).sendMessagePromise(U.leaveStage,ff.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=gf.fromBinary.bind(gf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=dh.fromBinary.bind(dh);break}case U.peerStageStatusUpdate:{r=Xg.fromBinary.bind(Xg);break}}a(this,At).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,At).sendMessagePromise(U.getPeerInfo,sf.toBinary({peerId:t}));return Cn.fromBinary(e.payload)}}At=new WeakMap;class T1{constructor(t,e){g(this,oi,void 0);g(this,Ua,void 0);f(this,oi,e),f(this,Ua,t)}get logger(){return a(this,Ua).getValue("logger")}get peerId(){return a(this,Ua).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,oi).sendMessage(Qs.storeInsertKeys,MA.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,oi).sendMessage(Qs.storeGetKeys,DA.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,oi).sendMessage(Qs.storeDeleteKeys,VA.toBinary(n),i)}on(t,e){const r=pf.fromBinary.bind(pf);a(this,oi).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}oi=new WeakMap,Ua=new WeakMap;var y1=Object.defineProperty,E1=(s,t,e)=>t in s?y1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,b1=(s,t,e)=>(E1(s,typeof t!="symbol"?t+"":t,e),e),$h=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>($h(s,t,"read from private field"),e?e.call(s):t.get(s)),le=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>($h(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ne=(s,t,e)=>($h(s,t,"access private method"),e),Xd={},w1={get exports(){return Xd},set exports(s){Xd=s}},Dn=typeof Reflect=="object"?Reflect:null,dv=Dn&&typeof Dn.apply=="function"?Dn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Zd;Dn&&typeof Dn.ownKeys=="function"?Zd=Dn.ownKeys:Object.getOwnPropertySymbols?Zd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Zd=function(s){return Object.getOwnPropertyNames(s)};function P1(s){console&&console.warn&&console.warn(s)}var lv=Number.isNaN||function(s){return s!==s};function ue(){ue.init.call(this)}w1.exports=ue,Xd.once=R1,ue.EventEmitter=ue,ue.prototype._events=void 0,ue.prototype._eventsCount=0,ue.prototype._maxListeners=void 0;var uv=10;function el(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ue,"defaultMaxListeners",{enumerable:!0,get:function(){return uv},set:function(s){if(typeof s!="number"||s<0||lv(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");uv=s}}),ue.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},ue.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||lv(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function hv(s){return s._maxListeners===void 0?ue.defaultMaxListeners:s._maxListeners}ue.prototype.getMaxListeners=function(){return hv(this)},ue.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")dv(c,this,t);else for(var d=c.length,l=vv(c,d),e=0;e<d;++e)dv(l[e],this,t);return!0};function pv(s,t,e,r){var i,n,o;if(el(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=hv(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,P1(c)}return s}ue.prototype.addListener=function(s,t){return pv(this,s,t,!1)},ue.prototype.on=ue.prototype.addListener,ue.prototype.prependListener=function(s,t){return pv(this,s,t,!0)};function _1(){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 mv(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=_1.bind(r);return i.listener=e,r.wrapFn=i,i}ue.prototype.once=function(s,t){return el(t),this.on(s,mv(this,s,t)),this},ue.prototype.prependOnceListener=function(s,t){return el(t),this.prependListener(s,mv(this,s,t)),this},ue.prototype.removeListener=function(s,t){var e,r,i,n,o;if(el(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():k1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},ue.prototype.off=ue.prototype.removeListener,ue.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function gv(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?C1(i):vv(i,i.length)}ue.prototype.listeners=function(s){return gv(this,s,!0)},ue.prototype.rawListeners=function(s){return gv(this,s,!1)},ue.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):fv.call(s,t)},ue.prototype.listenerCount=fv;function fv(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ue.prototype.eventNames=function(){return this._eventsCount>0?Zd(this._events):[]};function vv(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function k1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function C1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function R1(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}Sv(s,t,n,{once:!0}),t!=="error"&&I1(s,i,{once:!0})})}function I1(s,t,e){typeof s.on=="function"&&Sv(s,"error",t,e)}function Sv(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class A1 extends S{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 Tv=new A1;class yv{static encode(t){return Tv.toBinary(t)}static decode(t){return Tv.fromBinary(new Uint8Array(t))}}function M1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Ur;class O1{constructor(t={}){b1(this,"opts"),le(this,Ur,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Ur,0)}async wait(){ie(this,Ur,M(this,Ur)+1);const t=M1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,Ur)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,Ur)}reset(){ie(this,Ur,0)}}Ur=new WeakMap;const $r={debug:0,info:1,warn:2,error:3};var Ci,Ri;class D1{constructor(t){le(this,Ci,void 0),le(this,Ri,void 0),ie(this,Ci,console),ie(this,Ri,t)}debug(...t){$r[M(this,Ri)]>$r.debug||M(this,Ci).debug("[Sockrates]:",...t)}info(...t){$r[M(this,Ri)]>$r.info||M(this,Ci).info("[Sockrates]:",...t)}warn(...t){$r[M(this,Ri)]>$r.warn||M(this,Ci).warn("[Sockrates]:",...t)}error(...t){$r[M(this,Ri)]>$r.error||M(this,Ci).error("[Sockrates]:",...t)}}Ci=new WeakMap,Ri=new WeakMap;var Ev=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(Ev||{});const bv="2",wv="3";var Me,Nn,he,ke,Br,Ke,ir,Fr,ms,Vn,Ln,nr,Bh,Pv,fo,tl,Fh,_v,sl,Hh,rl,qh,jh,kv,vo,il,xn,So,nl,Gh,Un,To,Wh,Cv,yo,al,Eo,ol;class N1{constructor(t,e){var y,w,R,P,N,$,x,H,F,Z,je,jt;le(this,Bh),le(this,fo),le(this,Fh),le(this,sl),le(this,rl),le(this,jh),le(this,vo),le(this,xn),le(this,nl),le(this,Un),le(this,Wh),le(this,yo),le(this,Eo),le(this,Me,void 0),le(this,Nn,void 0),le(this,he,void 0),le(this,ke,void 0),le(this,Br,void 0),le(this,Ke,void 0),le(this,ir,void 0),le(this,Fr,void 0),le(this,ms,void 0),le(this,Vn,void 0),le(this,Ln,void 0),le(this,nr,void 0);var r,i,n,o,c,d,l,u,h,m,v;ie(this,Nn,t),ie(this,Br,[]),ie(this,Ke,new Xd),ie(this,ir,!0),ie(this,ms,!1),ie(this,he,e!=null?e:{}),(y=(r=M(this,he)).autoReconnect)!=null||(r.autoReconnect=!0),(w=(i=M(this,he)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(R=(n=M(this,he)).pingTimeout)!=null||(n.pingTimeout=3e4),(P=(o=M(this,he)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(N=(c=M(this,he)).debug)!=null||(c.debug=!0),($=(d=M(this,he)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(x=(l=M(this,he)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(H=(u=M(this,he)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(F=(h=M(this,he)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(Z=(m=M(this,he)).clientInitiatedPings)!=null||(m.clientInitiatedPings=!1),(je=(v=M(this,he)).clientInitiatedPingInterval)!=null||(v.clientInitiatedPingInterval=3e4),ie(this,Fr,{code:void 0,reason:void 0}),ie(this,ke,(jt=M(this,he).logger)!=null?jt:new D1(M(this,he).debug?"debug":"info")),ie(this,nr,new O1)}get readyState(){var t;return(t=M(this,Me))==null?void 0:t.readyState}get url(){return M(this,Nn)}updateURL(t){ie(this,Nn,t),ne(this,jh,kv).call(this)}get config(){return M(this,he)}get sendQueue(){return M(this,Br)}flush(){if(!M(this,he).queueOnDisconnect)return!1;const t=[];return M(this,Br).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Br,t),M(this,Br)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,ke).debug("Websocket was already connecting or connected.");return}if(M(this,ir)!==!1)return new Promise((e,r)=>{ne(this,Un,To).call(this),ne(this,Eo,ol).call(this);try{ie(this,Me,new WebSocket(ne(this,Bh,Pv).call(this,M(this,Nn)))),M(this,Me).binaryType="arraybuffer",M(this,ke).debug("Connecting");const i=setTimeout(()=>{M(this,ke).debug("Connection timeout. Closing socket"),ie(this,ir,!0),ne(this,Eo,ol).call(this),M(this,Me).close(3001,"Connection Timeout"),M(this,he).autoReconnect&&!M(this,ms)&&(M(this,Ke).emit("reconnecting"),ne(this,vo,il).call(this)),r(new Error("Connection timed out!"))},M(this,he).connectionTimeout);M(this,Me).onopen=()=>{M(this,ke).debug(`Ready State: ${Ev[M(this,Me).readyState]}`),i&&clearTimeout(i),ne(this,nl,Gh).call(this),ne(this,Wh,Cv).call(this),ie(this,Fr,{code:void 0,reason:void 0}),M(this,Ke).emit("connected"),M(this,he).flushOnReconnect&&this.flush(),e()},M(this,Me).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,ke).debug("Socket closed. Close event:",{event:n}),M(this,ke).debug(`Connection closed code: ${o}`),M(this,ke).debug(`Connection closed reason: ${c}`),M(this,ms)||ne(this,rl,qh).call(this,o,c)}catch(o){ne(this,fo,tl).call(this,o)}},M(this,Me).onerror=n=>{ne(this,fo,tl).call(this,n)},M(this,Me).onmessage=n=>ne(this,Fh,_v).call(this,n)}catch(i){ne(this,fo,tl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,he).queueOnDisconnect&&(!M(this,Me)||M(this,Me).readyState!==1))return M(this,ke).debug("Queuing message since socket is not connected!",n),M(this,Br).push(n),!1;const o=yv.encode(n);return ne(this,xn,So).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ne(this,xn,So).call(this,t)}receive(t,e){return M(this,Ke).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,Ke).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,Ke).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,Ke).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,Ke).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,ir,!1),ne(this,Un,To).call(this),ne(this,yo,al).call(this),this.removeAllListeners(),ie(this,Fr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Me).close(1e3,"Sockrates disconnect method called.")}}Me=new WeakMap,Nn=new WeakMap,he=new WeakMap,ke=new WeakMap,Br=new WeakMap,Ke=new WeakMap,ir=new WeakMap,Fr=new WeakMap,ms=new WeakMap,Vn=new WeakMap,Ln=new WeakMap,nr=new WeakMap,Bh=new WeakSet,Pv=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},fo=new WeakSet,tl=function(s,t){M(this,ke).error("Error:",{error:s}),M(this,Ke).emit("errored",{error:s}),t==null||t(s)},Fh=new WeakSet,_v=function(s){if(ne(this,nl,Gh).call(this),s.data===bv){M(this,ke).debug("Received ping from server"),ne(this,xn,So).call(this,wv);return}if(s.data===wv){M(this,ke).debug("Received pong from server");return}const t=yv.decode(s.data),{id:e,payload:r}=t;M(this,ke).debug("Received message",{event:t.event,messageID:e}),M(this,Ke).emit(t.event.toString(),{id:e,payload:r})},sl=new WeakSet,Hh=function(){return M(this,Me).readyState===1},rl=new WeakSet,qh=function(s,t){ie(this,Fr,{reason:t,code:s}),M(this,Ke).emit("disconnected",{code:s,reason:t})},jh=new WeakSet,kv=function(){const{reason:s,code:t}=M(this,Fr);t&&t!==1e3&&M(this,ir)&&M(this,he).autoReconnect&&!M(this,ms)&&(M(this,ke).debug(`Triggering reconnection due to ${s}.`),M(this,Ke).emit("reconnecting"),ne(this,vo,il).call(this))},vo=new WeakSet,il=async function(s=!0){if(s&&M(this,ms)){M(this,ke).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ms)||M(this,nr).reset(),M(this,he).maxReconnectionAttempts!==null&&M(this,nr).getAttempts()>=M(this,he).maxReconnectionAttempts){M(this,Ke).emit("failed"),ie(this,ms,!1);return}ie(this,ms,!0),ne(this,Eo,ol).call(this),ne(this,Un,To).call(this);try{if(await M(this,nr).wait(),M(this,ir)===!1)return;if(M(this,ke).debug(`Reconnection attempt ${M(this,nr).getAttempts()}`),M(this,Ke).emit("reconnectAttempt",{attempt:M(this,nr).getAttempts()}),await this.connect(),!ne(this,sl,Hh).call(this))throw Error("Reconnect Failed");ie(this,ms,!1),ie(this,Fr,{code:void 0,reason:void 0}),M(this,Ke).emit("reconnected")}catch(t){M(this,ke).debug("Failed to reconnect."),M(this,Ke).emit("reconnectFailure",{attempt:M(this,nr).getAttempts()}),ne(this,vo,il).call(this,!1)}},xn=new WeakSet,So=function(s){try{return M(this,Me).send(s),!0}catch(t){return M(this,ke).error(t.message),!1}},nl=new WeakSet,Gh=function(){this.config.disconnectOnPingTimeout&&(M(this,ke).debug("Resetting ping timeout"),ne(this,Un,To).call(this),ie(this,Vn,setTimeout(()=>{var s;M(this,ke).debug("Disconnecting the socket due to ping timeout"),ie(this,ir,!0);const t=3002,e="Ping timeout";(s=M(this,Me))==null||s.close(t,e),ne(this,rl,qh).call(this,t,e)},M(this,he).pingTimeout)))},Un=new WeakSet,To=function(){M(this,Vn)&&(clearTimeout(M(this,Vn)),ie(this,Vn,void 0))},Wh=new WeakSet,Cv=function(){ne(this,yo,al).call(this),M(this,he).clientInitiatedPings&&ie(this,Ln,setInterval(()=>{ne(this,sl,Hh).call(this)&&(M(this,ke).debug("Sending client-initiated ping"),ne(this,xn,So).call(this,bv))},M(this,he).clientInitiatedPingInterval))},yo=new WeakSet,al=function(){M(this,Ln)&&(clearInterval(M(this,Ln)),ie(this,Ln,void 0))},Eo=new WeakSet,ol=function(){ne(this,yo,al).call(this),M(this,Me)&&(M(this,Me).onopen=void 0,M(this,Me).onerror=void 0,M(this,Me).onmessage=void 0,M(this,Me).onclose=void 0)};var V1=Object.defineProperty,L1=Object.getOwnPropertyDescriptor,cl=(s,t,e,r)=>{for(var i=r>1?void 0:r?L1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&V1(t,e,i),i};const Rv=65535,x1=3e3,Iv=(Qv=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Re);g(this,Cc);g(this,Rc);g(this,ci,void 0);g(this,Ce,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,as,void 0);g(this,st,void 0);if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,as,void 0),f(this,st,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,ci,V(this,Cc,gp).call(this,t));const n=i.includes("PING");f(this,Ce,new N1(a(this,ci),{autoReconnect:!0,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,maxReconnectionAttempts:50,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Re,Fe).socketJoinAttempted}set joinAttempted(s){a(this,Re,Fe).socketJoinAttempted=s}get telemetry(){return a(this,st).getValue("telemetry")}get logger(){return a(this,st).getValue("logger")}get peerId(){return a(this,st).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,ci,V(this,Cc,gp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ce).updateURL(a(this,ci))}static getSocketEdgeDomain(s){return _n({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,ci)}async connect(){a(this,Re,Fe).socketJoinAttempted=!0,await a(this,Ce).connect(),a(this,Re,Fe).socketJoinAttempted=!0,a(this,Re,Fe).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Re,Fe).socketJoinAttempted=!1,a(this,Ce).disconnect(),a(this,Re,Fe).socketJoinAttempted=!0,a(this,Re,Fe).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,st).getValue("telemetry").injectContext(r),a(this,Ce).send(s,e!=null?e:V(this,Rc,fp).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,w)=>{a(this,Ce).removeListener(n,y),a(this,Ce).removeListener(Rv,w),a(this,Ce).removeListener(Mr.errorResponse,w),a(this,Ce).removeListener(hs.errorResponse,w)},l=r!=null?r:V(this,Rc,fp).call(this),u={};a(this,st).getValue("telemetry").injectContext(u);const m=({id:y,payload:w})=>{if(l===y){let R;try{const P=qC.fromBinary(w);R=new Error(P.errorMessage)}catch(P){R=new Error("failed to parse error message",{cause:P});try{const N=jR.fromBinary(w);R=new Error(N.message)}catch(N){R=new Error("failed to parse error message",{cause:N})}}c(R),d(v,m)}},v=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(v,m))};a(this,Ce).on(n,v),a(this,Ce).on(Rv,m),a(this,Ce).on(Mr.errorResponse,m),a(this,Ce).on(hs.errorResponse,m),setTimeout(()=>{d(v,m),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Ce).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Ce).on(s,t)}onStateEvent(s,t){a(this,Ce).on(s,t)}removeListener(s,t){a(this,Ce).removeListener(s,t)}removeListeners(s){a(this,Ce).removeListeners(s)}flush(){return a(this,Ce).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,Re,Fe).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=a(this,Re,Fe).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Ds.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Ds.CONNECTED?a(this,st).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Re,Fe).joinAttempted}):f(this,as,setTimeout(()=>{a(this,st).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Re,Fe).joinAttempted}),f(this,as,void 0)},x1)),a(this,Re,Fe).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Re,Fe).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Re,Fe).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Re,Fe).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Re,Fe).mediaJoinAttempted}}),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,st).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Re,Fe).mediaJoinAttempted}),a(this,Re,Fe).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,st).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_FAILED),a(this,Re,Fe).updateSocketConnectionState("failed")})}},ci=new WeakMap,Ce=new WeakMap,Re=new WeakSet,Fe=function(){return a(this,st).getValue("connectionHandler")},as=new WeakMap,st=new WeakMap,Cc=new WeakSet,gp=function(s){const t=a(this,st).getValue("socketBaseURI")||a(this,st).getValue("baseURI");let e=Iv.getSocketEdgeDomain(t);typeof Pn(a(this,st),"socket_server_base")=="string"&&(e=Pn(a(this,st),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>Md[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Rc=new WeakSet,fp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},Qv);let bo=Iv;cl([E.trace("SocketService.connect")],bo.prototype,"connect",1),cl([E.trace("SocketService.disconnect")],bo.prototype,"disconnect",1),cl([E.trace("SocketService.sendMessagePromise")],bo.prototype,"sendMessagePromise",1),cl([E.trace("SocketService.sendMessagePromiseWithTimeout")],bo.prototype,"sendMessagePromiseWithTimeout",1);class U1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=vI.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=qI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=af.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return nf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return DI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,EI.toBinary({payloads:t}));return nf.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(U.deleteConnectedRooms,MI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,$I.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}}}}var $1=Object.defineProperty,B1=Object.getOwnPropertyDescriptor,F1=(s,t,e,r)=>{for(var i=r>1?void 0:r?B1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&$1(t,e,i),i};class Av extends Ot{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,qt,void 0);f(this,qt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,qt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,qt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,qt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,qt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,qt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,qt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,qt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,qt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,qt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}qt=new WeakMap,F1([Dt({maxInvocations:60,period:60})],Av.prototype,"getConnectedMeetings",1);var H1=Object.defineProperty,q1=Object.getOwnPropertyDescriptor,Jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?q1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&H1(t,e,i),i};const Mv=(Xv=class{constructor(s){p(this,"connectedMeetings");g(this,Se,void 0);f(this,Se,s),this.connectedMeetings=new Av(s)}get telemetry(){return a(this,Se).getValue("telemetry")}get logger(){return a(this,Se).getValue("logger")}static init(s){const t=new Mv(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,Se).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,Se).getValue("self").videoEnabled,audio:a(this,Se).getValue("self").audioEnabled};try{a(this,Se).getValue("self").cleanupEvents(),await a(this,Se).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,Se).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await Dv.init({...a(this,Se).getValue("options"),cachedUserDetails:null,defaults:{...a(this,Se).getValue("options").defaults,...e,mediaHandler:a(this,Se).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,Se).getValue("self");r.self.setName(a(this,Se).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,Se).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,Se).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},Se=new WeakMap,Xv);let dl=Mv;Jh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],dl.prototype,"getConnectedMeetings",1),Jh([E.trace("ConnectedMeetingsController.setupEvents")],dl.prototype,"setupEvents",1),Jh([E.trace("ConnectedMeetingsController.switchMeeting")],dl.prototype,"switchMeeting",1);var j1=Object.defineProperty,G1=Object.getOwnPropertyDescriptor,Kh=(s,t,e,r)=>{for(var i=r>1?void 0:r?G1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&j1(t,e,i),i};const wo=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var $,x,H;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(c1(s),Te.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=UM(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new yO(s);s.setValue("connectionHandler",l);let u="",h="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=(($=m.meeting)==null?void 0:$.title)||"",h=((x=m.socket)==null?void 0:x.baseUri)||s.getValue("baseURI"),s.setValue("presetName",m.preset.name),s.setValue("socketBaseURI",h),c.info(`Socket Base URI ${h} is being used`)}catch(F){throw c.error("Failed to get user details",{error:F}),F instanceof hh?F.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):F.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):F.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new C("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004")):F.status>=500?new C(`The server encountered an error. Try again. (${F.status})`,"0001"):F.isHttpError?new C(`Request rejected by the server. (${F.status})`,"0001"):F.isTimeout?new C("Connection timed out. Check the network and try again.","0001"):new C("Unable to connect to the server. Check the internet connection.","0001"):new C((F==null?void 0:F.message)||"Failed to initialize.","0001")}const v=wo.createSocketService(s),y=v.connect();try{await y}catch(F){c.error("[Controller]: Failed to connect to socket server:",{error:F})}const w=_h.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",w);const R=Ch.init(s,w.viewType,m.preset.permissions),P=wo.setupControllers(v,s,m,u,w,R);cO(w)&&((H=wo.createRoomNodeClient(s,v).initializeConnection(m.participant.name,i,!1,R))==null||H.catch(Z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Z})}));const{controllers:N}=await P;return Q_(),new wo(e,N,s)}static async setupControllers(s,t,e,r,i,n){var Ve,L,I;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:h}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(Ve=h.enableHighBitrate)!=null?Ve:!1,enableStereo:(L=h.enableStereo)!=null?L:!1}},...d}),t.setValue("maxPreferredStreams",Te.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let m,v,y,w,R,P,N,$,x;const H=new h1(t,s),F=new U1(s);t.setValue("connectedMeetingsSocketHandler",F);const Z=new Qd(t,s),je=new Zs(t,s),jt=new S1(s),Ps=new cv(t,s),gn=new T1(t,s),A=new u1(s),T=await xr.init(t,Ps,c,n,i);t.setValue("selfController",T);const _=await Cf.init(t,T.self,Ps,H,r);o.participant&&($=new rr(t,T.self,Ps)),(I=o.e2ee)!=null&&I.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(v=await ro.init(t,je,T.self,$.participants)),o.internals&&(R=await yh.init(t)),o.livestream&&i.viewType===Ws.Livestream&&(N=new Kf(t,T.self,A)),o.poll&&(m=await wf.init(t,T.self,Z)),o.recording&&(P=new Df(t,T.self,Ps)),o.stage&&(y=new Rf(t,jt,Ps,T.self,$.participants));const B=new SD(t,gn);if(o.plugin){if(!$)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Be=d.plugins||[];w=await Of.init(t,Be,T.self,B)}if(o.connectedMeetings&&(x=await dl.init(t)),o.pip){const Be=await Hu._init(t,T.self);t.setValue("pip",Be)}return{theme:i,permissions:n,controllers:{storesManager:B,pollController:m,selfController:T,metaController:_,chatController:v,stageController:y,pluginController:w,recordingController:P,internalsController:R,livestreamController:N,participantController:$,connectedMeetingsController:x}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return av(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new bo(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let ll=wo;Kh([E.trace("Controller.init")],ll,"init",1),Kh([E.trace("Controller.createRoomNodeClient")],ll,"createRoomNodeClient",1),Kh([E.trace("Controller.createSocketService")],ll,"createSocketService",1);class W1{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const Ov=new W1;function J1(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=fi.baseURI.prod;t&&(n=t);const o=`https://${_n({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new C("Invalid auth token","0004")}}class K1{constructor(){g(this,au);g(this,di,new Audio);g(this,un,new MediaStream);g(this,hn,new Map);g(this,Ic,void 0);a(this,di).srcObject=a(this,un),a(this,di).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,hn).has(e.id)||(a(this,un).addTrack(e),a(this,hn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,di).setSinkId(t)}removeTrack(t){const e=a(this,hn).get(t);e&&(a(this,un).removeTrack(e),a(this,hn).delete(t))}async play(){return a(this,di).srcObject=a(this,un),a(this,di).play().catch(t=>{V(this,au,LS).call(this,t)})}onError(t){f(this,Ic,t)}}di=new WeakMap,un=new WeakMap,hn=new WeakMap,Ic=new WeakMap,au=new WeakSet,LS=function(t){var e;(e=a(this,Ic))==null||e.call(this,t)};class z1 extends K1{constructor(){super();g(this,pn,void 0);f(this,pn,new Map)}addParticipantTrack(e,r){a(this,pn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,pn).get(e);r&&this.removeTrack(r),a(this,pn).delete(e)}}pn=new WeakMap;var Y1=Object.defineProperty,Q1=Object.getOwnPropertyDescriptor,ul=(s,t,e,r)=>{for(var i=r>1?void 0:r?Q1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&Y1(t,e,i),i};let Hr=(Zv=class{constructor(t,e){g(this,He,void 0);g(this,mn,void 0);f(this,mn,t),f(this,He,e)}get peerId(){return a(this,mn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:Sn(),n=Rr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Qf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var m,v,y,w,R,P,N,$,x;Te.init();const e=(v=(m=t==null?void 0:t.cachedUserDetails)==null?void 0:m.peerId)!=null?v:Sn(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=J1(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new C("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Hr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");BS(l),Ov.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(R=(w=t.modules)==null?void 0:w.tracing)!=null?R:!0,(N=(P=t==null?void 0:t.modules)==null?void 0:P.devTools)==null?void 0:N.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${($=t.authToken)==null?void 0:$.slice(0,10)}...
18
- ${(x=t.authToken)==null?void 0:x.slice(-10)}`}});const u=await ll.init(c),h=new Hr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Rr.createContext(t,e),o={...R_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",I_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Is(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.2-staging.5"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new z1),n}async join(){const{selfController:t}=a(this,He);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;Ov.cleanup(),a(this,mn).getValue("peerSessionStore").reset(),(r=a(this,He).pluginController)==null||r.cleanup();const{selfController:e}=a(this,He);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,He).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,He).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,He).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,He).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,He).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,He).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,He).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,He).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,He).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,He).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,He).stageController)==null?void 0:t.stage}get stores(){return a(this,He).storesManager}get audio(){return a(this,mn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,He).internalsController)==null?void 0:t.internals}},He=new WeakMap,mn=new WeakMap,Zv);ul([dt("0002"),tr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Hr.prototype,"join",1),ul([dt("0003")],Hr.prototype,"leave",1),ul([dt("0001"),tr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Hr,"init",1),Hr=ul([dt("0000")],Hr);const Dv=Hr;return Dv}();
17
+ `},wi=tS,GD=jD,zd=GD,Pi=wi.parse;wi.parseParams,wi.parseFmtpConfig,wi.parsePayloads,wi.parseRemoteCandidates,wi.parseImageAttributes,wi.parseSimulcastStreamList;class Yd extends Mh{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Yd(e,r)}get name(){return"Firefox60"}async send({track:e,encodings:r,codecOptions:i,screenShare:n}){this._assertSendDirection();const o=this.supportsSendEncodings&&r!==void 0?{sendEncodings:r}:{},c=this.pc.addTransceiver(e,{direction:"sendonly",streams:[n?this._sendScreenShareStream:this._sendWebStream],...o});if(!this.supportsSendEncodings&&r){r.reverse();const h=c.sender.getParameters();h.encodings=r,await c.sender.setParameters(h)}const d=(h,m)=>{var V;const S=Pi(h),y=S.media[S.media.length-1],w=y.rtp.filter($=>m.some(H=>H.name===$.codec)),_=y.fmtp.filter($=>w.some(H=>H.payload===$.payload)),C=(V=y.rtcpFb)==null?void 0:V.filter($=>w.some(H=>H.payload===$.payload)),D=w.map($=>$.payload);return S.media[S.media.length-1].rtp=w,S.media[S.media.length-1].fmtp=_,S.media[S.media.length-1].rtcpFb=C,S.media[S.media.length-1].payloads=D.join(" "),zd(S)},l=await this.pc.createOffer();if(l.sdp=d(l.sdp,i),this.logger.debug(`[SDP] send() | calling pc.setLocalDescription() [offer:${JSON.stringify(l)}]`),await this.pc.setLocalDescription(l),e==="audio"||e.kind==="audio"){const{enableDtx:h,enableStereo:m}=this,S=this.enableHighBitrate?m?128e3:64e3:m?64e3:32e3;l.sdp=l.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${m?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${S}`)}return this.midTransceiverMap.set(c.mid,c),{offerSdp:l,callback:async h=>(this.logger.debug(`send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(h)}]`),await this.pc.setRemoteDescription(h),c.mid),sender:c.sender,mid:c.mid}}async setMaxSpatialLayer(e,r){this._assertSendDirection(),this.logger.debug(`setMaxSpatialLayer() [localId:${e}, spatialLayer:${r}]`);const i=this.midTransceiverMap.get(e);if(!i)throw new Error("associated RTCRtpTransceiver not found");const n=i.sender.getParameters(),o=n.encodings.length-1-r;n.encodings.forEach((c,d)=>{d>=o?c.active=!0:c.active=!1}),await i.sender.setParameters(n)}addCustomEventListeners(){this.pc.addEventListener("datachannel",e=>{const{channel:r}=e;r.onmessage=async i=>{const n=await i.data.arrayBuffer();this.safeEmit("datachannel",e.channel,String.fromCharCode(...new Uint8Array(n)))}})}}class Nh extends Mh{static createFactory(t){return()=>new Nh(t)}get name(){return"Safari12"}async send({track:t,encodings:e,codecOptions:r,screenShare:i}){this._assertSendDirection(),this.logger.debug("Safari12::creating new transceiver");const n=this.pc.addTransceiver(t,{direction:"sendonly",streams:[i?this._sendScreenShareStream:this._sendWebStream],sendEncodings:e}),o=RTCRtpSender.getCapabilities(typeof t=="string"?t:t.kind);this.logger.info(`Safari12::senders available params: ${JSON.stringify(o)}`);const c=[];r&&r.length>0&&r.forEach(u=>{var m;const h=o.codecs.find(S=>S.mimeType.includes(u.name));if(u.parameters){this.logger.info(`Safari12::codecOption.parameters:, ${JSON.stringify(u.parameters)}`);const S=((m=h.sdpFmtpLine)==null?void 0:m.split(";"))||[];S.push(...u.parameters);const y=[...new Set(S).values()];h.sdpFmtpLine=y.join(";")}c.push(h)}),this.logger.info(`Safari12::selected codecs: ${JSON.stringify(c)}`),n.setCodecPreferences(c);const d=await this.pc.createOffer();if(await this.pc.setLocalDescription(d),t==="audio"||t.kind==="audio"){const{enableStereo:u,enableDtx:h}=this,m=this.enableHighBitrate?u?128e3:64e3:u?64e3:32e3;d.sdp=d.sdp.replace("minptime=10;useinbandfec=1",`minptime=10;useinbandfec=1;${h?"usedtx=1;":""}${u?"stereo=1;sprop-stereo=1;":""}maxaveragebitrate=${m}`)}return this.midTransceiverMap.set(n.mid,n),{offerSdp:d,callback:async u=>(this.logger.debug(`Safari12::send() | calling pc.setRemoteDescription() [answer:${JSON.stringify(u)}]`),await this.pc.setRemoteDescription(u),n.mid),sender:n.sender,mid:n.mid}}addCustomEventListeners(){this.pc.ondatachannel=t=>{const{channel:e}=t;e.onmessage=async r=>{const i=String.fromCharCode(...new Uint8Array(r.data));this.safeEmit("datachannel",t.channel,i)}}}}function WD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class JD extends Jd{constructor(e,r){var i;super(e);g(this,xs);g(this,ec);g(this,Rl);g(this,Il);p(this,"rtpReceiver");p(this,"id");p(this,"localId");p(this,"producerId");p(this,"producingTransportId");p(this,"mimeType");p(this,"track");p(this,"peerId");p(this,"appData");p(this,"transceiver");g(this,Zo,void 0);g(this,zi,void 0);g(this,Ls,void 0);g(this,Cl,void 0);this.id=r.id,this.localId=r.localId,f(this,Zo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ls,!1),this.producerId=r.producerId,this.track=r.track,f(this,zi,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,L(this,Rl,lv).call(this),f(this,Cl,e)}get closed(){return a(this,Ls)}get kind(){return this.track.kind}get paused(){return a(this,zi)}close(e,r){a(this,Ls)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,xs,li)),f(this,Ls,!0),r&&(L(this,Il,uv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ls))throw new kt("closed");return a(this,Zo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,xs,li)),a(this,Ls)){this.logger.error("consumer::pause() | Consumer closed",a(this,xs,li));return}f(this,zi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,xs,li)),a(this,Ls)){this.logger.error("Consumer::resume() | Consumer closed",a(this,xs,li));return}f(this,zi,!1),this.track.enabled=!0,this.safeEmit("resume")}}Zo=new WeakMap,zi=new WeakMap,Ls=new WeakMap,Cl=new WeakMap,xs=new WeakSet,li=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},ec=new WeakSet,cp=function(){this.logger.debug('Consumer::track "ended" event',a(this,xs,li)),this.safeEmit("trackended")},Rl=new WeakSet,lv=function(){this.track.addEventListener("ended",L(this,ec,cp).bind(this))},Il=new WeakSet,uv=function(){try{this.track.removeEventListener("ended",L(this,ec,cp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,xs,li),error:e})}};class KD extends Jd{constructor(e,r){var i,n;super(e);g(this,Ft);p(this,"id");p(this,"localId");g(this,ys,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,va,void 0);g(this,Ta,void 0);g(this,Yi,void 0);g(this,is,!1);g(this,ot,void 0);g(this,ti,void 0);g(this,ya,void 0);g(this,Al,void 0);this.id=r.id,this.localId=r.localId,f(this,ot,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,ti,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,ya,void 0),f(this,va,r.stopTracks),f(this,Ta,r.disableTrackOnPause),f(this,Yi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,ys,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Al,e)}get closed(){return a(this,is)}get track(){return a(this,ot)}get paused(){return a(this,ti)}get maxSpatialLayer(){return a(this,ya)}async close(e){if(a(this,is))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Ft,_s)),f(this,is,!0),this._destroyTrack(),e===po){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,ys).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,is))throw new kt("closed");return a(this,ys).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Ft,_s)),a(this,is)&&this.logger.error("Producer::pause() | Producer closed",a(this,Ft,_s)),f(this,ti,!0),a(this,ot)&&a(this,Ta)&&(a(this,ot).enabled=!1),a(this,Yi)&&a(this,ys).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Ft,_s)),a(this,is)){this.logger.error("Producer::resume() | Producer closed",a(this,Ft,_s));return}f(this,ti,!1),a(this,ot)&&a(this,Ta)&&(a(this,ot).enabled=!0),a(this,Yi)&&a(this,ys).replaceTrack(this.localId,a(this,ot)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,Ft,_s)),a(this,is)){if(e&&a(this,va))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Ft,_s),error:r})}throw new kt("closed")}else if(e&&e.readyState==="ended")throw new kt("track ended");if(e===a(this,ot)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Ft,_s));return}(!a(this,Yi)||!a(this,ti))&&await a(this,ys).replaceTrack(this.localId,e),this._destroyTrack(),f(this,ot,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,is))throw new kt("closed");if(this.kind!=="video")throw new uo("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,ys).setMaxSpatialLayer(this.localId,e),f(this,ya,e)}async setRtpEncodingParameters(e){if(a(this,is))throw new kt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,ys).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Ft,_s)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,ot)&&a(this,ot).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,ot))try{a(this,ot).removeEventListener("ended",this._onTrackEnded),a(this,va)&&a(this,ot).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Ft,_s),error:r})}}}ys=new WeakMap,va=new WeakMap,Ta=new WeakMap,Yi=new WeakMap,is=new WeakMap,ot=new WeakMap,ti=new WeakMap,ya=new WeakMap,Al=new WeakMap,Ft=new WeakSet,_s=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function rS(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Vh(s){return Math.random().toString(36).substring(2,2+s)}const Qd=1;function iS(s){const t=s;return delete t.payload._bolt,t}function zD(s){return s.payload&&rS(s.payload)}function YD(s){var t,e;return zD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const Ea=class extends dt.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");g(this,si,new Map);g(this,Ml,void 0);g(this,Qi,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=Ea.createErrorResponse(e,r):n=Ea.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=Ea.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=Ea.createRequest(e),i=new Promise((n,o)=>{const{id:d}=r.payload._bolt,l={id:d,method:r.type,resolve:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),n(u))},timer:setTimeout(()=>{this.queue.delete(d)&&o(new Error(`request timeout for message id: ${d}`))},2e4),cancel:u=>{this.queue.delete(d)&&(clearTimeout(l.timer),o(u))}};this.queue.set(d,l)});return this.channel.send(JSON.stringify(r)),i});p(this,"send",e=>{const r=JSON.stringify(e),i=16384;if(r.length>i){const n=i-200,o=Math.ceil(r.length/n),c=[];for(let l=0;l<o;l+=1){const u=l*n,h=(l+1)*n;c.push(r.slice(u,h))}const d=vn();for(let l=0;l<o;l+=1){const u=c[l],m=JSON.stringify({id:d,count:o,chunkIndex:l,chunk:u});a(this,Qi).debug(`Sending message chunk over dc: ${m}`),this.channel.send(m)}}else a(this,Qi).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,si).has(e.id)||a(this,si).set(e.id,[]);const r=a(this,si).get(e.id);if(r[e.chunkIndex]=e,(r==null?void 0:r.length)===e.count&&!r.some(n=>n===void 0)){const n=a(this,si).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,si).delete(e.id);const c=JSON.parse(o);if(!c.payload||!rS(c.payload))throw new Error("corrupted incoming message over dc",{cause:{code:"CORRUPT_DC_MESSAGE",values:c}});if(this.processBoltHandshake(c))return;if(this.serverProtocolVersion=(i=c.payload._bolt)==null?void 0:i.version,!this.processResponseMsg(c))return c}});p(this,"processResponseMsg",e=>{const{id:r}=e.payload._bolt,i=this.queue.get(r);return i?(a(this,Qi).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(iS(e)):i.resolve(iS(e)),!0):!1});p(this,"processBoltHandshake",e=>{var r,i;return e.type==="_bolt"||e.type==="handshake"?(this.respond((i=(r=e.payload._bolt)==null?void 0:r.id)!=null?i:Vh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Ml,e),f(this,Qi,e.getValue("logger")),this.channel=r,this.queue=new Map}};let _i=Ea;si=new WeakMap,Ml=new WeakMap,Qi=new WeakMap,p(_i,"createRequest",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,_bolt:{id:Vh(8),type:"REQUEST",version:Qd}}}}),p(_i,"createResponse",(e,r)=>{var i;if((i=r.payload)!=null&&i._bolt)throw new Error("rpc fields are internal values");return{type:r.type,payload:{...r.payload,_bolt:{id:e,type:"RESPONSE",version:Qd}}}}),p(_i,"createNotification",e=>{var r;if((r=e.payload)!=null&&r._bolt)throw new Error("rpc fields are internal values");return{type:e.type,payload:{...e.payload,bolt:{id:Vh(8),type:"NOTIFY",version:Qd}}}}),p(_i,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Qd}}}));const po="transport closed",ba=class extends Jd{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,_,C;super(e);p(this,"awaitQueue");p(this,"observer");p(this,"id");p(this,"serverId");p(this,"direction");p(this,"maxSctpMessageSize");p(this,"handler");p(this,"connectionState","new");p(this,"producers");p(this,"consumers");p(this,"datachannels");p(this,"connected",!1);p(this,"eventsDCReadyPromise");p(this,"eventsDCReadyPromiseResolver");p(this,"eventsDCFailureTimer");p(this,"transportConnectionPromise");p(this,"consumerTrackEvents");p(this,"unknownTracksMap");p(this,"appData");g(this,Xi,void 0);f(this,Xi,e);const m=e.getValue("logger");m.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=WD(l,{});delete S.iceServers,delete S.iceTransportPolicy,delete S.bundlePolicy,delete S.rtcpMuxPolicy,delete S.sdpSemantics,this.producers=new Map,this.consumers=new Map,this.datachannels=new Map,this.consumerTrackEvents=new Map,this.unknownTracksMap=new Map,this.awaitQueue=new Ah(m,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(_=h==null?void 0:h.enableStereo)!=null?_:!1,this.handler.enableDtx=(C=h==null?void 0:h.enableDtx)!=null?C:!0,this.handler.init({onTrackHandler:this._ontrack.bind(this),direction:i,iceServers:o,iceTransportPolicy:c,additionalSettings:l,proprietaryConstraints:d}),this.appData=u||{};const y=3e4;this.transportConnectionPromise=new Promise(D=>{const V=setTimeout(()=>{m.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),D(!1)},y);this.once("connected",()=>{clearTimeout(V),D(!0)}),this.once("disconnect",()=>{clearTimeout(V),D(!1)}),this.once("close",()=>{clearTimeout(V),D(!1)})}),this.eventsDCReadyPromise=new Promise(D=>{this.eventsDCReadyPromiseResolver=D}),this.handler.on("@connectionstatechange",D=>{D!==this.connectionState&&(this.logger.debug(`connection state changed to ${D}`),this.connectionState=D,D==="connected"&&(this.connected=!0,this.emit("connected")),D==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(D==="failed"||D==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",D))}),this.handler.on("@icecandidate",({candidate:D})=>{this.closed||this.safeEmit("icecandidate",D)}),this.handler.on("dc_open",D=>{let V=this.datachannels.get(D.label);V||(V||(V=new _i(a(this,Xi),D,D.label,this.serverId),this.datachannels.set(D.label,V)),this.eventsDCFailureTimer=setTimeout(()=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",D.label))},5e3))}),this.handler.on("datachannel",(D,V)=>{D.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const $=this.datachannels.get(D.label);if(!$){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:D.label,message:V}});return}try{const H=JSON.parse(V);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:H.id,count:H.count,chunkIndex:H.chunkIndex,chunk:H.chunk,transprtId:this.serverId}});const F=$.processMessage(H);if(!F)return;this.logger.debug(`datachannel message with id:${H.id} on transport:${this.serverId}complete - ${JSON.stringify(F)}`),this.emit(`datachannel:${D.label}`,$.label,F)}catch(H){this.logger.error("error parsing message",{error:H})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId!==e&&(this.serverId=e,this.emit("serveridchange",e))}getDatachannel(e){return this.datachannels.get(e)}get isEventsDCReady(){return this.eventsDCReadyPromise}close(){this.closed||(this.logger.debug("Transport close called"),this.connectionState="closed",this.awaitQueue.stop(),this.awaitQueue=void 0,this.connected=!1,this.handler.close(),Array.from(this.producers.values()).forEach(e=>{e.close(po).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(po)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new kt("closed");return this.handler.getTransportStats()}async connect(e){try{if(await this.awaitQueue.push(async()=>{const{offerSdp:r,callback:i}=await this.handler.connect(),{transportId:n,answer:o}=await e(r);this.setServerId(n),await i(o)}),!await this.transportConnectionPromise)throw new Error("ice connection failed")}catch(r){throw this.logger.error("transport failed to connect:",{error:r}),r}}async restartIce(){if(this.logger.debug("restartIce()"),this.closed)throw new kt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new uo("not a sending Transport");if(r.readyState==="ended")throw new kt("track ended");if(i&&typeof i!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing track");if(!await this.transportConnectionPromise)throw new Lr("transport not connected");return!0}async produce(e,r){if(!await this.canProduce(e))throw new Error("Cannot produce");const{track:n,encodings:o,codecOptions:c,stopTracks:d=!0,disableTrackOnPause:l=!0,zeroRtpOnPause:u=!1,appData:h={}}=e;this.logger.debug(`produce() [track:${n.id}]`);const{producerId:m,localId:S,rtpSender:y}=await this.awaitQueue.push(async()=>{const{offerSdp:w,callback:_,sender:C,mid:D}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:V,producerId:$}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:D},codecOptions:c,producingTransportId:this.serverId}),H=await _(V);return{producerId:$,localId:H,rtpSender:C}},"Transport.produce");return this.createProducerObject({id:m,localId:S,track:n,stopTracks:d,disableTrackOnPause:l,zeroRtpOnPause:u,appData:h,handler:this.handler,rtpSender:y})}async createProducerObject(e){const r=new KD(a(this,Xi),e);return this.producers.set(r.id,r),r.once("close",()=>{this.producers.delete(r.id)}),this.emit("newproducer",r),r}async closeProducer(e){await this.awaitQueue.push(e.close.bind(e),"Transport.closeProducer")}async canConsume(){if(this.closed)throw new kt("closed");if(this.direction!=="recv")throw new uo("not a receiving transport");if(!await this.transportConnectionPromise)throw new Lr("transport not connected");return!0}async consume(e,r,i){return this.awaitQueue.push(async()=>{const n={},{consumerStates:o,sessionDescription:c,failedProducers:d}=await r(e);o.forEach((u,h)=>{n[h]=this.createConsumerObjectAndWaitForTrack({...u,producerId:h})}),c&&(this.logger.info("Session description found, sending negotiation request"),await i(c));const l=[];return await Promise.all(Object.entries(n).map(([u,h])=>h.then(m=>l.push(m)).catch(()=>{this.logger.error(`Failed to create consumer object, producer: ${u}`,{error:{message:"This should not happen"},transport:{serverId:this.serverId}})}))),{consumers:l,failedProducers:d}},"Transport.consume",{producersLength:e.length})}static parseCodecAndFmtpMappings(e,r){const i=Pi(e.sdp),n={};return i.media.forEach(o=>{r.includes(o.mid.toString())&&(n[o.mid.toString()]={rtp:o.rtp,fmtp:o.fmtp,payloads:o.payloads,rtcpFb:o.rtcpFb})}),n}static setCodecAndFmtpMappings(e,r,i){const n=Pi(e.sdp);return n.media=n.media.map(c=>{if(r.includes(c.mid.toString())){const d={...c};return d.rtp=i[c.mid.toString()].rtp,d.fmtp=i[c.mid.toString()].fmtp,d.payloads=i[c.mid.toString()].payloads,d.rtcpFb=i[c.mid.toString()].rtcpFb,d}return c}),{...e,sdp:zd(n)}}static parseHeaderExtensionMappings(e){const r=Pi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=Pi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:zd(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=ba.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=ba.parseHeaderExtensionMappings(this.handler.pc.remoteDescription);this.logger.info("Stopping transceivers",{consumerIds:e.map(({id:l})=>l)}),e.forEach(l=>l.close(void 0,!0));let c=await this.handler.pc.createOffer();this.logger.info("[SDP] Created offer for closing consumers",{sdp:c.sdp}),c=ba.setCodecAndFmtpMappings(c,i,n),c=ba.setHeaderExtensionMappings(c,o),this.logger.info("[SDP] Updated codec and fmtp mappings in close consumer offer",{sdp:c.sdp}),await this.setLocalDescription(c),this.logger.info("Successfully set local description in close consumers");const d=await r(e,c);this.logger.info("[SDP] Received answer in close consumers",{sdp:d.sdp}),await this.setRemoteDescription(d),this.logger.info("[SDP] Remote description was set successfully in close consumers",{sdp:d.sdp})}catch(i){this.logger.error("Failed to close consumers",{error:i})}}async setRemoteOffer(e){try{this.logger.info("[SDP] Received offer from SFU",{sdp:e.sdp}),await this.setRemoteDescription(e);const r=await this.handler.pc.createAnswer();this.logger.info("[SDP] Created answer corresponding to received offer",{sdp:r.sdp});const i=Pi(r.sdp);return i.media=i.media.map(n=>{if(n.type==="audio"){const o={...n},c=o.fmtp.find(l=>l.payload===111);return c&&(c.config+=";stereo=1;sprop-stereo=1"),o.rtcpFb||(o.rtcpFb=[]),o.rtcpFb.some(l=>l.type==="nack")||o.rtcpFb.push({payload:parseInt(o.payloads,10),type:"nack"}),o}return n}),r.sdp=zd(i),this.logger.info("[SDP] Setting munged SDP",{sdp:r.sdp}),await this.setLocalDescription(r),this.logger.info("[SDP] Successfully set local description",{sdp:r.sdp}),r}catch(r){throw this.logger.error("Set remote offer failed",{error:r}),r}}_ontrack(e){const{track:r,transceiver:i}=e;this.logger.info(`track event received [trackId: ${r.id}] [mid: ${i.mid}]`);const n=`${i.mid}:${r.kind}`;r.addEventListener("ended",()=>{this.logger.info(`rtc consumer track ended [trackId: ${r.id}]`),this.unknownTracksMap.delete(n)});const o=this.consumerTrackEvents.get(n);o?(o(r,i),this.consumerTrackEvents.delete(n)):(this.logger.warn(`track event handler not found ${n}`),this.unknownTracksMap.set(n,e))}sendErrorOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i,!0)}sendResponseOverDC(e,r,i){const n=this.getDatachannel(e);if(!n)throw new Error("datachannel not found",{cause:{code:"DC_NOT_FOUND",values:{label:e}}});n.respond(r,i)}async createConsumerObjectAndWaitForTrack(e){const{consumerId:r,producerId:i,producingPeerId:n,producingTransportId:o,streamId:c,paused:d,screenShare:l,appData:u,kind:h,mimeType:m}=e,S=`${c}:${h}`,y={...e,name:"consumer creation task error",message:"consumer creation failed"};return new Promise(async(w,_)=>{const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,_(y)},5e3),D=($,H)=>{try{if($.readyState==="ended")clearTimeout(C),_(y);else{const F=$;F.enabled=!0,this.handler.midTransceiverMap.set(H.mid,H);const Z=new JD(a(this,Xi),{id:r,localId:H.mid,transceiver:H,track:F,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:H.receiver,mimeType:m});this.consumers.set(r,Z),Z.once("close",()=>{this.consumers.delete(Z.id),this.handler.midTransceiverMap.delete(H.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",Z),clearTimeout(C),w(Z)}}catch(F){this.logger.warn("error while creating consumer:",F),clearTimeout(C),_(y)}},V=this.unknownTracksMap.get(S);V?(this.logger.info(`track event already received [trackId: ${V.track.id}] [mid: ${V.transceiver.mid}]`),this.unknownTracksMap.delete(S),D(V.track,V.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,D))})}async setRemoteDescription(e){await this.handler.pc.setRemoteDescription(e)}async setLocalDescription(e){this.logger.debug(`[SDP] ${this.direction}() {transportId: ${this.serverId}} | calling pc.setLocalDescription() [offer:${JSON.stringify(e)}]`),await this.handler.pc.setLocalDescription(e)}async sendDataChannelMessage(e,r){const i=this.getDatachannel(e);if(!i)throw ND("DC_NOT_READY",`${e} datachannel not ready`);const n=(await i.request(r)).payload;return this.logger.info(`sendDataChannelMessage::response ${JSON.stringify(n)}`),n}};let Lh=ba;Xi=new WeakMap;function QD(s){if(typeof navigator=="object"&&navigator.product==="ReactNative"){if(typeof RTCPeerConnection=="undefined"){s.warn("Device::this._detectDevice() | unsupported ReactNative without RTCPeerConnection");return}return s.debug("Device::this._detectDevice() | ReactNative handler chosen"),"Chrome74"}if(typeof navigator=="object"&&typeof navigator.userAgent=="string"){const t=navigator.userAgent,e=Tp.getParser(t),r=e.getEngine();if(e.satisfies({chrome:">=74",chromium:">=74","microsoft edge":">=88"}))return"Chrome74";if(e.satisfies({chrome:">=55",chromium:">=55"}))return;if(e.satisfies({firefox:">=110"}))return"Firefox110";if(e.satisfies({firefox:">=60"}))return"Firefox60";if(e.satisfies({ios:{OS:">=14.3",firefox:">=30.0"}})||e.satisfies({safari:">=12.0"})&&typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection"))return"Safari12";if(e.satisfies({safari:">=11"})||e.satisfies({"microsoft edge":">=11"})&&e.satisfies({"microsoft edge":"<=18"}))return;if(r.name&&r.name.toLowerCase()==="blink"){const i=t.match(/(?:(?:Chrome|Chromium))[ /](\w+)/i);return i?Number(i[1])>=74?"Chrome74":void 0:"Chrome74"}if(r.name.toLowerCase()==="webkit"&&e.getOS().name.toLowerCase()==="ios")return typeof RTCRtpTransceiver!="undefined"&&RTCRtpTransceiver.prototype.hasOwnProperty("currentDirection")?"Safari12":void 0;s.warn("Device::this._detectDevice() | browser not supported");return}s.warn("Device::this._detectDevice() | unknown device")}class XD{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,fr,void 0);g(this,Zi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,fr,t),f(this,Zi,i),e&&r)throw new TypeError("just one of handlerName or handlerInterface can be given");if(r)this.handlerFactory=r;else{if(e)a(this,Zi).debug(`Device::constructor() | handler given: ${e}`);else if(e=QD(a(this,Zi)),e)a(this,Zi).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Oh.createFactory(a(this,fr));break;case"Safari12":this.handlerFactory=Nh.createFactory(a(this,fr));break;case"Firefox60":this.handlerFactory=Yd.createFactory(a(this,fr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Yd.createFactory(a(this,fr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=vn();return new Lh(a(this,fr),{id:e,...t,handlerFactory:this.handlerFactory})}}fr=new WeakMap,Zi=new WeakMap;const ZD=2e3;class e1 extends dt.EventEmitter{constructor(e,r){super();g(this,ka);g(this,ic);g(this,Ol);g(this,nc);g(this,Dl);g(this,Nl);g(this,Vl);g(this,Ll);g(this,xl);g(this,ac);g(this,ri);p(this,"context");g(this,wa,void 0);g(this,tt,void 0);g(this,st,void 0);g(this,tc,void 0);g(this,sc,void 0);g(this,en,void 0);g(this,Pa,void 0);g(this,rc,void 0);g(this,_a,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,tn,void 0);g(this,Us,"all");this.context=e,f(this,en,r),f(this,wa,new XD(e)),f(this,Pa,new UD(r)),f(this,rc,hs),a(this,ka,hu).mediaState={send:{state:Ds.NEW},recv:{state:Ds.NEW}},Pn(this.context,"forceRelay")&&f(this,Us,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Us)}`),L(this,ic,dp).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,en)}get socketHandler(){return a(this,Pa)}get sendTransport(){return a(this,tt)}get recvTransport(){return a(this,st)}get events(){return a(this,rc)}set sendTransportConnectedCallback(e){f(this,tc,e)}set recvTransportConnectedCallback(e){f(this,sc,e)}async setupTransports(e){await L(this,Ol,hv).call(this,e);let r,i;e.send&&(r=L(this,nc,lp).call(this,a(this,tt)).then(n=>{try{a(this,tc).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=L(this,nc,lp).call(this,a(this,st)).then(n=>{try{a(this,sc).call(this,n)}catch(o){this.logger.error("Failed to run recv transport callback")}})),await Promise.all([r,i])}stopTransports(e){var r,i;if(e.send&&this.sendTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,tt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,tt).close(),a(this,tt).removeAllListeners(),f(this,tt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,st);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,st))==null||r.close(),(i=a(this,st))==null||i.removeAllListeners(),f(this,st,void 0)}L(this,ic,dp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}wa=new WeakMap,tt=new WeakMap,st=new WeakMap,tc=new WeakMap,sc=new WeakMap,en=new WeakMap,Pa=new WeakMap,rc=new WeakMap,_a=new WeakMap,tn=new WeakMap,Us=new WeakMap,ka=new WeakSet,hu=function(){return this.context.getValue("connectionHandler")},ic=new WeakSet,dp=function(){f(this,tn,{send:void 0,recv:void 0})},Ol=new WeakSet,hv=async function(e){var o,c,d,l,u,h,m,S;Pn(this.context,"forceRelay")&&f(this,Us,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Us)}`);const n=await Pt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&L(this,Nl,mv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(o=this.context.getValue("modules").e2ee)==null?void 0:o.enabled},config:{enableHighBitrate:(l=(d=(c=this.context.getValue("defaults").mediaConfiguration)==null?void 0:c.audio)==null?void 0:d.enableHighBitrate)!=null?l:!1,enableStereo:(m=(h=(u=this.context.getValue("defaults").mediaConfiguration)==null?void 0:u.audio)==null?void 0:h.enableStereo)!=null?m:!1,enableDtx:!1},iceTransportPolicy:a(this,Us)}),e.recv&&L(this,Vl,gv).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,Us)})},nc=new WeakSet,lp=async function(e){const{id:r,serverId:i,direction:n}=e;L(this,Ll,fv).call(this,e);try{return await eS(async(c,d)=>{c>0&&this.logger.debug(`Retrying transport connect, count: ${c}`,{transport:{id:r,serverId:i,type:n}});try{if(e.closed)throw new Lr("Cannot reconnect closed transport");await L(this,Dl,pv).call(this,e)}catch(l){if(l instanceof Lr){d(l);return}throw this.logger.error("Failed to connect transport, retrying",{transport:e,error:l}),l}},{delayTime:100,strategy:"exponential",maxRetryCount:15}),e}catch(o){throw this.logger.error(`Failed to connect send transport after retry: ${e.id}`,{error:o,transport:{id:r,serverId:i,type:n}}),e.close(),e.removeAllListeners(),o}},Dl=new WeakSet,pv=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,en).isConnected)throw new Lr("Socket is not connected");if(e.connectionState==="closed")throw new Lr("Transport is closed");try{await e.connect(n=>L(this,xl,Sv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,_a).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Lr(n.message):n}},Nl=new WeakSet,mv=function(e){var r,i;if(a(this,tt)&&a(this,tt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,tt))==null?void 0:r.id,serverId:(i=a(this,tt))==null?void 0:i.serverId,type:"send"}});return}f(this,tt,a(this,wa).createTransport({...e,direction:"send"})),L(this,ri,Ba).call(this,{state:Ds.NEW,direction:"send",sfuSessionId:a(this,tt).serverId}),this.context.getValue("callstats").configureSendTransport(a(this,tt))},Vl=new WeakSet,gv=function(e){var r,i;if(a(this,st)&&a(this,st).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,st))==null?void 0:r.id,serverId:(i=a(this,st))==null?void 0:i.serverId,type:"recv"}});return}f(this,st,a(this,wa).createTransport({...e,direction:"recv"})),L(this,ri,Ba).call(this,{state:Ds.NEW,direction:"recv",sfuSessionId:a(this,st).serverId}),this.context.getValue("callstats").configureRecvTransport(a(this,st))},Ll=new WeakSet,fv=function(e){const{direction:r,id:i}=e;e.on("serveridchange",n=>{L(this,ri,Ba).call(this,{state:e.connectionState,direction:r,sfuSessionId:n})}),e.on("connectionstatechange",async n=>{L(this,ri,Ba).call(this,{state:n,direction:r,sfuSessionId:e.serverId}),this.logger.info(`Transport connection state changed for ${r} transport`,{transport:{id:i,serverId:e.serverId,type:r,status:n}});const o=()=>{const c=a(this,tn)[r];c!==void 0&&(clearTimeout(c),a(this,tn)[r]=void 0)};switch(n){case"connected":o(),a(this,_a).lastConnectionTime=performance.now();break;case"disconnected":a(this,tn)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,ac,up).call(this,e.direction)},ZD);break;case"failed":if(e.closed)return;o(),this.logger.warn(`${r} transport is in failed state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await L(this,ac,up).call(this,e.direction);break}}),e.on("icecandidate",async n=>{this.logger.debug("Sending iceCandidate:",{iceCandidate:n})}),e.on("datachannel:events",async(n,o)=>{var c,d;this.logger.debug("Got data channel message on event:",{rtcChannel:{label:n,message:o}});try{switch(o.type){case"handshake":{const l={type:"handshake",payload:{message:"pong"}};e.sendResponseOverDC(n,YD(o),l);break}case"hub-disconnect":{this.logger.debug(`media hub disconnected, full_reconnect: ${(c=o.payload)==null?void 0:c.full_reconnect}`),((d=o.payload)==null?void 0:d.full_reconnect)===!0&&this.handleErrors("rejoin");break}case"error":break;default:break}}catch(l){this.logger.error(`Unable to handle the incoming datachannel message on channel ${n}`)}}),e.on("dc_error",()=>{e.direction==="recv"&&(this.logger.warn("Events datachannel did not open in 5s"),this.handleErrors("reconnectRecvTransport"))})},xl=new WeakSet,Sv=async function(e,r){const i=e==="recv";try{const{sdp:n,type:o}=r,c={consuming:i,description:{sdp:n,type:o,target:i?Ks.SUBSCRIBER:Ks.PUBLISHER},producers:[]};return a(this,Pa).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},ac=new WeakSet,up=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,en).isConnected&&a(this,_a).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Us,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,tt)}),this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,st)}),this.context.getValue("peerSessionStore").emit(k.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}const r=e==="send"?a(this,tt):a(this,st);L(this,ri,Ba).call(this,{state:Ds.CONNECTED,direction:e,sfuSessionId:r.serverId})},ri=new WeakSet,Ba=function(e){const{state:r,direction:i,sfuSessionId:n}=e;a(this,ka,hu).mediaState[i]={state:r,sfuSessionId:n},this.context.getValue("peerSessionStore").emit(k.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,ka,hu).mediaState[i]})};class t1{constructor(t,e,r,i,n){g(this,Ul,void 0);g(this,ns,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,Ul,t),f(this,ns,t.getValue("logger"))}async create(t){if(!t||t&&t.length===0)throw new Error("List of producers is required");const e=new Map,r=[];t.forEach(d=>{const{producingPeerId:l,producerId:u,producingTransportId:h}=d,m={simulcast:{preferredRid:"f",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}};e.set(u,l),r.push({producingPeerId:l,producerId:u,producingTransportId:h,...m})});const i=await this.socketHandler.consume({requests:r,consumingTransportId:this.recvTransport.serverId}),n=new Map;t.forEach(d=>n.set(d.producerId,d));const o=new Map,c=[];return Object.entries(i.consumerStateMap).forEach(([d,l])=>{const u=n.get(d);if(!u)return;if(l.errorCode){a(this,ns).warn(`Consumer request failed for producer ${d}`,{error:{message:l.errorCode}}),c.push({...u,errorCode:l.errorCode});return}let h={};try{h=JSON.parse(l.producerState.appData)}catch(m){}o.set(d,{consumerId:l.consumerId,producingTransportId:u.producingTransportId,producingPeerId:u.producingPeerId,kind:u.kind,paused:u.pause,streamId:l.producerTrack.streamId,trackId:l.producerTrack.trackId,screenShare:u.screenShare,mimeType:u.mimeType,appData:h})}),{consumerStates:o,sessionDescription:i.sessionDescription,failedProducers:c}}async negotiate(t){try{a(this,ns).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ns).debug(`[SDP] setting remote offer: ${JSON.stringify(t)} on recvTransport`,{transport:this.recvTransport});const e=await this.recvTransport.setRemoteOffer(t),r={transportId:this.recvTransport.serverId,description:{sdp:e.sdp,type:e.type,target:Ks.SUBSCRIBER}};return a(this,ns).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,Fk.toBinary(r)),a(this,ns).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ns).error("Failed to renegotiate",{error:e});return}}async close(t){if(!t.length)return{};const e=async(r,i)=>{const n=r.map(l=>l.localId);a(this,ns).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:Ks.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=mR.fromBinary(c).description;return{sdp:d.sdp,type:d.type}};return await this.recvTransport.awaitQueue.push(()=>this.recvTransport.closeConsumers(t,e),"ConsumerStrategy.close",{consumersLength:t.length}),{}}async switchConsumersToLayer(t,e){const r={requests:[],consumingTransportId:this.recvTransport.serverId},i=t.filter(n=>n&&n.id);i.forEach(({id:n,producingTransportId:o,localId:c})=>{r.requests.push({producerId:n,producingTransportId:o,mid:c,simulcast:{preferredRid:e===0?"q":"h",priorityOrdering:"asciibetical",ridNotAvailable:"asciibetical"}})}),await this.socketHandler.updateConsumersSimulcastConfig(r),a(this,ns).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Ul=new WeakMap,ns=new WeakMap;class xh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return Pi(t).media.filter(n=>e==="video"?n.type==="video":n.type==="audio").at(-1).msid}async create({offer:t,kind:e,paused:r,appData:i,codecOptions:n,producingTransportId:o}){var h,m;const c=xh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Ks.PUBLISHER},paused:r,kind:e,msid:c,appData:JSON.stringify(i),screenShare:(h=i.screenShare)!=null?h:!1,mimeType:`${e}/${(m=n[0])==null?void 0:m.name}`,producingTransportId:o},{answer:l,producerId:u}=await this.socketHandler.produce(d);return{answer:l,producerId:u}}}function s1(s){try{const t=JSON.parse(s.message);if(typeof t!="object"||t===null)return{};const{errorCode:e,errorDescription:r}=t;return{...typeof e=="string"&&{errorCode:e},...typeof r=="string"&&{errorDescription:r}}}catch(t){return{}}}class r1 extends e1{constructor(e,r){super(e,r);g(this,cc);g(this,Bl);g(this,Fl);g(this,Hl);g(this,ql);g(this,ii,void 0);g(this,ni,void 0);g(this,Ca,void 0);g(this,oc,void 0);g(this,$s,void 0);g(this,$l,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,Sr,[]);g(this,Ra,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,oc,new xh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,Ca).clear(),f(this,$s,new t1(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,ii)}get consumers(){return a(this,ni)}get producerIdToConsumerIdMap(){return a(this,Ca)}get logger(){return this.context.getValue("logger")}reset(){f(this,ii,new Map),f(this,ni,new Map),f(this,Ca,new Map)}async createProducer(e,r){var i,n;if(!this.sendTransport||this.sendTransport.closed)throw new Error("Send transport is closed");try{const o=await this.sendTransport.produce(e,L(this,Bl,vv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,o),L(this,Fl,Tv).call(this,o,r),o}catch(o){throw this.logger.error(`Failed to create ${((n=e==null?void 0:e.track)==null?void 0:n.kind)||"unknown"} producer`,{error:o}),a(this,$l).producerCreationFailureCount+=1,o}}async closeProducer(e,r){var n;const i=this.producers.get(e);if(!i){this.logger.warn(`Producer with ID ${e} was not found`);return}r!=null&&r.stopTrack&&i.track.stop();try{await this.sendTransport.closeProducer(i),(n=this.context.getValue("modules").e2ee)!=null&&n.enabled&&this.context.getValue("peerSessionStore").emit(k.E2EE_INACTIVE_PRODUCER,i)}catch(o){this.logger.error("Failed to close producer on server",{error:o,producer:i})}}closeAllProducers(){return Promise.all(Array.from(a(this,ii).entries()).map(([,e])=>e.close()))}async closeAllProducersLocally(){var r;const e=(r=this.sendTransport)==null?void 0:r.handler;await Promise.all(Array.from(a(this,ii).values()).map(async i=>{try{if(e){const n=e.midTransceiverMap.get(i.localId);n&&(await n.sender.replaceTrack(null),n.direction="inactive")}}catch(n){this.logger.warn("closeAllProducersLocally: failed to deactivate transceiver",{producer:{id:i.id,kind:i.kind,appData:i.appData},error:n})}await i.close(po)}))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Ra)||clearTimeout(a(this,Ra)),f(this,Sr,a(this,Sr).concat(e)),await L(this,cc,hp).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,$s))return;const r=e.map(n=>this.consumers.get(n)).filter(n=>n!==void 0);if(r.length===0)return;const{failedConsumers:i}=await a(this,$s).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,ni).keys()))}async switchConsumersToLayer(e,r){a(this,$s).switchConsumersToLayer(e,r)}}ii=new WeakMap,ni=new WeakMap,Ca=new WeakMap,oc=new WeakMap,$s=new WeakMap,$l=new WeakMap,Sr=new WeakMap,Ra=new WeakMap,cc=new WeakSet,hp=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,Sr).splice(0,a(this,Sr).length);try{const i=new Set(Array.from(this.consumers.values()).map(({producerId:d})=>d)),n=r.filter(({producerId:d})=>!this.producers.get(d)&&!i.has(d));if(n.length===0)return;const{consumers:o,failedProducers:c}=await this.recvTransport.consume(n,L(this,Hl,yv).bind(this),a(this,$s).negotiate.bind(a(this,$s)));if(o.forEach(L(this,ql,Ev).bind(this)),c!=null&&c.length){this.logger.error("Failed to create consumers for producers",{producers:c});const d=c.filter(({errorCode:l,producerId:u})=>l==="not_found_track_error"?(this.logger.error(`Track not found for producer: ${u}. This will not be retried.`),!1):l==="backend_error"?(this.logger.error("Unrecoverable error: backend error"),!1):!0);f(this,Sr,a(this,Sr).concat(d)),f(this,Ra,setTimeout(L(this,cc,hp).bind(this),e))}}catch(i){const n=i instanceof Error?i:new Error(String(i));this.logger.error("failed to consume on transport",{error:n});const{errorCode:o,errorDescription:c}=s1(n);if(o==="internal_error"&&c==="Backend error"||o==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:o,message:c}});try{this.stopTransports({recv:!0})}catch(d){}await this.setupTransports({recv:!0})}}},Bl=new WeakSet,vv=function(e){return a(this,oc).create(e)},Fl=new WeakSet,Tv=function(e,r){e.on("close",async(i,n)=>{const{offer:o,reason:c}=i;if(this.logger.info("producer::closing",{debuggingHint:c,producer:{...e,status:"closing"}}),c!==po){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Ks.PUBLISHER}};try{const l=await this.socketHandler.closeProducer(d),u={sdp:l==null?void 0:l.sdp,type:l==null?void 0:l.type};this.logger.info("producer::closed",{producer:{...e,status:"closed"}}),n({answer:u})}catch(l){this.logger.error("producer close error",l)}}this.producers.delete(e.id),r()}),e.on("trackended",()=>{this.logger.info("producer::trackended",{producer:{...e,status:"UNKNOWN"}})}),a(this,ii).set(e.id,e)},Hl=new WeakSet,yv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,$s).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},ql=new WeakSet,Ev=function(e){e.on("close",async r=>{this.logger.debug("consumer closed",{consumer:{closureReason:r,id:e.id,kind:e.kind,appData:e.appData}}),a(this,ni).delete(e.id),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:e.id})}),a(this,ni).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(k.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};const Kl=class{constructor({initialEnergyThreshold:t=.015,zeroCrossingThreshold:e=20,minVoiceDuration:r=3,hangoverFrames:i=5,noiseAdaptationRate:n=.95,voiceAdaptationRate:o=.99,minEnergyThreshold:c=.005,maxEnergyThreshold:d=.2,energyRatioThreshold:l=1.5,noiseHistorySize:u=50}={}){g(this,jl);g(this,Gl);g(this,dc,void 0);g(this,lc,void 0);g(this,uc,void 0);g(this,Ia,void 0);g(this,Aa,void 0);g(this,Ma,void 0);g(this,hc,void 0);g(this,pc,void 0);g(this,Oa,void 0);g(this,Rt,void 0);g(this,Es,void 0);g(this,bs,!1);g(this,sn,0);g(this,rn,0);g(this,vr,[]);g(this,mc,void 0);f(this,Ia,t),f(this,Rt,t),f(this,dc,e),f(this,lc,r),f(this,uc,i),f(this,Aa,n),f(this,Ma,o),f(this,hc,c),f(this,pc,d),f(this,Oa,l),f(this,mc,u),f(this,Es,t/2)}get voiceDetected(){return a(this,bs)}processAudioChunk(t){var o,c;const e=L(o=Kl,Wl,Pv).call(o,t),r=L(c=Kl,Jl,_v).call(c,t);return L(this,jl,bv).call(this,e),e/a(this,Es)>a(this,Oa)&&e>a(this,Rt)&&r>a(this,dc)?(f(this,sn,a(this,sn)+1),f(this,rn,a(this,uc)),a(this,sn)>=a(this,lc)&&f(this,bs,!0)):(f(this,sn,0),a(this,rn)>0?f(this,rn,a(this,rn)-1):a(this,bs)&&f(this,bs,!1),a(this,bs)||L(this,Gl,wv).call(this,e)),{energy:e,isVoice:a(this,bs)}}reset(){f(this,bs,!1),f(this,sn,0),f(this,rn,0),f(this,Rt,a(this,Ia)),f(this,Es,a(this,Ia)/2),f(this,vr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Rt),backgroundNoiseEnergy:a(this,Es),energyRatioThreshold:a(this,Oa)}}};let mo=Kl;dc=new WeakMap,lc=new WeakMap,uc=new WeakMap,Ia=new WeakMap,Aa=new WeakMap,Ma=new WeakMap,hc=new WeakMap,pc=new WeakMap,Oa=new WeakMap,Rt=new WeakMap,Es=new WeakMap,bs=new WeakMap,sn=new WeakMap,rn=new WeakMap,vr=new WeakMap,mc=new WeakMap,jl=new WeakSet,bv=function(t){a(this,bs)?f(this,Rt,a(this,Ma)*a(this,Rt)+(1-a(this,Ma))*t):f(this,Rt,a(this,Aa)*a(this,Rt)+(1-a(this,Aa))*a(this,Es)),f(this,Rt,Math.max(a(this,hc),Math.min(a(this,pc),a(this,Rt))))},Gl=new WeakSet,wv=function(t){if(t<a(this,Rt)*1.2)if(a(this,vr).push(t),a(this,vr).length>a(this,mc)&&a(this,vr).shift(),a(this,vr).length>=10){const e=[...a(this,vr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Es,e[r])}else f(this,Es,.95*a(this,Es)+.05*t)},Wl=new WeakSet,Pv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Jl=new WeakSet,_v=function(t){let e=0;for(let r=1;r<t.length;r+=1)(t[r]>=0&&t[r-1]<0||t[r]<0&&t[r-1]>=0)&&(e+=1);return e},g(mo,Wl),g(mo,Jl);class nS{constructor(t){p(this,"RNAudioSampleHandler");g(this,gc,void 0);f(this,gc,t);const{RNAudioSampleHandlerImpl:e}=navigator;e==null||e.init().then(r=>{this.RNAudioSampleHandler=r}).catch(r=>{this.logger.error("ReactNativeAudioSampler: Failed to initialize audio sampler",r)})}get logger(){return a(this,gc).getValue("logger")}get samples(){var e;const t=new Float32Array(1024);return(e=this.RNAudioSampleHandler)==null||e.getFloatTimeDomainData(t),t}stop(){var t;(t=this.RNAudioSampleHandler)==null||t.destructor()}}gc=new WeakMap;class aS{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,fc,void 0);f(this,fc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,fc).getValue("logger")}get samples(){if(this.audioContext.state==="suspended")try{this.audioContext.resume()}catch(e){this.logger.error("AudioContextSampler: Failed to resume audio context",e)}const t=new Float32Array(this.analyser.frequencyBinCount);return this.analyser.getFloatTimeDomainData(t),t}set audioTrack(t){const e=new MediaStream;e.addTrack(t),this.audioContext.createMediaStreamSource(e).connect(this.analyser)}}fc=new WeakMap;class i1{static setInterval(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setInterval(t,e,...r):global.setInterval(t,e,...r)}static clearInterval(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearInterval(t):global.clearInterval(t)}static setTimeout(t,e=0,...r){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.setTimeout(t,e,...r):global.setTimeout(t,e,...r)}static clearTimeout(t){return navigator&&navigator.RNBackgroundTimerImpl?navigator.RNBackgroundTimerImpl.clearTimeout(t):global.clearTimeout(t)}}const n1=60,a1=400,Tc=class{constructor(t,e){g(this,zl);g(this,Yl);g(this,Tr,void 0);g(this,yr,void 0);g(this,Er,void 0);g(this,Sc,void 0);g(this,Da,void 0);g(this,Na,void 0);g(this,ai,void 0);g(this,nn,void 0);g(this,Va,void 0);g(this,an,void 0);g(this,br,void 0);g(this,Bs,void 0);this.reportRequest=e,f(this,an,t),f(this,Na,new mo);const{isReactNative:r}=navigator;f(this,br,r?new nS(a(this,an)):new aS(a(this,an))),f(this,Bs,r?i1:Ff)}get logger(){return a(this,an).getValue("logger")}set producerId(t){f(this,Er,t)}set audioTrack(t){f(this,Sc,t),a(this,br)instanceof aS&&(a(this,br).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Er)}`),a(this,Tr)&&a(this,Bs).clearInterval(a(this,Tr)),f(this,Tr,a(this,Bs).setInterval(async()=>{var i;if(!a(this,Sc)||!a(this,Er))return;const{energy:t}=L(this,zl,kv).call(this),e=L(i=Tc,vc,pp).call(i,t);let r=.9;a(this,Va)!==e&&a(this,Va)?r=.9:e?r=.3:r=.5,f(this,Da,(a(this,Da)||0)*(1-r)+t*r)},n1)),a(this,yr)&&a(this,Bs).clearInterval(a(this,yr)),f(this,yr,a(this,Bs).setInterval(L(this,Yl,Cv).bind(this),a1))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Er)}`),a(this,Tr)&&(a(this,Bs).clearInterval(a(this,Tr)),f(this,Tr,void 0)),a(this,yr)&&(a(this,Bs).clearInterval(a(this,yr)),f(this,yr,void 0))}catch(t){}a(this,Na).reset(),a(this,br)instanceof nS&&a(this,br).stop()}};let go=Tc;Tr=new WeakMap,yr=new WeakMap,Er=new WeakMap,Sc=new WeakMap,Da=new WeakMap,Na=new WeakMap,ai=new WeakMap,nn=new WeakMap,Va=new WeakMap,an=new WeakMap,br=new WeakMap,Bs=new WeakMap,zl=new WeakSet,kv=function(){var o;const{samples:t}=a(this,br),{energy:e,isVoice:r}=a(this,Na).processAudioChunk(t),i=L(o=Tc,Ql,Rv).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,ai)||i<a(this,ai))&&f(this,ai,i),(!a(this,nn)||i>a(this,nn))&&f(this,nn,i),{energy:(i-a(this,ai))/(a(this,nn)-a(this,ai))*10||0,isVoice:r})},vc=new WeakSet,pp=function(t){return t<5},Yl=new WeakSet,Cv=function(t=a(this,Da)){var r;if(!a(this,Er)||!t)return;const e={producerId:a(this,Er),energy:Math.round(t),silent:L(r=Tc,vc,pp).call(r,t)};f(this,Va,e.silent),this.reportRequest(e)},Ql=new WeakSet,Rv=function(t){const e=Math.log10(t);return Math.round(e)},g(go,vc),g(go,Ql);var o1=Object.defineProperty,c1=Object.getOwnPropertyDescriptor,de=(s,t,e,r)=>{for(var i=r>1?void 0:r?c1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&o1(t,e,i),i};class ae{constructor(t,e){g(this,wr);g(this,Zl);g(this,eu);g(this,tu);g(this,wc);g(this,su);g(this,ru);g(this,wt);g(this,ln);g(this,iu);g(this,nu);g(this,au);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,yc,void 0);g(this,Ec,void 0);g(this,pt,void 0);g(this,q,void 0);g(this,Xl,void 0);g(this,bt,void 0);g(this,on,void 0);g(this,cn,void 0);g(this,dn,void 0);g(this,bc,void 0);g(this,Ht,null);g(this,Fs,void 0);g(this,mt,void 0);g(this,It,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,pt,r),f(this,on,!1),f(this,q,new r1(t,r)),f(this,bt,a(this,q).events),f(this,Fs,new Set),f(this,mt,new Map),f(this,cn,!1),f(this,dn,new Ah(t.getValue("logger"))),f(this,It,new go(this.context,a(this,q).socketHandler.audioActivity.bind(a(this,q).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,bc,Uu(async()=>{if(!a(this,wr,Sn).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Ec),a(this,yc),!0);o&&(this.context.getValue("peerSessionStore").emit(k.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_RECONNECTED))},5e3,{leading:!0,maxWait:1e3}))}get peerId(){return this.context.getValue("peerId")}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get mediaJoined(){return a(this,wr,Sn).mediaJoined}set mediaJoined(t){a(this,wr,Sn).mediaJoined=t}reset({resetTransportQueue:t}){this.logger.info(`Resetting media node client: closing all transports, producers, consumers, and queues(resetTransportQueue: ${t}).`),a(this,q).closeAllProducers(),a(this,q).closeAllConsumers(),a(this,mt).clear(),a(this,Fs).clear(),f(this,Ht,null),t&&a(this,dn).stop(),a(this,q).stopAllTransports(),a(this,q).reset(),t&&f(this,dn,new Ah)}async joinRoom(t,e,r=!1,i={}){a(this,wr,Sn).mediaJoinAttempted=!0,f(this,on,!0);try{return await a(this,dn).push(()=>L(this,Zl,Iv).call(this,t,e,r,i),"joinRoom")}catch(n){return this.logger.error("Error in room joining process",{error:n}),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_FAILED),{roomJoined:!1,error:n}}}async initializeConnection(t,e,r=!1,i={}){return a(this,Ht)?a(this,Ht):(f(this,Ht,(async()=>{try{await L(this,wc,mp).call(this,t,e,r,i)}catch(n){throw f(this,Ht,null),n}})()),a(this,Ht))}getConsumers(){return a(this,q).consumers}getProducers(){return a(this,q).producers}async leaveRoom(){a(this,q).stopAllTransports(),f(this,cn,!1),a(this,wr,Sn).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,pt).sendMessagePromise(a(this,bt).leaveRoom,hC.toBinary(t)).then(r=>{var i;(i=eR.fromBinary(r.payload))!=null&&i.closed&&this.logger.warn("Weird state on peer closed and should not happen")}).catch(r=>{this.logger.error("error on sending leave room request",{error:r})}),this.context.getValue("callstats").callEnded(),this.context.getValue("telemetry").destruct().catch(r=>{this.logger.error("leaveRoom::telemetry_destruct_failed",{error:r})})}async activatePeers(t){return this.createConsumers(t)}async createConsumers(t){return t.length===0?Promise.resolve():a(this,q).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,q).producerIdToConsumerIdMap.get(i.producerId);return n?(r.push(n),r):(this.logger.warn(`consumer not found in close consumers: ${i.producerId}`),r)},[]);await a(this,q).closeConsumers(e)}async _shareWebcam(t){var u,h,m,S;const e=Ae.WEBCAM,r=L(this,wt,Wt).call(this,e);if(r){const y=await r;if(a(this,q).producers.has(y)){const w=a(this,q).producers.get(y);if(!w.closed)return await w.replaceTrack({track:t}),await this.resumeWebcam(e),t;await this.disableWebcam()}return this._shareWebcam(t)}const i=L(this,au,Lv).call(this,t),n=Pn(this.context,"disableSimulcast"),o=(h=(u=this.context)==null?void 0:u.getValue("overrides"))==null?void 0:h.simulcastConfig;n||o&&o.disable||!((S=(m=this.context)==null?void 0:m.getValue("theme"))!=null&&S.isSimulcastEnabled)?this.logger.info("Simulcast disabled for webcam producer, SFU: CF"):(this.logger.info("Simulcast enabled for SFU: CF"),i.encodings=FO(this.context,t),this.logger.info(`Simulcast encodings: ${JSON.stringify(i.encodings)}`));const d=()=>{this.logger.info("Disabling video due to the producer closure"),a(this,mt).delete(e)},l=a(this,q).createProducer(i,d);return L(this,ln,Yc).call(this,e,l.then(y=>y.id)),l.then(y=>y.track)}async shareWebcam(t){return t===void 0?null:(this.logger.debug("Calling _shareWebcam with VP8 codec"),this._shareWebcam(t))}async shareScreen(t){const{video:e,audio:r}=t;if(e===void 0)return;const i={track:e,codecOptions:[{name:"VP8"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,mt).delete(Ae.SCREENSHARE_VIDEO),a(this,mt).delete(Ae.SCREENSHARE_AUDIO)},o=a(this,q).createProducer(i,n);L(this,ln,Yc).call(this,Ae.SCREENSHARE_VIDEO,o.then(d=>d.id));let c;if(r){const d={track:r,codecOptions:[{name:"opus"}],appData:{screenShare:!0,e2ee:this.e2ee,supportsRemoteControl:Te.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,q).createProducer(d,l),L(this,ln,Yc).call(this,Ae.SCREENSHARE_AUDIO,c.then(u=>u.id))}await Promise.all([o,c||Promise.resolve()]),this.context.getValue("callstats").screenShareStart()}async shareMic(t){try{if(t===void 0)throw new kt("track undefined");const e=L(this,wt,Wt).call(this,Ae.MIC);if(e){const o=await e;if(a(this,q).producers.has(o)){const c=a(this,q).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,It)&&(a(this,It).audioTrack=t,a(this,It).producerId=o,a(this,It).start());return}await a(this,q).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=L(this,nu,Vv).call(this,t),i=()=>{a(this,mt).delete(Ae.MIC)},n=a(this,q).createProducer(r,i);L(this,ln,Yc).call(this,Ae.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,It)&&(a(this,It).audioTrack=o.track,a(this,It).producerId=o.id,a(this,It).start())})}catch(e){throw new R(e)}}async pauseMic(){var i;const t=await L(this,wt,Wt).call(this,Ae.MIC),e=a(this,q).producers.get(t);if(!e){this.logger.error("pauseMic::could_not_find_mic_producer");return}if(e.paused){this.logger.info("pauseMic::mic_producer_already_paused");return}e.pause(),(i=a(this,It))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,pt).sendMessage(a(this,bt).toggleProducer,Ad.toBinary(r))}async pauseWebcam(){const t=await L(this,wt,Wt).call(this,Ae.WEBCAM),e=a(this,q).producers.get(t);if(!e){this.logger.error("pauseWebcam::could_not_find_webcam_producer");return}e.pause();const r={producerId:e.id,pause:!0};a(this,pt).sendMessage(a(this,bt).toggleProducer,Ad.toBinary(r))}async resumeMic(){const t=await L(this,wt,Wt).call(this,Ae.MIC),e=a(this,q).producers.get(t);if(!e){this.logger.error("resumeMic::could_not_find_mic_producer");return}if(!e.pause){this.logger.info("resumeMic::mic_producer_already_resumed");return}e.resume(),e.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,pt).sendMessage(a(this,bt).toggleProducer,Ad.toBinary(r))}async resumeWebcam(t=Ae.WEBCAM){const e=await L(this,wt,Wt).call(this,t),r=a(this,q).producers.get(e);if(!r){this.logger.error("resumeWebcam::could_not_find_webcam_producer");return}if(!r.paused){this.logger.info("resumeWebcam::webcam_producer_already_resumed");return}r.resume(),r.appData.e2ee&&this.context.getValue("peerSessionStore").emit(k.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,pt).sendMessage(a(this,bt).toggleProducer,Ad.toBinary(i))}async disableWebcam(){const t=Ae.WEBCAM,e=await L(this,wt,Wt).call(this,t);L(this,iu,Nv).call(this,t),e&&await a(this,q).closeProducer(e)}async disableMic(){var e;const t=await L(this,wt,Wt).call(this,Ae.MIC);t&&await a(this,q).closeProducer(t),(e=a(this,It))==null||e.stop(),a(this,mt).delete(Ae.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await L(this,wt,Wt).call(this,Ae.SCREENSHARE_VIDEO),e=await L(this,wt,Wt).call(this,Ae.SCREENSHARE_AUDIO);t&&await a(this,q).closeProducer(t),e&&await a(this,q).closeProducer(e),a(this,Fs).clear(),a(this,mt).delete(Ae.SCREENSHARE_VIDEO),a(this,mt).delete(Ae.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await L(this,wt,Wt).call(this,Ae.WEBCAM);await a(this,q).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await L(this,wt,Wt).call(this,Ae.SCREENSHARE_VIDEO);await a(this,q).closeProducer(r,{stopTrack:!1}),this.shareScreen({video:e})}}async changeDisplayName(t,e){const r={displayName:t,participantId:e!=null?e:this.peerId};if(!await a(this,q).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,q).socketHandler.kickPeer(e)}kickAll(){a(this,q).socketHandler.kickAll()}async muteAll(t){if(!await a(this,q).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,q).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,q).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,q).socketHandler.hostControlForPeer(t,"video"))throw new Error("failed to mute video of given participant")}async pinPeer(t){const e={participantId:t!=null?t:""};try{await a(this,pt).sendMessagePromise(a(this,bt).globalPinPeer,kC.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,q).producers.get(t.producerId)&&a(this,Fs).add(t.consumerPeerId),a(this,Fs).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,q).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,pt).on(a(this,bt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=AR.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===zs.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(k.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===zs.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,pt).on(a(this,bt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=Yg.fromBinary(t);if(c)return;const d=i===zs.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(Yg.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?k.MUTE_SELF:k.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(k.PRODUCER_TOGGLE,{peerId:e,producerId:o,paused:n,kind:d}),Array.from(this.getConsumers().values()).filter(u=>u.producerId===o).forEach(u=>{u.kind==="video"&&n||u.paused!==n&&(this.logger.debug(`consumer state mismatched for ${u.id}. updating consumer pause state ${u.paused} to ${n}`),n?(u.pause(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(k.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,pt).on(a(this,bt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Xu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Fs).delete(e),a(this,q).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(k.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,pt).on(a(this,bt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=DR.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(k.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,q).producerIdToConsumerIdMap.get(r);if(!i){this.logger.warn(`no consumer found for producer:${r}`);return}this.logger.info(`closing consumer ${i}, producer id: ${r}`),a(this,q).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,q).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(k.CONSUMER_CLOSED,{id:i})}).catch(n=>{this.logger.error("error closing consumer",{error:n})})}catch(e){this.logger.error("error on producer close broadcast",{error:e})}}),a(this,pt).on(a(this,bt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,on)&&!a(this,cn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(k.ROOM_NODE_DISCONNECTED),a(this,bc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,q).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(k.CONSUMER_SCORE_UPDATE,{id:r,kind:i.kind,peerId:i.peerId,score:e.score,scoreStats:e})})}),this.context.getValue("callstats").onProducerScore(t=>{t.forEach((e,r)=>{const i=Array.from(a(this,q).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(k.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}yc=new WeakMap,Ec=new WeakMap,pt=new WeakMap,q=new WeakMap,Xl=new WeakMap,bt=new WeakMap,on=new WeakMap,cn=new WeakMap,dn=new WeakMap,bc=new WeakMap,Ht=new WeakMap,Fs=new WeakMap,mt=new WeakMap,It=new WeakMap,wr=new WeakSet,Sn=function(){return this.context.getValue("connectionHandler")},Zl=new WeakSet,Iv=async function(t,e,r,i){var o;f(this,Ec,t);let n=!1;if(r){const{recv:c,send:d}=(o=a(this,wr,Sn).mediaState)!=null?o:{};(d==null?void 0:d.state)===Ds.CONNECTED&&(c==null?void 0:c.state)===Ds.CONNECTED?(this.logger.info("MediaNodeClient.joinRoom: transports healthy — partial reset (producers only)"),await a(this,q).closeAllProducersLocally(),a(this,mt).clear(),a(this,Fs).clear(),f(this,Ht,null),n=!0):(this.logger.info("MediaNodeClient.joinRoom: transports unhealthy — full reset"),this.reset({resetTransportQueue:!1}))}try{a(this,Ht)?await a(this,Ht):await L(this,wc,mp).call(this,t,e,r,i,n),L(this,tu,Mv).call(this,e);const{joined:c,error:d}=await L(this,eu,Av).call(this);return{roomJoined:c,error:d}}catch(c){return this.logger.error("Failed to complete room join",{error:c}),{roomJoined:!1,error:c}}finally{f(this,Ht,null)}},eu=new WeakSet,Av=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,q).socketHandler.notifySelfJoinComplete();return f(this,yc,t.roomUuid),f(this,cn,!0),f(this,on,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},tu=new WeakSet,Mv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...Te.getDeviceInfo(),userAgent:navigator.userAgent,memory:navigator.deviceMemory,cpus:navigator.hardwareConcurrency},sdkName:this.context.getValue("sdkName"),sdkVersion:this.context.getValue("sdkVersion"),metaData:{},permissions:{}};this.context.getValue("callstats").roomJoined(r)}catch(e){this.logger.error("Error reporting room joined analytics",{error:e})}},0)},wc=new WeakSet,mp=async function(t,e,r,i,n=!1){try{const o=L(this,su,Ov).call(this);await L(this,ru,Dv).call(this,t,e,r,o),n?this.logger.info("MediaNodeClient: reusing existing transports on rejoin"):await a(this,q).setupTransports({send:!0,recv:!0})}catch(o){throw this.logger.error("Failed to initialize connection",{error:o}),o}},su=new WeakSet,Ov=function(){const t=xD("video/VP8");return f(this,Xl,t),t},ru=new WeakSet,Dv=async function(t,e,r,i){await eS(async(n,o)=>{if(!a(this,pt).isConnected){o(new Error("Socket is not connected"));return}n>0&&this.logger.warn("Retry: send joinRoom message",{debuggingHint:`Retry attempt ${n}`});try{await a(this,q).socketHandler.joinRoom(e,t,i,r)}catch(c){throw this.logger.error("Failed to send joinRoom message after retries",{error:c}),c}},{delayTime:1e3,strategy:"exponential",maxRetryCount:15})},wt=new WeakSet,Wt=function(t){return a(this,mt).get(t)},ln=new WeakSet,Yc=function(t,e){return a(this,mt).set(t,e)},iu=new WeakSet,Nv=function(t){return a(this,mt).delete(t)},nu=new WeakSet,Vv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},au=new WeakSet,Lv=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},de([E.trace("MediaNodeClient.reset")],ae.prototype,"reset",1),de([E.trace("MediaNodeClient.joinRoom")],ae.prototype,"joinRoom",1),de([E.trace("MediaNodeClient.leaveRoom")],ae.prototype,"leaveRoom",1),de([E.trace("MediaNodeClient.activatePeers")],ae.prototype,"activatePeers",1),de([E.trace("MediaNodeClient.createConsumers")],ae.prototype,"createConsumers",1),de([E.trace("MediaNodeClient.closeConsumers")],ae.prototype,"closeConsumers",1),de([E.trace("MediaNodeClient._shareWebcam")],ae.prototype,"_shareWebcam",1),de([E.trace("MediaNodeClient.shareWebcam")],ae.prototype,"shareWebcam",1),de([E.trace("MediaNodeClient.shareScreen")],ae.prototype,"shareScreen",1),de([E.trace("MediaNodeClient.shareMic")],ae.prototype,"shareMic",1),de([E.trace("MediaNodeClient.pauseMic")],ae.prototype,"pauseMic",1),de([E.trace("MediaNodeClient.pauseWebcam")],ae.prototype,"pauseWebcam",1),de([E.trace("MediaNodeClient.resumeMic")],ae.prototype,"resumeMic",1),de([E.trace("MediaNodeClient.resumeWebcam")],ae.prototype,"resumeWebcam",1),de([E.trace("MediaNodeClient.disableWebcam")],ae.prototype,"disableWebcam",1),de([E.trace("MediaNodeClient.disableMic")],ae.prototype,"disableMic",1),de([E.trace("MediaNodeClient.disableScreenShare")],ae.prototype,"disableScreenShare",1),de([E.trace("MediaNodeClient.muteSelf")],ae.prototype,"muteSelf",1),de([E.trace("MediaNodeClient.resetVideoProducers")],ae.prototype,"resetVideoProducers",1),de([E.trace("MediaNodeClient.changeDisplayName")],ae.prototype,"changeDisplayName",1),de([E.trace("MediaNodeClient.kickPeer")],ae.prototype,"kick",1),de([E.trace("MediaNodeClient.kickAllPeers")],ae.prototype,"kickAll",1),de([E.trace("MediaNodeClient.muteAll")],ae.prototype,"muteAll",1),de([E.trace("MediaNodeClient.muteAllVideo")],ae.prototype,"muteAllVideo",1),de([E.trace("MediaNodeClient.disableAudio")],ae.prototype,"disableAudio",1),de([E.trace("MediaNodeClient.disableVideo")],ae.prototype,"disableVideo",1),de([E.trace("MediaNodeClient.pinPeer")],ae.prototype,"pinPeer",1),de([E.trace("MediaNodeClient.validateScreenShare")],ae.prototype,"validateScreenShare",1);function oS(s,t){const e=s.getValue("roomNodeClient");if(e){if(e)return e;throw new Error("Room node client already set up.")}const r=new ae(s,t);return s.setValue("roomNodeClient",r),r}function d1(s){const t=s.getValue("roomNodeClient");try{t==null||t.leaveRoom()}catch(e){s.getValue("logger").error("roomNodeClient::cleanupRoomNodeClient")}s.setValue("roomNodeClient",void 0)}var l1=Object.defineProperty,u1=Object.getOwnPropertyDescriptor,ki=(s,t,e,r)=>{for(var i=r>1?void 0:r?u1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&l1(t,e,i),i};const cS=(QS=class{constructor(s,t,e,r){g(this,At);p(this,"self");p(this,"authToken");g(this,La,void 0);p(this,"viewType");g(this,ws,void 0);g(this,ee,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,ee,s),this.viewType=r,this.authToken=n,f(this,La,i),f(this,ws,e),this.setupEvents()}get peerId(){return a(this,ee).getValue("peerId")}get telemetry(){return a(this,ee).getValue("telemetry")}get logger(){return a(this,ee).getValue("logger")}get mediaJoined(){return a(this,ee).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=Pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await Ke.__init__(s,e,r,i,i.name,c);s.setValue("self",d);const l=s.getValue("logger");return navigator.product!=="ReactNative"?setTimeout(async()=>{const h=await d.getAllDevices();l.info("populated_full_device_list",{devices:JSON.stringify(h)}),s.getValue("callstats").devices("AUDIO",h==null?void 0:h.filter(m=>m.kind==="audioinput")),s.getValue("callstats").devices("VIDEO",h==null?void 0:h.filter(m=>m.kind==="videoinput")),s.getValue("callstats").devices("SPEAKER",h==null?void 0:h.filter(m=>m.kind==="audiooutput")),l.info("Callstats:: initializing");try{await s.getValue("callstats").initialize({peerId:o,engineName:Te.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:M_(s),skipConnectivityChecks:!0,authToken:s.getValue("authToken")}),l.info("Callstats:: initialized")}catch(m){l.error("Callstats:: initialization failed",{error:m})}},0):l.info("Callstats:: Skipped initialization due to navigator product being ReactNative."),new cS(s,d,t,i.viewType)}async shareMediaTracks(){var c;const{audioTrack:s,videoTrack:t,permissions:e,audioEnabled:r,videoEnabled:i,screenShareEnabled:n,screenShareTracks:o}=this.self;if(e.canProduceAudio===G.Allowed&&r)if((s==null?void 0:s.readyState)==="live")try{await a(this,At,os).shareMic(s),this.self.audioEnabled||a(this,At,os).pauseMic()}catch(d){this.self.disableAudio()}else this.logger.warn("shareMediaTracks: audio track is dead, disabling audio"),this.self.disableAudio();if(e.canProduceVideo===G.Allowed&&i)if((t==null?void 0:t.readyState)==="live")try{await a(this,At,os).shareWebcam(t),this.self.videoEnabled||a(this,At,os).pauseWebcam()}catch(d){this.self.disableVideo()}else this.logger.warn("shareMediaTracks: video track is dead, disabling video"),this.self.disableVideo();if(e.canProduceScreenshare===G.Allowed&&n){const d=o.video,l=o.audio;if((d==null?void 0:d.readyState)==="live")try{await((c=a(this,At,os))==null?void 0:c.shareScreen({video:d,audio:(l==null?void 0:l.readyState)==="live"?l:void 0}))}catch(u){this.self.disableScreenShare()}else this.logger.warn("shareMediaTracks: screenshare video track is dead, disabling screenshare"),this.self.disableScreenShare()}}async kickHandler(s){let t="kicked";(s==null?void 0:s.kickType)==="kickAll"&&(t="ended"),this.leaveRoom(t)}waitlistedHandler(){this.logger.info("SelController.waitlisted"),this.self.waitlistStatus="waiting",this.self.roomState="waitlisted",this.self.emit("waitlisted")}waitlistAcceptHandler(){if(this.logger.info("SelController.waitlistAccepted"),this.self.waitlistStatus==="accepted"){this.logger.warn("SelfController.WAITLIST_ACCEPTED.UserAlreadyAccepted");return}this.self.waitlistStatus="accepted",this.joinRoom()}waitlistRejectedHandler(){if(this.logger.info("SelfController.waitlistRejected"),this.self.waitlistStatus==="rejected"){this.logger.warn("SelfController.WAITLIST_REJECTED.UserAlreadyRejected");return}this.self.waitlistStatus="rejected",this.leaveRoom("rejected")}async resetSelf(s){a(this,ee).getValue("callstats").callEnded(),s?(this.logger.info("Resetting Self post reconnect. Peer has earlier tried joining the meeting. State cleanup will be done during room rejoin."),await this.joinRoom(s)):(this.logger.info("Resetting Self post reconnect. User never joined the room so doing full reset."),a(this,At,os).reset({resetTransportQueue:!0}))}setupEvents(){a(this,ee).getValue("peerSessionStore").on(k.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,ee).getValue("peerSessionStore").on(k.ROOM_NODE_FAILED,()=>{this.logger.error("Room node failed. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,La).updateURL(t),a(this,ee).getValue("telemetry").resetPeerId(t),Pt().setHeader("tracing-id",t),Rr.remapContext(t,a(this,ee)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,ee).getValue("peerSessionStore").on(k.SOCKET_SERVICE_FAILED,()=>{this.logger.error("Socket reconnection failed after exhausting all attempts. SDK re-initialization is required."),this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ws).on(U.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ws).on(Ld.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,ee).getValue("peerSessionStore").emit(k.UPDATE_PERMISSIONS,t.patch)})}),a(this,ws).on(U.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ws).on(U.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ws).on(U.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,ee).getValue("peerSessionStore").onAsync(k.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(k.PRODUCER_SCORE_UPDATE,({score:s,kind:t,appData:e,scoreStats:r})=>{var n;const i=(n=e==null?void 0:e.screenShare)!=null?n:!1;this.self.emit("mediaScoreUpdate",{kind:t,isScreenshare:i,score:s,participantId:this.self.id,scoreStats:r})}),a(this,ee).getValue("peerSessionStore").on(k.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,ee).getValue("callstats").audioOff())}),a(this,ee).getValue("peerSessionStore").on(k.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,ee).getValue("callstats").videoOff())}),a(this,ee).getValue("peerSessionStore").onAsync(k.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,ee).getValue("peerSessionStore").on(k.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{this.logger.info("Joining socket room.");const{peer:t}=await a(this,ws).joinRoom(this.self);this.logger.info("Joined socket room."),a(this,ws).socket.flush();const e=fh(t.stageType);if(a(this,ee).setValue("stageStatus",e,!1),t.waitlisted){this.logger.info("Peer was waitlisted. Skipped joining media room."),this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new R("Check the network and try again.","0002")}try{this.logger.info("Joining media room."),await this.joinMediaRoom(s),this.logger.info("Joined media room."),a(this,ee).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Lr&&t.message==="ice connection failed"?new R("A firewall or network restriction may be blocking the connection.","0014"):new R("Check the network and try again.","0014")}}async leaveRoom(s="left"){var t;if(this.logger.info(`Leaving room with state: ${s}`),s==="rejected"){this.self.roomState=s,this.self.emit("roomLeft",{state:s});return}this.self.setIsPinned(!1),a(this,ee).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,ee).setValue("roomNodeClient",void 0),a(this,ee).notify("stageStatus"),(t=a(this,ee).getValue("roomSocketHandler"))==null||t.cleanup(),this.self.roomState=s,this.self.emit("roomLeft",{state:s}),this.logger.info(`roomLeft event emitted with state: ${s}`)}async joinMediaRoom(s=!1){var n,o;const{peerId:t,viewType:e,meetingId:r,stageStatus:i}=a(this,ee).getAllValues();try{if(e===Ws.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}oS(a(this,ee),{socket:a(this,La),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,At,os))==null?void 0:n.joinRoom(this.self.name,r,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");this.logger.info(i==="ON_STAGE"?"Peer is on stage. Sharing media tracks":"Peer is not on stage. Not sharing media tracks"),i==="ON_STAGE"&&await this.shareMediaTracks(),this.logger.info(i==="ON_STAGE"?"Peer is on stage. Shared media tracks":"Peer is not on stage. Did not share media tracks"),this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s})}catch(c){throw this.logger.error("SelfController.mediaRoomJoin",{error:c}),c}}async leaveMediaRoom(s){const t=a(this,ee).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Ws.Webinar)&&a(this,At,os)&&(a(this,At,os).mediaJoined&&s!=="disconnected"&&await a(this,At,os).leaveRoom(),!(s==="stageLeft"&&t===Ws.Livestream)&&(a(this,At,os).mediaJoined=!1))}async cleanupSelf(){await this.self.disableAudio(),await this.self.disableVideo(),await this.self.disableScreenShare(),this.self.cleanUpTracks(),this.self.destructMediaHandler(),navigator.isReactNative||this.self.removeDocumentEventListeners()}},La=new WeakMap,ws=new WeakMap,ee=new WeakMap,At=new WeakSet,os=function(){return a(this,ee).getValue("roomNodeClient")},QS);let xr=cS;ki([E.trace("SelfController.resetSelf")],xr.prototype,"resetSelf",1),ki([E.trace("SelfController.setupEvents")],xr.prototype,"setupEvents",1),ki([E.trace("SelfController.joinRoom")],xr.prototype,"joinRoom",1),ki([E.trace("SelfController.leaveRoom")],xr.prototype,"leaveRoom",1),ki([E.trace("SelfController.joinMediaRoom")],xr.prototype,"joinMediaRoom",1),ki([E.trace("SelfController.leaveMediaRoom")],xr.prototype,"leaveMediaRoom",1),ki([E.trace("SelfController.init")],xr,"init",1);class h1{constructor(t){g(this,Pc,void 0);f(this,Pc,t)}on(t,e){let r;t===U.roomPeerCount?r=Zg.fromBinary.bind(Zg):r=mf.fromBinary.bind(mf),a(this,Pc).on(t,({payload:i})=>{if(t===U.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Pc=new WeakMap;class p1{constructor(t,e){g(this,_c,void 0);g(this,kc,void 0);f(this,_c,e),f(this,kc,t)}get logger(){return a(this,kc).getValue("logger")}on(t,e){let r,i;switch(t){case U.transcript:{r=Zu.fromBinary.bind(Zu),i=Zu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,_c).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("aiSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}}_c=new WeakMap,kc=new WeakMap;var m1=Object.defineProperty,g1=Object.getOwnPropertyDescriptor,Uh=(s,t,e,r)=>{for(var i=r>1?void 0:r?g1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&m1(t,e,i),i};class Xd{constructor(t,e){g(this,Pr,void 0);g(this,xa,void 0);f(this,Pr,e),f(this,xa,t)}get logger(){return a(this,xa).getValue("logger")}get telemetry(){return a(this,xa).getValue("telemetry")}getPolls(){return a(this,Pr).sendMessagePromise(Xs.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Pr).sendMessage(Xs.createPoll,cM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Pr).sendMessage(Xs.votePoll,lM.toBinary(r))}on(t,e){let r,i;switch(t){case Xs.updatePoll:case Xs.createPoll:case Xs.votePoll:{r=uh.fromBinary.bind(uh),i=uh.create();break}}a(this,Pr).on(t,({payload:n})=>{let o=i;try{o=r(n)}catch(c){this.logger.error("pollSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}removeListeners(t){a(this,Pr).removeListeners(t)}}Pr=new WeakMap,xa=new WeakMap,Uh([E.trace("PollSocketHandler.getPolls")],Xd.prototype,"getPolls",1),Uh([E.trace("PollSocketHandler.createPoll")],Xd.prototype,"createPoll",1),Uh([E.trace("PollSocketHandler.votePoll")],Xd.prototype,"votePoll",1);var f1=Object.defineProperty,S1=Object.getOwnPropertyDescriptor,v1=(s,t,e,r)=>{for(var i=r>1?void 0:r?S1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&f1(t,e,i),i};class dS{constructor(t,e){p(this,"socket");g(this,qt,void 0);f(this,qt,t),this.socket=e,this.handleSocketEvents(),a(this,qt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,qt).getValue("telemetry")}get logger(){return a(this,qt).getValue("logger")}cleanup(){var t;try{(t=this.socket)==null||t.disconnect()}catch(e){this.logger.error("roomSocketHandler::cleanup")}}async joinRoom(t){var i;this.socket.joinAttempted=!0;const e={capabilities:[],peer:{displayName:(i=t.name)!=null?i:"Participant",customParticipantId:t.customParticipantId,peerId:t.id,userId:t.userId,displayPictureUrl:t.picture,waitlisted:!1},roomUuid:""},r=this.socket.sendMessagePromise(U.joinRoom,cI.toBinary(e));try{const{peer:n}=Cn.fromBinary((await r).payload);a(this,qt).getValue("connectionHandler").socketJoined=!0,a(this,qt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_ROOM_JOINED,{peer:n});const o=this.getRoomState(),c=this.getRoomPeersNonPaginated(),[{room:d},{peers:l}]=await Promise.all([o,c]);return a(this,qt).getValue("peerSessionStore").emit(k.ROOM_STATE,d),a(this,qt).getValue("peerSessionStore").emit(k.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return WI.fromBinary((await this.socket.sendMessagePromise(U.getAllAddedParticipants)).payload).participants.map(({id:e,...r})=>({...r,userId:e}))}catch(t){return[]}}async getRoomPeers(t,e,r){let i;try{const n={seachQuery:t,limit:e,offset:r},o=await this.socket.sendMessagePromise(U.getRoomPeersInfo,XR.toBinary(n));i=sh.fromBinary(o.payload)}catch(n){this.logger.error("getRoomPeers::binary_decode_error",{error:n})}return i}async getRoomPeersNonPaginated(){let t;try{const e=await this.socket.sendMessagePromise(U.getRoomPeersInfo);t=sh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getStagePeers(){let t;try{const e=await this.socket.sendMessagePromise(U.getRoomPeersInfo);t=sh.fromBinary(e.payload)}catch(e){this.logger.error("getRoomJoinedPeers::binary_decode_error",{error:e})}return t}async getPeerInfo(t){let e;try{const r=await this.socket.sendMessagePromise(U.getPeerInfo,sf.toBinary({peerId:t}));e=Cn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=tf.create();try{const e=await this.socket.sendMessagePromise(U.getRoomInfo);t=tf.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=df.create();try{const e=await this.socket.sendMessagePromise(U.getRoomStageState);t=df.fromBinary(e.payload)}catch(e){this.logger.error("getRoomStageState::binary_decode_error",{error:e})}return t}async broadcastMessage(t,e){const r={type:t,payload:new TextEncoder().encode(JSON.stringify(e)),timestamp:Date.now(),ids:[]};return this.socket.sendMessagePromise(U.broadcastMessage,to.toBinary(r))}async broadcastToMeetings(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:1};return this.socket.sendMessagePromise(U.broadcastToEntity,to.toBinary(i))}async broadcastToPeers(t,e,r){const i={type:t,payload:new TextEncoder().encode(JSON.stringify(r)),timestamp:Date.now(),ids:e,broadcastType:0};return this.socket.sendMessage(U.broadcastToEntity,to.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(U.leaveRoom,lI.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(U.kick,of.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(U.kickAll,Gg.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(U.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.acceptWaitingRoomRequests,XI.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(U.denyWaitingRoomRequests,e0.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Ld.updateUserPreset,I0.toBinary(r))}handleSocketEvents(){this.socket.on(U.broadcastMessage,({payload:t})=>{try{const e=to.fromBinary(t);a(this,qt).getValue("peerSessionStore").emit(k.ROOM_MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode broadcast message:",e)}}),this.socket.on(U.broadcastToEntity,({payload:t})=>{try{const e=to.fromBinary(t);a(this,qt).getValue("peerSessionStore").emit(k.MESSAGE,{payload:JSON.parse(new TextDecoder().decode(e.payload)),type:e.type,timestamp:e.timestamp})}catch(e){this.logger.error("failed to decode peer broadcast message:",e)}})}on(t,e){let r,i;switch(t){case U.joinRoom:case U.leaveRoom:case U.kick:case U.kickAll:{r=Cn.fromBinary.bind(Cn),i=Cn.create();break}case U.getWaitingRoomRequests:{r=(n,o)=>n?cf.fromBinary(n,o):{requests:[]},i=cf.create();break}case U.recordingPaused:case U.recordingStarted:case U.recordingStopped:{r=vf.fromBinary.bind(vf);break}case Ld.updateUserPreset:{r=uf.fromBinary.bind(uf);break}case hs.peerJoinedBroadcast:case Mr.peerJoinedBroadcast:{r=Kg.fromBinary.bind(Kg);break}case hs.selfJoinComplete:case Mr.selfJoinComplete:{r=Qu.fromBinary.bind(Qu);break}case hs.globalPeerPinBroadcast:case Mr.globalPeerPinBroadcast:{r=Qg.fromBinary.bind(Qg);break}case hs.selectedPeer:case Mr.selectedPeer:{r=Yu.fromBinary.bind(Yu);break}case hs.selectedPeerDiff:case Mr.selectedPeerDiff:{r=Jg.fromBinary.bind(Jg);break}case hs.leaveRoom:case Mr.leaveRoom:{r=Xu.fromBinary.bind(Xu);break}}this.socket.on(t,({payload:n})=>{let o=i;if(!r)return e(void 0);try{o=r(n)}catch(c){this.logger.error("roomSocketHandler::on::binary_decode_error",{error:c})}return e(o)})}async getUserPermissions(t){const e={userIds:[t]};try{const r=await this.socket.sendMessagePromise(Ld.getUserPresets,b0.toBinary(e)),i=k0.fromBinary(r.payload).peerPresets[0],n=new TextDecoder().decode(i.preset),o=JSON.parse(n).permissions;return{chat:o.chat,polls:o.polls,plugins:o.plugins}}catch(r){throw this.logger.error("Error in getting user preset",{error:r}),r}}}qt=new WeakMap,v1([E.trace("RoomSocketHandler.joinRoom")],dS.prototype,"joinRoom",1);class T1{constructor(t){g(this,Mt,void 0);f(this,Mt,t)}async getStageRequests(){const{payload:t}=await a(this,Mt).sendMessagePromise(U.getStageRequests);return t?lh.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Mt).sendMessage(U.requestStageAccess)}cancelRequestAccess(){a(this,Mt).sendMessage(U.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Mt).sendMessage(U.grantStageAccess,XA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Mt).sendMessage(U.denyStageAccess,eM.toBinary(e))}joinStage(){return a(this,Mt).sendMessagePromise(U.joinStage,void 0,void 0,U.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Mt).sendMessagePromise(U.leaveStage,ff.toBinary(e),void 0,U.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Mt).sendMessagePromise(U.leaveStage,ff.toBinary(e))}on(t,e){let r;switch(t){case U.grantStageAccess:case U.denyStageAccess:{r=void 0;break}case U.getStagePeers:{r=gf.fromBinary.bind(gf);break}case U.getStageRequests:case U.requestStageAccess:case U.cancelStageRequest:{r=lh.fromBinary.bind(lh);break}case U.peerStageStatusUpdate:{r=Xg.fromBinary.bind(Xg);break}}a(this,Mt).on(t,({payload:i,id:n})=>{if(!i||!r)return e(void 0,n);const o=r(i);return e(o,n)})}async getPeerInfo(t){const e=await a(this,Mt).sendMessagePromise(U.getPeerInfo,sf.toBinary({peerId:t}));return Cn.fromBinary(e.payload)}}Mt=new WeakMap;class y1{constructor(t,e){g(this,oi,void 0);g(this,Ua,void 0);f(this,oi,e),f(this,Ua,t)}get logger(){return a(this,Ua).getValue("logger")}get peerId(){return a(this,Ua).getValue("peerId")}storeInsertKeys(t,e,r,i){const n={pluginId:t,storeName:e,insertKeys:r.map(o=>({storeKey:o.key,payload:new TextEncoder().encode(JSON.stringify(o.payload))}))};a(this,oi).sendMessage(Qs.storeInsertKeys,OA.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,oi).sendMessage(Qs.storeGetKeys,NA.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,oi).sendMessage(Qs.storeDeleteKeys,LA.toBinary(n),i)}on(t,e){const r=pf.fromBinary.bind(pf);a(this,oi).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}oi=new WeakMap,Ua=new WeakMap;var E1=Object.defineProperty,b1=(s,t,e)=>t in s?E1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,w1=(s,t,e)=>(b1(s,typeof t!="symbol"?t+"":t,e),e),$h=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},M=(s,t,e)=>($h(s,t,"read from private field"),e?e.call(s):t.get(s)),le=(s,t,e)=>{if(t.has(s))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(s):t.set(s,e)},ie=(s,t,e,r)=>($h(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),ne=(s,t,e)=>($h(s,t,"access private method"),e),Zd={},P1={get exports(){return Zd},set exports(s){Zd=s}},Dn=typeof Reflect=="object"?Reflect:null,lS=Dn&&typeof Dn.apply=="function"?Dn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},el;Dn&&typeof Dn.ownKeys=="function"?el=Dn.ownKeys:Object.getOwnPropertySymbols?el=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:el=function(s){return Object.getOwnPropertyNames(s)};function _1(s){console&&console.warn&&console.warn(s)}var uS=Number.isNaN||function(s){return s!==s};function ue(){ue.init.call(this)}P1.exports=ue,Zd.once=I1,ue.EventEmitter=ue,ue.prototype._events=void 0,ue.prototype._eventsCount=0,ue.prototype._maxListeners=void 0;var hS=10;function tl(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ue,"defaultMaxListeners",{enumerable:!0,get:function(){return hS},set:function(s){if(typeof s!="number"||s<0||uS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");hS=s}}),ue.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},ue.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||uS(s))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+s+".");return this._maxListeners=s,this};function pS(s){return s._maxListeners===void 0?ue.defaultMaxListeners:s._maxListeners}ue.prototype.getMaxListeners=function(){return pS(this)},ue.prototype.emit=function(s){for(var t=[],e=1;e<arguments.length;e++)t.push(arguments[e]);var r=s==="error",i=this._events;if(i!==void 0)r=r&&i.error===void 0;else if(!r)return!1;if(r){var n;if(t.length>0&&(n=t[0]),n instanceof Error)throw n;var o=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw o.context=n,o}var c=i[s];if(c===void 0)return!1;if(typeof c=="function")lS(c,this,t);else for(var d=c.length,l=vS(c,d),e=0;e<d;++e)lS(l[e],this,t);return!0};function mS(s,t,e,r){var i,n,o;if(tl(e),n=s._events,n===void 0?(n=s._events=Object.create(null),s._eventsCount=0):(n.newListener!==void 0&&(s.emit("newListener",t,e.listener?e.listener:e),n=s._events),o=n[t]),o===void 0)o=n[t]=e,++s._eventsCount;else if(typeof o=="function"?o=n[t]=r?[e,o]:[o,e]:r?o.unshift(e):o.push(e),i=pS(s),i>0&&o.length>i&&!o.warned){o.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=s,c.type=t,c.count=o.length,_1(c)}return s}ue.prototype.addListener=function(s,t){return mS(this,s,t,!1)},ue.prototype.on=ue.prototype.addListener,ue.prototype.prependListener=function(s,t){return mS(this,s,t,!0)};function k1(){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 gS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=k1.bind(r);return i.listener=e,r.wrapFn=i,i}ue.prototype.once=function(s,t){return tl(t),this.on(s,gS(this,s,t)),this},ue.prototype.prependOnceListener=function(s,t){return tl(t),this.prependListener(s,gS(this,s,t)),this},ue.prototype.removeListener=function(s,t){var e,r,i,n,o;if(tl(t),r=this._events,r===void 0)return this;if(e=r[s],e===void 0)return this;if(e===t||e.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[s],r.removeListener&&this.emit("removeListener",s,e.listener||t));else if(typeof e!="function"){for(i=-1,n=e.length-1;n>=0;n--)if(e[n]===t||e[n].listener===t){o=e[n].listener,i=n;break}if(i<0)return this;i===0?e.shift():C1(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},ue.prototype.off=ue.prototype.removeListener,ue.prototype.removeAllListeners=function(s){var t,e,r;if(e=this._events,e===void 0)return this;if(e.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):e[s]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete e[s]),this;if(arguments.length===0){var i=Object.keys(e),n;for(r=0;r<i.length;++r)n=i[r],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=e[s],typeof t=="function")this.removeListener(s,t);else if(t!==void 0)for(r=t.length-1;r>=0;r--)this.removeListener(s,t[r]);return this};function fS(s,t,e){var r=s._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i=="function"?e?[i.listener||i]:[i]:e?R1(i):vS(i,i.length)}ue.prototype.listeners=function(s){return fS(this,s,!0)},ue.prototype.rawListeners=function(s){return fS(this,s,!1)},ue.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):SS.call(s,t)},ue.prototype.listenerCount=SS;function SS(s){var t=this._events;if(t!==void 0){var e=t[s];if(typeof e=="function")return 1;if(e!==void 0)return e.length}return 0}ue.prototype.eventNames=function(){return this._eventsCount>0?el(this._events):[]};function vS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function C1(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function R1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function I1(s,t){return new Promise(function(e,r){function i(o){s.removeListener(t,n),r(o)}function n(){typeof s.removeListener=="function"&&s.removeListener("error",i),e([].slice.call(arguments))}TS(s,t,n,{once:!0}),t!=="error"&&A1(s,i,{once:!0})})}function A1(s,t,e){typeof s.on=="function"&&TS(s,"error",t,e)}function TS(s,t,e,r){if(typeof s.on=="function")r.once?s.once(t,e):s.on(t,e);else if(typeof s.addEventListener=="function")s.addEventListener(t,function i(n){r.once&&s.removeEventListener(t,i),e(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof s)}class M1 extends v{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 yS=new M1;class ES{static encode(t){return yS.toBinary(t)}static decode(t){return yS.fromBinary(new Uint8Array(t))}}function O1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Ur;class D1{constructor(t={}){w1(this,"opts"),le(this,Ur,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Ur,0)}async wait(){ie(this,Ur,M(this,Ur)+1);const t=O1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**M(this,Ur)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return M(this,Ur)}reset(){ie(this,Ur,0)}}Ur=new WeakMap;const $r={debug:0,info:1,warn:2,error:3};var Ci,Ri;class N1{constructor(t){le(this,Ci,void 0),le(this,Ri,void 0),ie(this,Ci,console),ie(this,Ri,t)}debug(...t){$r[M(this,Ri)]>$r.debug||M(this,Ci).debug("[Sockrates]:",...t)}info(...t){$r[M(this,Ri)]>$r.info||M(this,Ci).info("[Sockrates]:",...t)}warn(...t){$r[M(this,Ri)]>$r.warn||M(this,Ci).warn("[Sockrates]:",...t)}error(...t){$r[M(this,Ri)]>$r.error||M(this,Ci).error("[Sockrates]:",...t)}}Ci=new WeakMap,Ri=new WeakMap;var bS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(bS||{});const wS="2",PS="3";var Oe,Nn,he,Ce,Br,ze,ir,Fr,ms,Vn,Ln,nr,Bh,_S,fo,sl,Fh,kS,rl,Hh,il,qh,jh,CS,So,nl,xn,vo,al,Gh,Un,To,Wh,RS,yo,ol,Eo,cl;class V1{constructor(t,e){var y,w,_,C,D,V,$,H,F,Z,be,Ge;le(this,Bh),le(this,fo),le(this,Fh),le(this,rl),le(this,il),le(this,jh),le(this,So),le(this,xn),le(this,al),le(this,Un),le(this,Wh),le(this,yo),le(this,Eo),le(this,Oe,void 0),le(this,Nn,void 0),le(this,he,void 0),le(this,Ce,void 0),le(this,Br,void 0),le(this,ze,void 0),le(this,ir,void 0),le(this,Fr,void 0),le(this,ms,void 0),le(this,Vn,void 0),le(this,Ln,void 0),le(this,nr,void 0);var r,i,n,o,c,d,l,u,h,m,S;ie(this,Nn,t),ie(this,Br,[]),ie(this,ze,new Zd),ie(this,ir,!0),ie(this,ms,!1),ie(this,he,e!=null?e:{}),(y=(r=M(this,he)).autoReconnect)!=null||(r.autoReconnect=!0),(w=(i=M(this,he)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(_=(n=M(this,he)).pingTimeout)!=null||(n.pingTimeout=3e4),(C=(o=M(this,he)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(D=(c=M(this,he)).debug)!=null||(c.debug=!0),(V=(d=M(this,he)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),($=(l=M(this,he)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(H=(u=M(this,he)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(F=(h=M(this,he)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),(Z=(m=M(this,he)).clientInitiatedPings)!=null||(m.clientInitiatedPings=!1),(be=(S=M(this,he)).clientInitiatedPingInterval)!=null||(S.clientInitiatedPingInterval=3e4),ie(this,Fr,{code:void 0,reason:void 0}),ie(this,Ce,(Ge=M(this,he).logger)!=null?Ge:new N1(M(this,he).debug?"debug":"info")),ie(this,nr,new D1)}get readyState(){var t;return(t=M(this,Oe))==null?void 0:t.readyState}get url(){return M(this,Nn)}updateURL(t){ie(this,Nn,t),ne(this,jh,CS).call(this)}get config(){return M(this,he)}get sendQueue(){return M(this,Br)}flush(){if(!M(this,he).queueOnDisconnect)return!1;const t=[];return M(this,Br).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,Br,t),M(this,Br)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){M(this,Ce).debug("Websocket was already connecting or connected.");return}if(M(this,ir)!==!1)return new Promise((e,r)=>{ne(this,Un,To).call(this),ne(this,Eo,cl).call(this);try{ie(this,Oe,new WebSocket(ne(this,Bh,_S).call(this,M(this,Nn)))),M(this,Oe).binaryType="arraybuffer",M(this,Ce).debug("Connecting");const i=setTimeout(()=>{M(this,Ce).debug("Connection timeout. Closing socket"),ie(this,ir,!0),ne(this,Eo,cl).call(this),M(this,Oe).close(3001,"Connection Timeout"),M(this,he).autoReconnect&&!M(this,ms)&&(M(this,ze).emit("reconnecting"),ne(this,So,nl).call(this)),r(new Error("Connection timed out!"))},M(this,he).connectionTimeout);M(this,Oe).onopen=()=>{M(this,Ce).debug(`Ready State: ${bS[M(this,Oe).readyState]}`),i&&clearTimeout(i),ne(this,al,Gh).call(this),ne(this,Wh,RS).call(this),ie(this,Fr,{code:void 0,reason:void 0}),M(this,ze).emit("connected"),M(this,he).flushOnReconnect&&this.flush(),e()},M(this,Oe).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),M(this,Ce).debug("Socket closed. Close event:",{event:n}),M(this,Ce).debug(`Connection closed code: ${o}`),M(this,Ce).debug(`Connection closed reason: ${c}`),M(this,ms)||ne(this,il,qh).call(this,o,c)}catch(o){ne(this,fo,sl).call(this,o)}},M(this,Oe).onerror=n=>{ne(this,fo,sl).call(this,n)},M(this,Oe).onmessage=n=>ne(this,Fh,kS).call(this,n)}catch(i){ne(this,fo,sl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(M(this,he).queueOnDisconnect&&(!M(this,Oe)||M(this,Oe).readyState!==1))return M(this,Ce).debug("Queuing message since socket is not connected!",n),M(this,Br).push(n),!1;const o=ES.encode(n);return ne(this,xn,vo).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return ne(this,xn,vo).call(this,t)}receive(t,e){return M(this,ze).on(t.toString(),e)}on(t,e){if(typeof t=="string"&&(t==="connected"||t==="disconnected"||t==="errored"||t==="reconnected"||t==="reconnecting"||t==="reconnectAttempt"||t==="reconnectFailure"||t==="failed")){M(this,ze).on(t,e);return}this.receive(t,e)}removeAllListeners(){M(this,ze).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){M(this,ze).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){M(this,ze).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,ir,!1),ne(this,Un,To).call(this),ne(this,yo,ol).call(this),this.removeAllListeners(),ie(this,Fr,{code:1e3,reason:"Sockrates disconnect method called"}),M(this,Oe).close(1e3,"Sockrates disconnect method called.")}}Oe=new WeakMap,Nn=new WeakMap,he=new WeakMap,Ce=new WeakMap,Br=new WeakMap,ze=new WeakMap,ir=new WeakMap,Fr=new WeakMap,ms=new WeakMap,Vn=new WeakMap,Ln=new WeakMap,nr=new WeakMap,Bh=new WeakSet,_S=function(s){if(s.startsWith("ws://")||s.startsWith("wss://"))return s;if(s.startsWith("https://"))return`wss://${s.substring(8)}`;if(s.startsWith("http://"))return`ws://${s.substring(7)}`;throw new Error("Invalid URL. URL must start with http(s):// or ws(s)://.")},fo=new WeakSet,sl=function(s,t){M(this,Ce).error("Error:",{error:s}),M(this,ze).emit("errored",{error:s}),t==null||t(s)},Fh=new WeakSet,kS=function(s){if(ne(this,al,Gh).call(this),s.data===wS){M(this,Ce).debug("Received ping from server"),ne(this,xn,vo).call(this,PS);return}if(s.data===PS){M(this,Ce).debug("Received pong from server");return}const t=ES.decode(s.data),{id:e,payload:r}=t;M(this,Ce).debug("Received message",{event:t.event,messageID:e}),M(this,ze).emit(t.event.toString(),{id:e,payload:r})},rl=new WeakSet,Hh=function(){return M(this,Oe).readyState===1},il=new WeakSet,qh=function(s,t){ie(this,Fr,{reason:t,code:s}),M(this,ze).emit("disconnected",{code:s,reason:t})},jh=new WeakSet,CS=function(){const{reason:s,code:t}=M(this,Fr);t&&t!==1e3&&M(this,ir)&&M(this,he).autoReconnect&&!M(this,ms)&&(M(this,Ce).debug(`Triggering reconnection due to ${s}.`),M(this,ze).emit("reconnecting"),ne(this,So,nl).call(this))},So=new WeakSet,nl=async function(s=!0){if(s&&M(this,ms)){M(this,Ce).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(M(this,ms)||M(this,nr).reset(),M(this,he).maxReconnectionAttempts!==null&&M(this,nr).getAttempts()>=M(this,he).maxReconnectionAttempts){M(this,ze).emit("failed"),ie(this,ms,!1);return}ie(this,ms,!0),ne(this,Eo,cl).call(this),ne(this,Un,To).call(this);try{if(await M(this,nr).wait(),M(this,ir)===!1)return;if(M(this,Ce).debug(`Reconnection attempt ${M(this,nr).getAttempts()}`),M(this,ze).emit("reconnectAttempt",{attempt:M(this,nr).getAttempts()}),await this.connect(),!ne(this,rl,Hh).call(this))throw Error("Reconnect Failed");ie(this,ms,!1),ie(this,Fr,{code:void 0,reason:void 0}),M(this,ze).emit("reconnected")}catch(t){M(this,Ce).debug("Failed to reconnect."),M(this,ze).emit("reconnectFailure",{attempt:M(this,nr).getAttempts()}),ne(this,So,nl).call(this,!1)}},xn=new WeakSet,vo=function(s){try{return M(this,Oe).send(s),!0}catch(t){return M(this,Ce).error(t.message),!1}},al=new WeakSet,Gh=function(){this.config.disconnectOnPingTimeout&&(M(this,Ce).debug("Resetting ping timeout"),ne(this,Un,To).call(this),ie(this,Vn,setTimeout(()=>{var s;M(this,Ce).debug("Disconnecting the socket due to ping timeout"),ie(this,ir,!0);const t=3002,e="Ping timeout";(s=M(this,Oe))==null||s.close(t,e),ne(this,il,qh).call(this,t,e)},M(this,he).pingTimeout)))},Un=new WeakSet,To=function(){M(this,Vn)&&(clearTimeout(M(this,Vn)),ie(this,Vn,void 0))},Wh=new WeakSet,RS=function(){ne(this,yo,ol).call(this),M(this,he).clientInitiatedPings&&ie(this,Ln,setInterval(()=>{ne(this,rl,Hh).call(this)&&(M(this,Ce).debug("Sending client-initiated ping"),ne(this,xn,vo).call(this,wS))},M(this,he).clientInitiatedPingInterval))},yo=new WeakSet,ol=function(){M(this,Ln)&&(clearInterval(M(this,Ln)),ie(this,Ln,void 0))},Eo=new WeakSet,cl=function(){ne(this,yo,ol).call(this),M(this,Oe)&&(M(this,Oe).onopen=void 0,M(this,Oe).onerror=void 0,M(this,Oe).onmessage=void 0,M(this,Oe).onclose=void 0)};var L1=Object.defineProperty,x1=Object.getOwnPropertyDescriptor,dl=(s,t,e,r)=>{for(var i=r>1?void 0:r?x1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&L1(t,e,i),i};const IS=65535,U1=3e3,AS=(XS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Ie);g(this,Cc);g(this,Rc);g(this,ci,void 0);g(this,Re,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,as,void 0);g(this,rt,void 0);if(!t||!e||!r)throw new R("peerId, meetingId, or authToken can not be empty","0404");f(this,as,void 0),f(this,rt,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,ci,L(this,Cc,gp).call(this,t));const n=i.includes("PING");f(this,Re,new V1(a(this,ci),{autoReconnect:!0,disconnectOnPingTimeout:n,queueOnDisconnect:!1,flushOnReconnect:!1,logger:this.logger,clientInitiatedPings:!n,maxReconnectionAttempts:50,clientInitiatedPingInterval:15e3})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Ie,He).socketJoinAttempted}set joinAttempted(s){a(this,Ie,He).socketJoinAttempted=s}get telemetry(){return a(this,rt).getValue("telemetry")}get logger(){return a(this,rt).getValue("logger")}get peerId(){return a(this,rt).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,ci,L(this,Cc,gp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Re).updateURL(a(this,ci))}static getSocketEdgeDomain(s){return _n({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,ci)}async connect(){a(this,Ie,He).socketJoinAttempted=!0,await a(this,Re).connect(),a(this,Ie,He).socketJoinAttempted=!0,a(this,Ie,He).socketState={state:"connected",reconnected:!1,reconnectionAttempt:void 0}}disconnect(){a(this,Ie,He).socketJoinAttempted=!1,a(this,Re).disconnect(),a(this,Ie,He).socketJoinAttempted=!0,a(this,Ie,He).socketState={state:"disconnected",reconnected:!1,reconnectionAttempt:void 0}}get isConnected(){try{return a(this,Re).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,rt).getValue("telemetry").injectContext(r),a(this,Re).send(s,e!=null?e:L(this,Rc,fp).call(this),t,new TextEncoder().encode(JSON.stringify(r)))}sendMessagePromise(s,t,e,r){const i=parseInt({}.SOCKET_SERVICE_MESSAGE_REQUEST_TIMEOUT,10)||2e4;return this.sendMessagePromiseWithTimeout({event:s,timeout:i,protobuf:t,messageId:e,resp:r})}sendMessagePromiseWithTimeout({event:s,timeout:t,protobuf:e,messageId:r,resp:i}){const n=i!=null?i:s;return new Promise((o,c)=>{const d=(y,w)=>{a(this,Re).removeListener(n,y),a(this,Re).removeListener(IS,w),a(this,Re).removeListener(Mr.errorResponse,w),a(this,Re).removeListener(hs.errorResponse,w)},l=r!=null?r:L(this,Rc,fp).call(this),u={};a(this,rt).getValue("telemetry").injectContext(u);const m=({id:y,payload:w})=>{if(l===y){let _;try{const C=jC.fromBinary(w);_=new Error(C.errorMessage)}catch(C){_=new Error("failed to parse error message",{cause:C});try{const D=GR.fromBinary(w);_=new Error(D.message)}catch(D){_=new Error("failed to parse error message",{cause:D})}}c(_),d(S,m)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,m))};a(this,Re).on(n,S),a(this,Re).on(IS,m),a(this,Re).on(Mr.errorResponse,m),a(this,Re).on(hs.errorResponse,m),setTimeout(()=>{d(S,m),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,Re).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,Re).on(s,t)}onStateEvent(s,t){a(this,Re).on(s,t)}removeListener(s,t){a(this,Re).removeListener(s,t)}removeListeners(s){a(this,Re).removeListeners(s)}flush(){return a(this,Re).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,Ie,He).updateSocketConnectionState("connected")}),this.onStateEvent("disconnected",({code:s,reason:t})=>{var i;this.logger.info("SocketService::Disconnected from socket-edge",{error:{code:s,reason:t}});const{recv:e,send:r}=(i=a(this,Ie,He).mediaState)!=null?i:{};e!=null&&e.state&&(e==null?void 0:e.state)!==Ds.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Ds.CONNECTED?a(this,rt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ie,He).joinAttempted}):f(this,as,setTimeout(()=>{a(this,rt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ie,He).joinAttempted}),f(this,as,void 0)},U1)),a(this,Ie,He).updateSocketConnectionState("disconnected")}),this.onStateEvent("reconnecting",async()=>{this.logger.info("SocketService::Reconnecting to socket-edge"),a(this,Ie,He).updateSocketConnectionState("reconnecting")}),this.onStateEvent("reconnectAttempt",async({attempt:s})=>{this.logger.info("SocketService::Attempting to reconnect to socket-edge",{socket:{retryAttempt:s}}),a(this,Ie,He).updateSocketConnectionState("reconnectAttempt",s)}),this.onStateEvent("reconnectFailure",({attempt:s})=>{this.logger.info("SocketService::Reconnect attempt to socket-edge failed",{socket:{retryAttempt:s}}),a(this,Ie,He).updateSocketConnectionState("reconnectFailure",s)}),this.onStateEvent("reconnected",async()=>{this.logger.info("SocketService::Reconnected to socket-edge",{connectionState:{joinAttempted:a(this,Ie,He).mediaJoinAttempted}}),a(this,as)&&(clearTimeout(a(this,as)),f(this,as,void 0)),a(this,rt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_RECONNECTED,{wasJoinAttempted:a(this,Ie,He).mediaJoinAttempted}),a(this,Ie,He).updateSocketConnectionState("reconnected")}),this.onStateEvent("failed",async()=>{this.logger.info("SocketService::Failed to connect to socket-edge"),a(this,rt).getValue("peerSessionStore").emit(k.SOCKET_SERVICE_FAILED),a(this,Ie,He).updateSocketConnectionState("failed")})}},ci=new WeakMap,Re=new WeakMap,Ie=new WeakSet,He=function(){return a(this,rt).getValue("connectionHandler")},as=new WeakMap,rt=new WeakMap,Cc=new WeakSet,gp=function(s){const t=a(this,rt).getValue("socketBaseURI")||a(this,rt).getValue("baseURI");let e=AS.getSocketEdgeDomain(t);typeof Pn(a(this,rt),"socket_server_base")=="string"&&(e=Pn(a(this,rt),"socket_server_base"));const r=`wss://${e}`,i=new URL(`${r}/ws`),n=this.peerId,o={roomID:this.roomName,peerID:s,authToken:this.authToken,useMediaV2:!0,...n!==s&&{oldPeerID:n},ping:this.capabilities.includes("PING"),capabilities:this.capabilities.map(c=>Md[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Rc=new WeakSet,fp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},XS);let bo=AS;dl([E.trace("SocketService.connect")],bo.prototype,"connect",1),dl([E.trace("SocketService.disconnect")],bo.prototype,"disconnect",1),dl([E.trace("SocketService.sendMessagePromise")],bo.prototype,"sendMessagePromise",1),dl([E.trace("SocketService.sendMessagePromiseWithTimeout")],bo.prototype,"sendMessagePromiseWithTimeout",1);class $1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=vI.fromBinary(t),r=e.meetings.map(o=>{var c;return{id:o.id,title:o.title,participants:(c=o.participants)!=null?c:[]}});return{parentMeeting:{id:e.parentMeeting.id,title:e.parentMeeting.title,participants:(n=e.parentMeeting.participants)!=null?n:[]},meetings:r}}handleTransferPeerRaw({payload:t}){const e=jI.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=af.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return nf.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return NI.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(U.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(U.createConnectedRooms,bI.toBinary({payloads:t}));return nf.fromBinary(e).payloads.map(i=>({id:i.id,title:i.title}))}async updateConnectedRooms(t){}async disableConnectedRooms(t){const e=t.map(i=>({id:i})),r=await this.socketService.sendMessagePromise(U.deleteConnectedRooms,OI.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(U.movePeers,BI.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}}}}var B1=Object.defineProperty,F1=Object.getOwnPropertyDescriptor,H1=(s,t,e,r)=>{for(var i=r>1?void 0:r?F1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&B1(t,e,i),i};class MS extends Dt{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,jt,void 0);f(this,jt,e)}get isActive(){return this.meetings.length!==0}validateAlterAction(){const e=a(this,jt).getValue("self").permissions.connectedMeetings;if(!(e!=null&&e.canAlterConnectedMeetings))throw new Error("You are not allowed to perform this action. Please enable canAlterConnectedMeetings permission in your preset.")}validateMoveAction(e,r){var d;if(!(r!=null&&r.length))throw new Error("You're trying to move participants with an empty list.");const i=a(this,jt).getValue("self").permissions.connectedMeetings;if(!i)throw new Error("You are not allowed to perform this action. Please enable connected meetings permissions in your preset.");if(i.canAlterConnectedMeetings)return;const n=a(this,jt).getValue("userId");if(!(r.length===1&&r[0]===n))throw new Error("You are not allowed to move other participants. Please enable canAlterConnectedMeetings permission in your preset.");if(e===((d=this.parentMeeting)==null?void 0:d.id)){if(!i.canSwitchToParentMeeting)throw new Error("You are not allowed to move to the parent meeting. Please enable canSwitchToParentMeeting permission in your preset.");return}if(!i.canSwitchConnectedMeetings)throw new Error("You are not allowed to move to a connected meeting. Please enable canSwitchConnectedMeetings permission in your preset.")}async getConnectedMeetings(){this.logger.info("Getting connected meetings dump");const e=await a(this,jt).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateAlterAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,jt).getValue("connectedMeetingsSocketHandler").createConnectedRooms(e);return this.logger.info(`Created connected meetings ${JSON.stringify(r)}`),r.map(i=>({id:i.id,title:i.title}))}async updateMeetings(e){this.validateAlterAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,jt).getValue("connectedMeetingsSocketHandler").updateConnectedRooms(e.map(r=>({meetingId:r.id,title:r.title}))),this.logger.info(`Updated connected meetings ${JSON.stringify(e)}`)}async deleteMeetings(e){this.validateAlterAction(),this.logger.info(`Moving participants before deleting connected meetings ${JSON.stringify(e)}`);const r=this.meetings.map(n=>e.includes(n.id)&&n.participants.length!==0?this.moveParticipants(n.id,this.parentMeeting.id,n.participants.map(o=>o.id)):Promise.resolve());this.logger.info(`Moved participants before deleting connected meetings ${JSON.stringify(e)}. Deleting now.`),await Promise.all(r);const i=await a(this,jt).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateMoveAction(r,i),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,jt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i.map(o=>({id:o}))});return n.success?(this.logger.info(`Moved connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i)):this.logger.error(`Failed to move connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`),n}async moveParticipantsWithCustomPreset(e,r,i){this.validateMoveAction(r,i.map(o=>o.id)),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,jt).getValue("connectedMeetingsSocketHandler").movePeersBetweenRooms({sourceMeetingId:e,destinationMeetingId:r,participants:i});return n.success?(this.logger.info(`Moved connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),this.moveSuccessHandler(e,r,i.map(o=>o.id))):this.logger.error(`Failed to move connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`),n}moveSuccessHandler(e,r,i){const n=new Map;[...this.parentMeeting.participants,...this.meetings.flatMap(o=>o.participants)].forEach(o=>n.set(o.id,o)),r===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.concat(i.map(o=>n.get(o)))),e===this.parentMeeting.id&&(this.parentMeeting.participants=this.parentMeeting.participants.filter(o=>!i.includes(o.id))),this.meetings=this.meetings.map(o=>{if(r===o.id){const c=o.participants.concat(i.map(d=>n.get(d)));return{...o,participants:c}}if(e===o.id){const c=o.participants.filter(d=>!i.includes(d.id));return{...o,participants:c}}return o})}}jt=new WeakMap,H1([Nt({maxInvocations:60,period:60})],MS.prototype,"getConnectedMeetings",1);var q1=Object.defineProperty,j1=Object.getOwnPropertyDescriptor,Jh=(s,t,e,r)=>{for(var i=r>1?void 0:r?j1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&q1(t,e,i),i};const OS=(ZS=class{constructor(s){p(this,"connectedMeetings");g(this,ve,void 0);f(this,ve,s),this.connectedMeetings=new MS(s)}get telemetry(){return a(this,ve).getValue("telemetry")}get logger(){return a(this,ve).getValue("logger")}static init(s){const t=new OS(s);return s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings()),t.setupEvents(),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.transferPeer,this.handleTransferPeer.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.movedPeer,this.handleMovedPeer.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,ve).getValue("connectedMeetingsSocketHandler").socketService.on(U.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,ve).getValue("connectedMeetingsSocketHandler").handleTransferPeerRaw(s);return this.logger.info(`Honoring request to switch connected meetings. Going to ${t==null?void 0:t.meetingId}`),this.switchMeeting(t)}async switchMeeting({authToken:s,meetingId:t}){var i,n,o,c;this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,ve).getValue("self").videoEnabled,audio:a(this,ve).getValue("self").audioEnabled};try{a(this,ve).getValue("self").cleanupEvents(),await a(this,ve).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,ve).getValue("meeting"))==null?void 0:i.meta)==null?void 0:n.meetingId}`,{error:d})}this.logger.info(`ConnectedMeetingsController::switchMeeting:: initializing new meeting. Meeting Id: ${t}`);const r=await NS.init({...a(this,ve).getValue("options"),cachedUserDetails:null,defaults:{...a(this,ve).getValue("options").defaults,...e,mediaHandler:a(this,ve).getValue("self")},authToken:s});this.logger.info(`ConnectedMeetingsController::switchMeeting:: initialized new meeting. Meeting Id: ${(o=r==null?void 0:r.meta)==null?void 0:o.meetingId}`);try{const{hidden:d}=a(this,ve).getValue("self");r.self.setName(a(this,ve).getValue("self").name),await r.join(),d&&r.self.hide()}catch(d){this.logger.error("ConnectedMeetingsController.joinRoom",{error:d})}return this.logger.info(`ConnectedMeetingsController::switchMeeting:: asking ui-kit to show in-meeting ui of newly joined meeting id: ${(c=r==null?void 0:r.meta)==null?void 0:c.meetingId}`),this.connectedMeetings.emit("meetingChanged",r),r}handleConnectedRoomsDump(s){const t=a(this,ve).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDumpRaw(s);this.connectedMeetings.meetings=t.meetings.map(e=>({id:e.id,title:e.title,participants:e.participants||[]})),this.connectedMeetings.parentMeeting={id:t.parentMeeting.id,title:t.parentMeeting.title,participants:t.parentMeeting.participants},this.emitStateUpdate()}handleMovedPeer(s){return a(this,ve).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,ve).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsUpdatedRaw(s),e=new Map;this.connectedMeetings.meetings.forEach(r=>{e.set(r.id,r)}),t.forEach(r=>{e.has(r.id)?e.get(r.id).title=r.title:e.set(r.id,{...r,participants:[]})}),this.connectedMeetings.meetings=Array.from(e.values()),this.emitStateUpdate()}handleConnectedRoomsDeleted(s){const e=a(this,ve).getValue("connectedMeetingsSocketHandler").handleConnectedRoomsDeletedRaw(s).map(r=>r.id);this.connectedMeetings.meetings=this.connectedMeetings.meetings.filter(r=>!e.includes(r.id)),this.emitStateUpdate()}emitStateUpdate(){this.connectedMeetings.emit("stateUpdate",{meetings:this.connectedMeetings.meetings,parentMeeting:this.connectedMeetings.parentMeeting})}},ve=new WeakMap,ZS);let ll=OS;Jh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],ll.prototype,"getConnectedMeetings",1),Jh([E.trace("ConnectedMeetingsController.setupEvents")],ll.prototype,"setupEvents",1),Jh([E.trace("ConnectedMeetingsController.switchMeeting")],ll.prototype,"switchMeeting",1);var G1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,Kh=(s,t,e,r)=>{for(var i=r>1?void 0:r?W1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&G1(t,e,i),i};const wo=class{constructor(s,t,e){p(this,"apiBase");p(this,"selfController");p(this,"pollController");p(this,"chatController");p(this,"metaController");p(this,"storesManager");p(this,"stageController");p(this,"pluginController");p(this,"internalsController");p(this,"recordingController");p(this,"livestreamController");p(this,"participantController");p(this,"connectedMeetingsController");p(this,"telemetry");p(this,"logger");this.apiBase=s,this.storesManager=t.storesManager,this.metaController=t.metaController,this.selfController=t.selfController,this.chatController=t.chatController,this.pollController=t.pollController,this.stageController=t.stageController,this.pluginController=t.pluginController,this.recordingController=t.recordingController,this.internalsController=t.internalsController,this.participantController=t.participantController,this.livestreamController=t.livestreamController,this.connectedMeetingsController=t.connectedMeetingsController,this.telemetry=e.getValue("telemetry"),this.logger=e.getValue("logger")}static async init(s){var V,$,H;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(d1(s),Te.isSupported()===!1)throw new R("Browser not supported","0010",c,!0);const d=$M(s,{authToken:r,baseURL:e,cachedUserDetails:o});d.setRoomName(i),d.setRoomUUID(i),d.setOrganizationId(n),d.setHeader("tracing-id",t),s.setValue("apiClient",d);const l=new EO(s);s.setValue("connectionHandler",l);let u="",h="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=((V=m.meeting)==null?void 0:V.title)||"",h=(($=m.socket)==null?void 0:$.baseUri)||s.getValue("baseURI"),s.setValue("presetName",m.preset.name),s.setValue("socketBaseURI",h),c.info(`Socket Base URI ${h} is being used`)}catch(F){throw c.error("Failed to get user details",{error:F}),F instanceof xd?F.status===401?new R("Unauthorized. The auth token may be invalid or expired. (401)","0004"):F.status===403?new R("Access denied. Insufficient permissions to join the meeting. (403)","0004"):F.status===404?(c.error("[ERROR:0004] participant-details returned 404."),new R("The auth token is not associated with an active participant in this meeting. The meeting may have ended, or the participant may no longer exist. (404)","0004")):F.status>=500?new R(`The server encountered an error. Try again. (${F.status})`,"0001"):F.isHttpError?new R(`Request rejected by the server. (${F.status})`,"0001"):F.isTimeout?new R("Connection timed out. Check the network and try again.","0001"):new R("Unable to connect to the server. Check the internet connection.","0001"):new R((F==null?void 0:F.message)||"Failed to initialize.","0001")}const S=wo.createSocketService(s),y=S.connect();try{await y}catch(F){c.error("[Controller]: Failed to connect to socket server:",{error:F})}const w=_h.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",w);const _=Ch.init(s,w.viewType,m.preset.permissions),C=wo.setupControllers(S,s,m,u,w,_);dO(w)&&((H=wo.createRoomNodeClient(s,S).initializeConnection(m.participant.name,i,!1,_))==null||H.catch(Z=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:Z})}));const{controllers:D}=await C;return X_(),new wo(e,D,s)}static async setupControllers(s,t,e,r,i,n){var Le,x,I;const o=t.getValue("modules"),{participant:c}=e,d=t.getValue("defaults"),l=t.getValue("logger"),{viewType:u,mediaConstraints:{audio:h}}=i;t.setValue("viewType",u),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(Le=h.enableHighBitrate)!=null?Le:!1,enableStereo:(x=h.enableStereo)!=null?x:!1}},...d}),t.setValue("maxPreferredStreams",Te.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let m,S,y,w,_,C,D,V,$;const H=new p1(t,s),F=new $1(s);t.setValue("connectedMeetingsSocketHandler",F);const Z=new Xd(t,s),be=new Zs(t,s),Ge=new T1(s),Ps=new dS(t,s),gn=new y1(t,s),A=new h1(s),T=await xr.init(t,Ps,c,n,i);t.setValue("selfController",T);const P=await Cf.init(t,T.self,Ps,H,r);o.participant&&(V=new rr(t,T.self,Ps)),(I=o.e2ee)!=null&&I.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await ro.init(t,be,T.self,V.participants)),o.internals&&(_=await yh.init(t)),o.livestream&&i.viewType===Ws.Livestream&&(D=new zf(t,T.self,A)),o.poll&&(m=await wf.init(t,T.self,Z)),o.recording&&(C=new Nf(t,T.self,Ps)),o.stage&&(y=new Rf(t,Ge,Ps,T.self,V.participants));const B=new TD(t,gn);if(o.plugin){if(!V)throw new R("The plugin module cannot be initialized without the `participant` module","0102");const Fe=d.plugins||[];w=await Of.init(t,Fe,T.self,B)}if(o.connectedMeetings&&($=await ll.init(t)),o.pip){const Fe=await qu._init(t,T.self);t.setValue("pip",Fe)}return{theme:i,permissions:n,controllers:{storesManager:B,pollController:m,selfController:T,metaController:P,chatController:S,stageController:y,pluginController:w,recordingController:C,internalsController:_,livestreamController:D,participantController:V,connectedMeetingsController:$}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return oS(s,{socket:t,peerId:e})}static createSocketService(s){var d;const{peerId:t,meetingId:e,authToken:r}=s.getAllValues(),o=((d=s.getValue("socketBaseURI"))!=null?d:"").includes("realtime.cloudflare.com")?[]:["PING"];return s.getValue("logger").info(`Socket service capabilities: ${JSON.stringify(o)}`),new bo(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let ul=wo;Kh([E.trace("Controller.init")],ul,"init",1),Kh([E.trace("Controller.createRoomNodeClient")],ul,"createRoomNodeClient",1),Kh([E.trace("Controller.createSocketService")],ul,"createSocketService",1);class J1{constructor(){p(this,"battery");p(this,"logger");p(this,"init",async t=>{this.logger=t;try{"getBattery"in navigator&&(this.battery=await navigator.getBattery(),this.battery.addEventListener("chargingchange",this.updateChargeInfo),this.battery.addEventListener("levelchange",this.updateLevelInfo),this.updateLevelInfo(),this.updateChargeInfo())}catch(e){t.error("Error getting battery",e)}});p(this,"updateChargeInfo",()=>{var t;this.logger.log(`Battery charging? ${(t=this.battery)!=null&&t.charging?"Yes":"No"}`)});p(this,"updateLevelInfo",()=>{if(!this.battery){this.logger.log("Battery level: Not known");return}this.logger.log(`Battery level: ${this.battery.level*100}%`)});p(this,"cleanup",()=>{var t,e;"getBattery"in navigator&&((t=this.battery)==null||t.removeEventListener("chargingchange",this.updateChargeInfo),(e=this.battery)==null||e.removeEventListener("levelchange",this.updateLevelInfo))})}}const DS=new J1;function K1(s,t){s.startsWith("eyJ")||console.error("Invalid auth token provided. Ensure you are passing a %cparticipant `authToken`%c — not an Org API Key or an incorrectly formatted token.\nYou get the participant token from the Add Participant API: https://docs.realtime.cloudflare.com/api#/operations/add_participant","font-weight: bold","font-weight: normal");try{const{meetingId:e,orgId:r,participantId:i}=JSON.parse(atob(s.split(".")[1]));if(!e)throw Error(`Received V1 auth token ${s}`);let n=fi.baseURI.prod;t&&(n=t);const o=`https://${_n({servicePrefix:"api",baseURI:n})}`;return{meetingId:e,orgId:r,participantId:i,baseURI:n,apiBase:o}}catch(e){throw new R("Invalid auth token","0004")}}class z1{constructor(){g(this,ou);g(this,di,new Audio);g(this,un,new MediaStream);g(this,hn,new Map);g(this,Ic,void 0);a(this,di).srcObject=a(this,un),a(this,di).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,hn).has(e.id)||(a(this,un).addTrack(e),a(this,hn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,di).setSinkId(t)}removeTrack(t){const e=a(this,hn).get(t);e&&(a(this,un).removeTrack(e),a(this,hn).delete(t))}async play(){return a(this,di).srcObject=a(this,un),a(this,di).play().catch(t=>{L(this,ou,xv).call(this,t)})}onError(t){f(this,Ic,t)}}di=new WeakMap,un=new WeakMap,hn=new WeakMap,Ic=new WeakMap,ou=new WeakSet,xv=function(t){var e;(e=a(this,Ic))==null||e.call(this,t)};class Y1 extends z1{constructor(){super();g(this,pn,void 0);f(this,pn,new Map)}addParticipantTrack(e,r){a(this,pn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,pn).get(e);r&&this.removeTrack(r),a(this,pn).delete(e)}}pn=new WeakMap;var Q1=Object.defineProperty,X1=Object.getOwnPropertyDescriptor,hl=(s,t,e,r)=>{for(var i=r>1?void 0:r?X1(t,e):t,n=s.length-1,o;n>=0;n--)(o=s[n])&&(i=(r?o(t,e,i):o(i))||i);return r&&i&&Q1(t,e,i),i};let Hr=(ev=class{constructor(t,e){g(this,qe,void 0);g(this,mn,void 0);f(this,mn,t),f(this,qe,e)}get peerId(){return a(this,mn).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:vn(),n=Rr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Xf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var m,S,y,w,_,C,D,V,$;Te.init();const e=(S=(m=t==null?void 0:t.cachedUserDetails)==null?void 0:m.peerId)!=null?S:vn(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=K1(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new R("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Hr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");Fv(l),DS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(_=(w=t.modules)==null?void 0:w.tracing)!=null?_:!0,(D=(C=t==null?void 0:t.modules)==null?void 0:C.devTools)==null?void 0:D.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(V=t.authToken)==null?void 0:V.slice(0,10)}...
18
+ ${($=t.authToken)==null?void 0:$.slice(-10)}`}});const u=await ul.init(c),h=new Hr(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Rr.createContext(t,e),o={...I_,...e==null?void 0:e.modules},c=e.defaults||{audio:!0,video:!0};return n.setValue("options",e),n.setValue("peerId",t),n.setValue("modules",o),n.setValue("sdkName","web-core"),n.setValue("meetingId",r),n.setValue("apiBase",i.apiBase),n.setValue("baseURI",i.baseURI),n.setValue("userId",i.participantId),n.setValue("organizationId",i.orgId),n.setValue("authToken",e.authToken),n.setValue("overrides",(d=e.overrides)!=null?d:{}),n.setValue("env",A_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Is(e.cachedUserDetails)),n.setValue("sdkVersion","2.0.2-staging.7"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new Y1),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){var r;DS.cleanup(),a(this,mn).getValue("peerSessionStore").reset(),(r=a(this,qe).pluginController)==null||r.cleanup();const{selfController:e}=a(this,qe);return e.leaveRoom(t)}get participants(){var t;return(t=a(this,qe).participantController)==null?void 0:t.participants}get self(){var t;return(t=a(this,qe).selfController)==null?void 0:t.self}get meta(){var t;return(t=a(this,qe).metaController)==null?void 0:t.meta}get ai(){var t;return(t=a(this,qe).metaController)==null?void 0:t.ai}get plugins(){var t;return(t=a(this,qe).pluginController)==null?void 0:t.plugins}get chat(){var t;return(t=a(this,qe).chatController)==null?void 0:t.chat}get polls(){var t;return(t=a(this,qe).pollController)==null?void 0:t.polls}get connectedMeetings(){var t;return(t=a(this,qe).connectedMeetingsController)==null?void 0:t.connectedMeetings}get recording(){var t;return(t=a(this,qe).recordingController)==null?void 0:t.recording}get livestream(){var t;return(t=a(this,qe).livestreamController)==null?void 0:t.livestream}get stage(){var t;return(t=a(this,qe).stageController)==null?void 0:t.stage}get stores(){return a(this,qe).storesManager}get audio(){return a(this,mn).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}},qe=new WeakMap,mn=new WeakMap,ev);hl([lt("0002"),tr.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Hr.prototype,"join",1),hl([lt("0003")],Hr.prototype,"leave",1),hl([lt("0001"),tr.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Hr,"init",1),Hr=hl([lt("0000")],Hr);const NS=Hr;return NS}();