@cloudflare/realtimekit 1.5.2-staging.1 → 1.5.2-staging.2
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/EncryptionManager.d.ts +108 -298
- package/dist/browser.js +13 -13
- package/dist/dependencies.txt +1 -1
- package/dist/index.cjs.js +10 -10
- package/dist/index.d.ts +117 -306
- package/dist/index.es.js +6602 -7271
- package/dist/index.es5.js +9533 -10069
- package/dist/index.rn.js +10 -10
- package/dist/ts3.4/dist/EncryptionManager.d.ts +105 -295
- package/dist/ts3.4/dist/index.d.ts +112 -302
- package/package.json +1 -1
package/dist/browser.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
var RealtimeKitClient=function(){var ko,dr,lr,CS,ss,Ai,lt,rs,Oe,ws,ur,Et,Ue,$n,Bn,hr,Fn,qt,Hn,te,Mi,Qe,qn,pl,KS,Ro,zh,IS,Di,AS,ml,zS,gl,YS,jn,Gn,Co,MS,Jr,Wn,Oi,DS,Jn,Io,Yh,Ni,Ao,OS,Mo,NS,Kr,Kn,jt,VS,is,fl,ne,Do,Bs,Xe,Oo,Qh,zn,au,zr,Ps,Yr,No,bt,ut,Gt,Yn,Qn,pr,Xn,Qr,Zn,LS,$e,Vi,ns,ea,_s,xS,Vo,ta,sa,ra,ou,US,Li,xi,Ge,ye,me,mr,as,Lo,Ne,Ui,xo,$i,Sl,ia,os,Ze,$S,Bi,Uo,na,$o,wt,Fi,Bo,aa,ca,Fo,da,la,gr,Fs,ht,Xr,Zr,vl,QS,Hi,qi,Ho,Xh,qo,ei,Tl,XS,ua,ha,Wt,ji,jc,ti,qa,Gi,Gc,yl,ZS,fr,jo,si,Wi,Wc,Sr,El,Go,Zh,bl,ev,wl,tv,BS,ri,Re,Wo,ep,Ji,Jc,pa,cu,Ki,Dt,FS,cs,ks,ma,HS,q,ga,fa,Pl,Pt,Yt,Jt,va,_t,Ta,et,vr,Sn,tt,ft,ya,du,Be,Ke,Ea,ba,Jo,tp,qS,Ko,st,zo,Yo,zi,Hs,_l,qs,ui,Qo,sp,kl,sv,Rl,rv,Rs,wa,Pa,Yi,ds,at,ii,_a,Cl,Kt,Ns,ni,Il,Qi,Xi,Tr,Zi,Ca,pt,mt,Xo,Zo,en,Ia,ec,Aa,tn,js,Ma,lu,tc,rp,Al,iv,sc,ip,Ml,nv,Dl,av,Ol,ov,Nl,cv,Vl,dv,rc,np,ic,ap,Ll,ls,sn,ai,Da,nc,Gs,xl,yr,Oa,ac,op,Ul,lv,$l,uv,Bl,hv,Fl,pv,oc,cc,dc,Na,Va,La,lc,uc,xa,Ot,Cs,Is,rn,nn,Er,hc,Hl,mv,ql,gv,jl,fv,Gl,Sv,pc,mc,br,wr,Pr,gc,Ua,$a,oi,an,Ba,on,_r,Ws,Jl,vv,fc,cp,Kl,Tv,zl,yv,vc,Tc,gt,G,Yl,kt,cn,dn,ln,yc,us,kr,Rt,Nt,ci,ja,Ql,Ev,Xl,bv,Zl,wv,Ec,dp,eu,Pv,tu,_v,Ct,Qt,un,Kc,su,kv,ru,Rv,iu,Cv,Fa,As,Z,Vt,ps,jS,bc,wc,Pc,Rr,Ha,zt,Lt,We,_c,di,Ce,Ie,He,hs,rt,kc,lp,Rc,up,GS,Ms,ge,WS,li,hn,pn,Cc,nu,Iv,mn,Je,gn,JS;"use strict";var ZO=Object.defineProperty;var eN=(_e,Ee,ke)=>Ee in _e?ZO(_e,Ee,{enumerable:!0,configurable:!0,writable:!0,value:ke}):_e[Ee]=ke;var p=(_e,Ee,ke)=>(eN(_e,typeof Ee!="symbol"?Ee+"":Ee,ke),ke),Kh=(_e,Ee,ke)=>{if(!Ee.has(_e))throw TypeError("Cannot "+ke)};var a=(_e,Ee,ke)=>(Kh(_e,Ee,"read from private field"),ke?ke.call(_e):Ee.get(_e)),g=(_e,Ee,ke)=>{if(Ee.has(_e))throw TypeError("Cannot add the same private member more than once");Ee instanceof WeakSet?Ee.add(_e):Ee.set(_e,ke)},f=(_e,Ee,ke,zc)=>(Kh(_e,Ee,"write to private field"),zc?zc.call(_e,ke):Ee.set(_e,ke),ke);var U=(_e,Ee,ke)=>(Kh(_e,Ee,"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 Ee(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:Ee});var ke,zc=new Uint8Array(16);function Av(){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(zc)}const Mv=/^(?:[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 uu(s){return typeof s=="string"&&Mv.test(s)}for(var nt=[],hu=0;hu<256;++hu)nt.push((hu+256).toString(16).substr(1));function Dv(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(nt[s[t+0]]+nt[s[t+1]]+nt[s[t+2]]+nt[s[t+3]]+"-"+nt[s[t+4]]+nt[s[t+5]]+"-"+nt[s[t+6]]+nt[s[t+7]]+"-"+nt[s[t+8]]+nt[s[t+9]]+"-"+nt[s[t+10]]+nt[s[t+11]]+nt[s[t+12]]+nt[s[t+13]]+nt[s[t+14]]+nt[s[t+15]]).toLowerCase();if(!uu(e))throw TypeError("Stringified UUID is invalid");return e}function vn(s,t,e){s=s||{};var r=s.random||(s.rng||Av)();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 Dv(r)}const Ov=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")}))},Nv={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},hp={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Ve={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},St={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Ir={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class M{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(r=>parseInt(r,10)||0);if(e.push(0),e[0]===10)switch(e[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(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=M.getVersionPrecision(t),n=M.getVersionPrecision(e);let o=Math.max(i,n),c=0;const d=M.map([t,e],l=>{const u=o-M.getVersionPrecision(l),h=l+new Array(u+1).join(".0");return M.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 Nv[t]}static getBrowserTypeByAlias(t){return hp[t]||""}}const de=/version\/(\d+(\.?_?\d+)+)/i,Vv=[{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=M.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=M.getFirstMatch(de,s)||M.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=M.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=M.getFirstMatch(de,s)||M.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=M.getFirstMatch(de,s)||M.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=M.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=M.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=M.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=M.getFirstMatch(de,s)||M.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=M.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=M.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=M.getFirstMatch(de,s)||M.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=M.getFirstMatch(de,s)||M.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=M.getFirstMatch(de,s)||M.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=M.getFirstMatch(de,s)||M.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=M.getFirstMatch(de,s)||M.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=M.getFirstMatch(de,s)||M.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=M.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(de,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=M.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=M.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=M.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=M.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=M.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=M.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=M.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=M.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=M.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=M.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=M.getFirstMatch(de,s)||M.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=M.getFirstMatch(de,s)||M.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=M.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=M.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=M.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=M.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=M.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=M.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=M.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=M.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=M.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=M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=M.getFirstMatch(de,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,i=s.search("\\(")!==-1?e:t;return{name:M.getFirstMatch(i,s),version:M.getSecondMatch(i,s)}}}],Lv=[{test:[/Roku\/DVP/],describe(s){const t=M.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:St.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=M.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:St.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=M.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=M.getWindowsVersionName(t);return{name:St.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:St.iOS},e=M.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=M.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=M.getMacOSVersionName(t),r={name:St.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=M.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:St.iOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=M.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=M.getAndroidVersionName(t),r={name:St.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=M.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:St.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=M.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||M.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||M.getFirstMatch(/\bbb(\d+)/i,s);return{name:St.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=M.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:St.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=M.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:St.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:St.Linux}}},{test:[/CrOS/],describe(){return{name:St.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=M.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:St.PlayStation4,version:t}}}],xv=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(s){const t=M.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Ve.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Ve.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Ve.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Ve.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Ve.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Ve.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Ve.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=M.getFirstMatch(/(ipod|iphone)/i,s);return{type:Ve.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Ve.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Ve.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Ve.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Ve.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Ve.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Ve.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Ve.mobile}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Ve.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Ve.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Ve.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Ve.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Ve.tv}}}],Uv=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:Ir.Blink};const e=M.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Ir.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:Ir.Trident},e=M.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:Ir.Presto},e=M.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:Ir.Gecko},e=M.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Ir.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:Ir.WebKit},e=M.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class pp{constructor(t,e=!1){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t,this.parsedResult={},e!==!0&&this.parse()}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=M.find(Vv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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.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=M.find(Lv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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=M.find(xv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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=M.find(Uv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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 M.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=M.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(e[d]);if(u!==void 0)return u}const l=M.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=M.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=M.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(M.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 vo,rr,ir,vS,Yt,bi,ot,Qt,Me,gs,nr,ft,xe,Vn,Ln,ar,xn,$t,Un,Z,Pi,Ke,$n,il,US,To,Bh,TS,_i,yS,nl,$S,al,BS,Bn,Fn,yo,ES,$r,Hn,Ci,wS,qn,Eo,Fh,ki,wo,bS,bo,PS,Br,jn,Bt,_S,Xt,ol,re,Po,Ms,ze,_o,Hh,Gn,Ql,Fr,fs,Hr,Co,St,Ri,Wn,ko,Ro,Ii,CS,Ue,Ai,Mi,Io,Oi,kS,Ao,Jn,Kn,zn,Xl,RS,Di,Ni,He,Te,pe,or,Zt,Mo,Oe,Vi,Oo,Li,cl,Yn,es,Ye,IS,xi,Do,Qn,No,vt,Ui,Vo,Xn,ea,Lo,ta,sa,cr,Os,st,qr,jr,dl,FS,Gr,Wr,xo,qh,Uo,Ss,ll,HS,ra,ia,Ft,$i,Uc,Jr,La,Bi,$c,ul,qS,dr,$o,Kr,Fi,Bc,lr,hl,Bo,jh,pl,jS,ml,GS,AS,zr,Ce,Fo,Gh,Hi,Fc,na,Zl,qi,kt,MS,ts,vs,aa,OS,j,oa,ca,gl,Tt,Gt,Ht,la,yt,ua,Qe,ur,pn,Xe,ht,ha,eu,$e,je,pa,ma,Ho,Wh,DS,qo,Ze,jo,Go,ji,Ds,fl,Ns,ii,Wo,Jh,Sl,WS,vl,JS,Ts,ga,fa,Gi,ss,rt,Yr,Sa,Tl,qt,_s,Qr,yl,Wi,Ji,hr,Ki,ya,ct,dt,Jo,Ko,zi,Ea,zo,wa,Yi,Vs,ba,tu,Yo,Kh,El,KS,Qo,zh,wl,zS,bl,YS,Pl,QS,_l,XS,Cl,ZS,Xo,Yh,Zo,Qh,kl,rs,Qi,Xr,Pa,ec,Ls,Rl,pr,_a,tc,Xh,Il,ev,Al,tv,Ml,sv,Ol,rv,sc,rc,ic,Ca,ka,Ra,nc,ac,Ia,Rt,ys,Es,Xi,Zi,mr,oc,Dl,iv,Nl,nv,Vl,av,Ll,ov,cc,dc,gr,fr,Sr,lc,Aa,Ma,Zr,en,Oa,tn,vr,xs,Ul,cv,uc,Zh,$l,dv,Bl,lv,pc,mc,lt,G,Fl,Et,sn,rn,nn,gc,is,Tr,wt,It,ei,xa,Hl,uv,ql,hv,jl,pv,fc,ep,Gl,mv,Wl,gv,bt,Wt,an,Hc,Jl,fv,Kl,Sv,zl,vv,Da,ws,Q,At,as,NS,Sc,vc,Tc,yr,Na,jt,Mt,ti,Va,si,ke,Re,Fe,ns,et,yc,tp,Ec,sp,VS,bs,me,LS,ri,on,cn,wc,Yl,Tv,dn,qe,ln,xS;"use strict";var L1=Object.defineProperty;var x1=(Pe,ye,_e)=>ye in Pe?L1(Pe,ye,{enumerable:!0,configurable:!0,writable:!0,value:_e}):Pe[ye]=_e;var p=(Pe,ye,_e)=>(x1(Pe,typeof ye!="symbol"?ye+"":ye,_e),_e),$h=(Pe,ye,_e)=>{if(!ye.has(Pe))throw TypeError("Cannot "+_e)};var a=(Pe,ye,_e)=>($h(Pe,ye,"read from private field"),_e?_e.call(Pe):ye.get(Pe)),g=(Pe,ye,_e)=>{if(ye.has(Pe))throw TypeError("Cannot add the same private member more than once");ye instanceof WeakSet?ye.add(Pe):ye.set(Pe,_e)},f=(Pe,ye,_e,qc)=>($h(Pe,ye,"write to private field"),qc?qc.call(Pe,_e):ye.set(Pe,_e),_e);var $=(Pe,ye,_e)=>($h(Pe,ye,"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 ye(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:ye});var _e,qc=new Uint8Array(16);function yv(){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 Ev=/^(?:[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 su(s){return typeof s=="string"&&Ev.test(s)}for(var tt=[],ru=0;ru<256;++ru)tt.push((ru+256).toString(16).substr(1));function wv(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(tt[s[t+0]]+tt[s[t+1]]+tt[s[t+2]]+tt[s[t+3]]+"-"+tt[s[t+4]]+tt[s[t+5]]+"-"+tt[s[t+6]]+tt[s[t+7]]+"-"+tt[s[t+8]]+tt[s[t+9]]+"-"+tt[s[t+10]]+tt[s[t+11]]+tt[s[t+12]]+tt[s[t+13]]+tt[s[t+14]]+tt[s[t+15]]).toLowerCase();if(!su(e))throw TypeError("Stringified UUID is invalid");return e}function mn(s,t,e){s=s||{};var r=s.random||(s.rng||yv)();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 wv(r)}const bv=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")}))},Pv={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},rp={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Ne={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},pt={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Er={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class M{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(r=>parseInt(r,10)||0);if(e.push(0),e[0]===10)switch(e[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(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=M.getVersionPrecision(t),n=M.getVersionPrecision(e);let o=Math.max(i,n),c=0;const d=M.map([t,e],l=>{const u=o-M.getVersionPrecision(l),h=l+new Array(u+1).join(".0");return M.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 Pv[t]}static getBrowserTypeByAlias(t){return rp[t]||""}}const ce=/version\/(\d+(\.?_?\d+)+)/i,_v=[{test:[/googlebot/i],describe(s){const t={name:"Googlebot"},e=M.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/opera/i],describe(s){const t={name:"Opera"},e=M.getFirstMatch(ce,s)||M.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/opr\/|opios/i],describe(s){const t={name:"Opera"},e=M.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/SamsungBrowser/i],describe(s){const t={name:"Samsung Internet for Android"},e=M.getFirstMatch(ce,s)||M.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=M.getFirstMatch(ce,s)||M.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MZBrowser/i],describe(s){const t={name:"MZ Browser"},e=M.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/focus/i],describe(s){const t={name:"Focus"},e=M.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/swing/i],describe(s){const t={name:"Swing"},e=M.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/coast/i],describe(s){const t={name:"Opera Coast"},e=M.getFirstMatch(ce,s)||M.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=M.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/yabrowser/i],describe(s){const t={name:"Yandex Browser"},e=M.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/ucbrowser/i],describe(s){const t={name:"UC Browser"},e=M.getFirstMatch(ce,s)||M.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/Maxthon|mxios/i],describe(s){const t={name:"Maxthon"},e=M.getFirstMatch(ce,s)||M.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/epiphany/i],describe(s){const t={name:"Epiphany"},e=M.getFirstMatch(ce,s)||M.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/puffin/i],describe(s){const t={name:"Puffin"},e=M.getFirstMatch(ce,s)||M.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sleipnir/i],describe(s){const t={name:"Sleipnir"},e=M.getFirstMatch(ce,s)||M.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=M.getFirstMatch(ce,s)||M.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/micromessenger/i],describe(s){const t={name:"WeChat"},e=M.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(ce,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=M.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/msie|trident/i],describe(s){const t={name:"Internet Explorer"},e=M.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/\sedg\//i],describe(s){const t={name:"Microsoft Edge"},e=M.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=M.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/vivaldi/i],describe(s){const t={name:"Vivaldi"},e=M.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/seamonkey/i],describe(s){const t={name:"SeaMonkey"},e=M.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/sailfish/i],describe(s){const t={name:"Sailfish"},e=M.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=M.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/phantom/i],describe(s){const t={name:"PhantomJS"},e=M.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/slimerjs/i],describe(s){const t={name:"SlimerJS"},e=M.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=M.getFirstMatch(ce,s)||M.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=M.getFirstMatch(ce,s)||M.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=M.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/tizen/i],describe(s){const t={name:"Tizen"},e=M.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/qupzilla/i],describe(s){const t={name:"QupZilla"},e=M.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/firefox|iceweasel|fxios/i],describe(s){const t={name:"Firefox"},e=M.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=M.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/MiuiBrowser/i],describe(s){const t={name:"Miui"},e=M.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/chromium/i],describe(s){const t={name:"Chromium"},e=M.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,s)||M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/chrome|crios|crmo/i],describe(s){const t={name:"Chrome"},e=M.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=M.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=M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/playstation 4/i],describe(s){const t={name:"PlayStation 4"},e=M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/safari|applewebkit/i],describe(s){const t={name:"Safari"},e=M.getFirstMatch(ce,s);return e&&(t.version=e),t}},{test:[/.*/i],describe(s){const t=/^(.*)\/(.*) /,e=/^(.*)\/(.*)[ \t]\((.*)/,i=s.search("\\(")!==-1?e:t;return{name:M.getFirstMatch(i,s),version:M.getSecondMatch(i,s)}}}],Cv=[{test:[/Roku\/DVP/],describe(s){const t=M.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,s);return{name:pt.Roku,version:t}}},{test:[/windows phone/i],describe(s){const t=M.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,s);return{name:pt.WindowsPhone,version:t}}},{test:[/windows /i],describe(s){const t=M.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,s),e=M.getWindowsVersionName(t);return{name:pt.Windows,version:t,versionName:e}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(s){const t={name:pt.iOS},e=M.getSecondMatch(/(Version\/)(\d[\d.]+)/,s);return e&&(t.version=e),t}},{test:[/macintosh/i],describe(s){const t=M.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,s).replace(/[_\s]/g,"."),e=M.getMacOSVersionName(t),r={name:pt.MacOS,version:t};return e&&(r.versionName=e),r}},{test:[/(ipod|iphone|ipad)/i],describe(s){const t=M.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,s).replace(/[_\s]/g,".");return{name:pt.iOS,version:t}}},{test(s){const t=!s.test(/like android/i),e=s.test(/android/i);return t&&e},describe(s){const t=M.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,s),e=M.getAndroidVersionName(t),r={name:pt.Android,version:t};return e&&(r.versionName=e),r}},{test:[/(web|hpw)[o0]s/i],describe(s){const t=M.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,s),e={name:pt.WebOS};return t&&t.length&&(e.version=t),e}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(s){const t=M.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,s)||M.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,s)||M.getFirstMatch(/\bbb(\d+)/i,s);return{name:pt.BlackBerry,version:t}}},{test:[/bada/i],describe(s){const t=M.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,s);return{name:pt.Bada,version:t}}},{test:[/tizen/i],describe(s){const t=M.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,s);return{name:pt.Tizen,version:t}}},{test:[/linux/i],describe(){return{name:pt.Linux}}},{test:[/CrOS/],describe(){return{name:pt.ChromeOS}}},{test:[/PlayStation 4/],describe(s){const t=M.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,s);return{name:pt.PlayStation4,version:t}}}],kv=[{test:[/googlebot/i],describe(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe(s){const t=M.getFirstMatch(/(can-l01)/i,s)&&"Nova",e={type:Ne.mobile,vendor:"Huawei"};return t&&(e.model=t),e}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe(){return{type:Ne.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe(){return{type:Ne.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(){return{type:Ne.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe(){return{type:Ne.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe(){return{type:Ne.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe(){return{type:Ne.tablet}}},{test(s){const t=s.test(/ipod|iphone/i),e=s.test(/like (ipod|iphone)/i);return t&&!e},describe(s){const t=M.getFirstMatch(/(ipod|iphone)/i,s);return{type:Ne.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe(){return{type:Ne.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe(){return{type:Ne.mobile}}},{test(s){return s.getBrowserName(!0)==="blackberry"},describe(){return{type:Ne.mobile,vendor:"BlackBerry"}}},{test(s){return s.getBrowserName(!0)==="bada"},describe(){return{type:Ne.mobile}}},{test(s){return s.getBrowserName()==="windows phone"},describe(){return{type:Ne.mobile,vendor:"Microsoft"}}},{test(s){const t=Number(String(s.getOSVersion()).split(".")[0]);return s.getOSName(!0)==="android"&&t>=3},describe(){return{type:Ne.tablet}}},{test(s){return s.getOSName(!0)==="android"},describe(){return{type:Ne.mobile}}},{test(s){return s.getOSName(!0)==="macos"},describe(){return{type:Ne.desktop,vendor:"Apple"}}},{test(s){return s.getOSName(!0)==="windows"},describe(){return{type:Ne.desktop}}},{test(s){return s.getOSName(!0)==="linux"},describe(){return{type:Ne.desktop}}},{test(s){return s.getOSName(!0)==="playstation 4"},describe(){return{type:Ne.tv}}},{test(s){return s.getOSName(!0)==="roku"},describe(){return{type:Ne.tv}}}],Rv=[{test(s){return s.getBrowserName(!0)==="microsoft edge"},describe(s){if(/\sedg\//i.test(s))return{name:Er.Blink};const e=M.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,s);return{name:Er.EdgeHTML,version:e}}},{test:[/trident/i],describe(s){const t={name:Er.Trident},e=M.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test(s){return s.test(/presto/i)},describe(s){const t={name:Er.Presto},e=M.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:Er.Gecko},e=M.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}},{test:[/(apple)?webkit\/537\.36/i],describe(){return{name:Er.Blink}}},{test:[/(apple)?webkit/i],describe(s){const t={name:Er.WebKit},e=M.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,s);return e&&(t.version=e),t}}];class ip{constructor(t,e=!1){if(t==null||t==="")throw new Error("UserAgent parameter can't be empty");this._ua=t,this.parsedResult={},e!==!0&&this.parse()}getUA(){return this._ua}test(t){return t.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const t=M.find(_v,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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.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=M.find(Cv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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=M.find(kv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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=M.find(Rv,e=>{if(typeof e.test=="function")return e.test(this);if(e.test instanceof Array)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 M.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=M.find(c,u=>this.isOS(u));if(d){const u=this.satisfies(e[d]);if(u!==void 0)return u}const l=M.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=M.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=M.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(M.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/lancedikson/bowser
|
|
4
4
|
* MIT License | (c) Dustin Diaz 2012-2015
|
|
5
5
|
* MIT License | (c) Denis Demchenko 2015-2019
|
|
6
|
-
*/class mp{static getParser(t,e=!1){if(typeof t!="string")throw new Error("UserAgent should be a string");return new pp(t,e)}static parse(t){return new pp(t).getResult()}static get BROWSER_MAP(){return hp}static get ENGINE_MAP(){return Ir}static get OS_MAP(){return St}static get PLATFORMS_MAP(){return Ve}}const Ga="chrome",gp="opera",fp="firefox",Sp="iexplorer",vp="safari",Tp="nwjs",yp="electron",Ep="react-native",pu="unknown",Yc={Chrome:Ga,Chromium:Ga,Opera:gp,Firefox:fp,"Internet Explorer":Sp,Safari:vp};function $v(){const{userAgent:s}=navigator,t={name:pu,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=Ga,t.version=e)}else t.name=Ga,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function Bv(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:yp,version:t}}return null}function Fv(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:Tp,version:t}}}function Hv(){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:Ep,version:t}}function qv(s){let t;const e=[Hv,Bv,Fv];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in Yc?{name:Yc[r],version:s.getBrowserVersion()}:(t=$v(),t||{name:pu,version:void 0})}class jv{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=mp.getParser(navigator.userAgent),typeof t=="undefined"){const i=qv(this._bowser);e=i.name,r=i.version}else t.name in Yc?(e=Yc[t.name],r=t.version):(e=pu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===Ga}isOpera(){return this._name===gp}isFirefox(){return this._name===fp}isIExplorer(){return this._name===Sp}isSafari(){return this._name===vp}isNWJS(){return this._name===Tp}isElectron(){return this._name===yp}isReactNative(){return this._name===Ep||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 Gv extends jv{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 fe=new Gv;var ot={},Wv={get exports(){return ot},set exports(s){ot=s}},Tn=typeof Reflect=="object"?Reflect:null,bp=Tn&&typeof Tn.apply=="function"?Tn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Qc;Tn&&typeof Tn.ownKeys=="function"?Qc=Tn.ownKeys:Object.getOwnPropertySymbols?Qc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Qc=function(t){return Object.getOwnPropertyNames(t)};function Jv(s){console&&console.warn&&console.warn(s)}var wp=Number.isNaN||function(t){return t!==t};function ae(){ae.init.call(this)}Wv.exports=ae,ot.once=Qv,ae.EventEmitter=ae,ae.prototype._events=void 0,ae.prototype._eventsCount=0,ae.prototype._maxListeners=void 0;var Pp=10;function Xc(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ae,"defaultMaxListeners",{enumerable:!0,get:function(){return Pp},set:function(s){if(typeof s!="number"||s<0||wp(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Pp=s}}),ae.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},ae.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||wp(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 _p(s){return s._maxListeners===void 0?ae.defaultMaxListeners:s._maxListeners}ae.prototype.getMaxListeners=function(){return _p(this)},ae.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")bp(d,this,e);else for(var l=d.length,u=Ap(d,l),r=0;r<l;++r)bp(u[r],this,e);return!0};function kp(s,t,e,r){var i,n,o;if(Xc(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=_p(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,Jv(c)}return s}ae.prototype.addListener=function(t,e){return kp(this,t,e,!1)},ae.prototype.on=ae.prototype.addListener,ae.prototype.prependListener=function(t,e){return kp(this,t,e,!0)};function Kv(){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 Rp(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=Kv.bind(r);return i.listener=e,r.wrapFn=i,i}ae.prototype.once=function(t,e){return Xc(e),this.on(t,Rp(this,t,e)),this},ae.prototype.prependOnceListener=function(t,e){return Xc(e),this.prependListener(t,Rp(this,t,e)),this},ae.prototype.removeListener=function(t,e){var r,i,n,o,c;if(Xc(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():zv(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},ae.prototype.off=ae.prototype.removeListener,ae.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 Cp(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?Yv(i):Ap(i,i.length)}ae.prototype.listeners=function(t){return Cp(this,t,!0)},ae.prototype.rawListeners=function(t){return Cp(this,t,!1)},ae.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):Ip.call(s,t)},ae.prototype.listenerCount=Ip;function Ip(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}ae.prototype.eventNames=function(){return this._eventsCount>0?Qc(this._events):[]};function Ap(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function zv(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function Yv(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function Qv(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))}Mp(s,t,n,{once:!0}),t!=="error"&&Xv(s,i,{once:!0})})}function Xv(s,t,e){typeof s.on=="function"&&Mp(s,"error",t,e)}function Mp(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 J;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(J||(J={}));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 Zv=new Map([[N.PRECALL_TEST_BEGIN,J.MINOR_EVENT],[N.PRECALL_TEST_COMPLETE,J.MINOR_EVENT],[N.CALL_JOIN_BEGIN,J.MAJOR_EVENT],[N.NET_QUALITY_TEST_BEGIN,J.MINOR_EVENT],[N.NET_QUALITY_TEST_END,J.MINOR_EVENT],[N.WEBSOCKET_CONNECTED,J.MINOR_EVENT],[N.TRANSPORT_CONNECTED,J.MAJOR_EVENT],[N.AUDIO_ON,J.MINOR_EVENT],[N.AUDIO_OFF,J.MINOR_EVENT],[N.VIDEO_ON,J.MINOR_EVENT],[N.VIDEO_OFF,J.MINOR_EVENT],[N.PARTICIPANT_ROLE,J.MINOR_EVENT],[N.PING_STAT,J.MAJOR_EVENT],[N.DISCONNECT,J.MAJOR_EVENT],[N.RECONNECT_ATTEMPT,J.MAJOR_EVENT],[N.SCREENSHARE_START_REQUESTED,J.MINOR_EVENT],[N.SCREENSHARE_STARTED,J.MINOR_EVENT],[N.SCREENSHARE_STOPPED,J.MINOR_EVENT],[N.TAB_CHANGE,J.MINOR_EVENT],[N.BROWSER_BACKGROUNDED,J.MINOR_EVENT],[N.BROWSER_FOREGROUNDED,J.MINOR_EVENT],[N.DOMINANT_SPEAKER,J.MINOR_EVENT],[N.AUDIO_DEVICES_UPDATES,J.MINOR_EVENT],[N.VIDEO_DEVICES_UPDATES,J.MINOR_EVENT],[N.SPEAKER_DEVICES_UPDATES,J.MINOR_EVENT],[N.SELECTED_MICROHPONE_UPDATE,J.MINOR_EVENT],[N.SELECTED_CAMERA_UPDATE,J.MINOR_EVENT],[N.SELECTED_SPEAKER_UPDATE,J.MINOR_EVENT],[N.MEDIA_PERMISSION,J.MINOR_EVENT],[N.LEGACY_SWITCH,J.MINOR_EVENT],[N.AUDIO_PLAY_FAILED,J.MINOR_EVENT],[N.VIDEO_PLAY_FAILED,J.MINOR_EVENT],[N.AUDIO_TRACK_MUTED,J.MINOR_EVENT],[N.VIDEO_TRACK_MUTED,J.MINOR_EVENT],[N.IVS_PLAYER_REBUFFERING,J.MAJOR_EVENT],[N.IVS_PLAYER_AUDIO_BLOCKED,J.MAJOR_EVENT],[N.IVS_PLAYER_PLAYBACK_BLOCKED,J.MAJOR_EVENT],[N.IVS_PLAYER_ERROR,J.MAJOR_EVENT],[N.IVS_PLAYER_RECOVERABLE_ERROR,J.MAJOR_EVENT],[N.IVS_PLAYER_WORKER_ERROR,J.MAJOR_EVENT],[N.IVS_PLAYER_NETWORK_UNAVAILABLE,J.MAJOR_EVENT],[N.LIVESTREAM_LATENCY,J.MAJOR_EVENT],[N.IVS_PLAYER_ANALYTICS_EVENT,J.MINOR_EVENT],[N.IVS_PLAYER_PLAYBACK_RATE_CHANGED,J.MINOR_EVENT],[N.IVS_PLAYER_QUALITY_CHANGED,J.MINOR_EVENT],[N.IVS_PLAYER_INITIALIZED,J.MINOR_EVENT],[N.EXPECTED_VIDEO_RESOLUTION,J.MINOR_EVENT],[N.EXPECTED_SCREENSHARE_RESOLUTION,J.MINOR_EVENT]]);class eT{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class tT extends ot{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 eT}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),Zv.get(e.event)===J.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 Dp;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(Dp||(Dp={}));const Op={DEVEL:"devel",PREPROD:"preprod",PROD:"prod"};var Xt;(function(s){s.AUDIO="AUDIO",s.VIDEO="VIDEO",s.SPEAKER="SPEAKER",s.SCREENSHARE="SCREENSHARE"})(Xt||(Xt={}));var Np;(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"})(Np||(Np={}));function Ar(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Zc({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function ed({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Vp=240,Lp=720,xp=8,Up=3,td=10,sd=.02,rd=.03;function Js({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 $p({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 Bp({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Fp({packetsLost:s,packetsSent:t,jitter:e}){const i=Js({stat:Bp({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:td,rangeRankingDirection:"UP"}),o=Js({stat:e,weight:.3,rangeMin:sd,rangeMax:rd,rangeRankingDirection:"UP"});return i+o}function sT({frameWidth:s,isScreenShare:t}){return s<(t?Lp:Vp)}function rT({framesPerSecond:s,isScreenShare:t}){return s<(t?Up:xp)}function iT({framesEncoded:s}){return s===0}function Hp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=Js({stat:Bp({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:td,rangeRankingDirection:"UP"}),d=Js({stat:i,weight:1,rangeMin:sd,rangeMax:rd,rangeRankingDirection:"UP"}),l=sT({frameWidth:s,isScreenShare:n}),u=rT({framesPerSecond:t,isScreenShare:n}),h=iT({framesEncoded:o,isScreenShare:n});return $p({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function qp({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function jp({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=Js({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=Js({stat:qp({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:td,rangeRankingDirection:"UP"}),l=Js({stat:r,weight:.3,rangeMin:sd,rangeMax:rd,rangeRankingDirection:"UP"});return n+c+l}function nT({framesDecoded:s}){return s===0}function aT({framesPerSecond:s,isScreenShare:t}){return s<(t?Up:xp)}function oT({frameWidth:s,isScreenShare:t}){return s<(t?Lp:Vp)}function Gp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=Js({stat:qp({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:td,rangeRankingDirection:"UP"}),d=Js({stat:i,weight:1,rangeMin:sd,rangeMax:rd,rangeRankingDirection:"UP"}),l=oT({frameWidth:s,isScreenShare:n}),u=aT({framesPerSecond:t,isScreenShare:n}),h=nT({framesDecoded:o,isScreenShare:n});return $p({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class Ks{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=Ks.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=Ks.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 np{static getParser(t,e=!1){if(typeof t!="string")throw new Error("UserAgent should be a string");return new ip(t,e)}static parse(t){return new ip(t).getResult()}static get BROWSER_MAP(){return rp}static get ENGINE_MAP(){return Er}static get OS_MAP(){return pt}static get PLATFORMS_MAP(){return Ne}}const Ua="chrome",ap="opera",op="firefox",cp="iexplorer",dp="safari",lp="nwjs",up="electron",hp="react-native",iu="unknown",jc={Chrome:Ua,Chromium:Ua,Opera:ap,Firefox:op,"Internet Explorer":cp,Safari:dp};function Iv(){const{userAgent:s}=navigator,t={name:iu,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=Ua,t.version=e)}else t.name=Ua,t.version=s.match(/Chrome\/([\d.]+)/)[1];return t}function Av(){const{userAgent:s}=navigator;if(s.match(/Electron/)){const t=s.match(/Electron\/([\d.]+)/)[1];return{name:up,version:t}}return null}function Mv(){const{userAgent:s}=navigator;if(s.match(/JitsiMeetNW/)){const t=s.match(/JitsiMeetNW\/([\d.]+)/)[1];return{name:lp,version:t}}}function Ov(){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:hp,version:t}}function Dv(s){let t;const e=[Ov,Av,Mv];for(let i=0;i<e.length;i+=1)if(t=e[i](),t)return t;const r=s.getBrowserName();return r in jc?{name:jc[r],version:s.getBrowserVersion()}:(t=Iv(),t||{name:iu,version:void 0})}class Nv{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=np.getParser(navigator.userAgent),typeof t=="undefined"){const i=Dv(this._bowser);e=i.name,r=i.version}else t.name in jc?(e=jc[t.name],r=t.version):(e=iu,r=void 0);this._name=e,this._version=r}getName(){return this._name}isChrome(){return this._name===Ua}isOpera(){return this._name===ap}isFirefox(){return this._name===op}isIExplorer(){return this._name===cp}isSafari(){return this._name===dp}isNWJS(){return this._name===lp}isElectron(){return this._name===up}isReactNative(){return this._name===hp||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 Vv extends Nv{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 ge=new Vv;var it={},Lv={get exports(){return it},set exports(s){it=s}},gn=typeof Reflect=="object"?Reflect:null,pp=gn&&typeof gn.apply=="function"?gn.apply:function(t,e,r){return Function.prototype.apply.call(t,e,r)},Gc;gn&&typeof gn.ownKeys=="function"?Gc=gn.ownKeys:Object.getOwnPropertySymbols?Gc=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Gc=function(t){return Object.getOwnPropertyNames(t)};function xv(s){console&&console.warn&&console.warn(s)}var mp=Number.isNaN||function(t){return t!==t};function ne(){ne.init.call(this)}Lv.exports=ne,it.once=Fv,ne.EventEmitter=ne,ne.prototype._events=void 0,ne.prototype._eventsCount=0,ne.prototype._maxListeners=void 0;var gp=10;function Wc(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(ne,"defaultMaxListeners",{enumerable:!0,get:function(){return gp},set:function(s){if(typeof s!="number"||s<0||mp(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");gp=s}}),ne.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},ne.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||mp(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 fp(s){return s._maxListeners===void 0?ne.defaultMaxListeners:s._maxListeners}ne.prototype.getMaxListeners=function(){return fp(this)},ne.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")pp(d,this,e);else for(var l=d.length,u=Ep(d,l),r=0;r<l;++r)pp(u[r],this,e);return!0};function Sp(s,t,e,r){var i,n,o;if(Wc(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=fp(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,xv(c)}return s}ne.prototype.addListener=function(t,e){return Sp(this,t,e,!1)},ne.prototype.on=ne.prototype.addListener,ne.prototype.prependListener=function(t,e){return Sp(this,t,e,!0)};function Uv(){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 vp(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=Uv.bind(r);return i.listener=e,r.wrapFn=i,i}ne.prototype.once=function(t,e){return Wc(e),this.on(t,vp(this,t,e)),this},ne.prototype.prependOnceListener=function(t,e){return Wc(e),this.prependListener(t,vp(this,t,e)),this},ne.prototype.removeListener=function(t,e){var r,i,n,o,c;if(Wc(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():$v(r,n),r.length===1&&(i[t]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",t,c||e)}return this},ne.prototype.off=ne.prototype.removeListener,ne.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 Tp(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?Bv(i):Ep(i,i.length)}ne.prototype.listeners=function(t){return Tp(this,t,!0)},ne.prototype.rawListeners=function(t){return Tp(this,t,!1)},ne.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):yp.call(s,t)},ne.prototype.listenerCount=yp;function yp(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}ne.prototype.eventNames=function(){return this._eventsCount>0?Gc(this._events):[]};function Ep(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function $v(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function Bv(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function Fv(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))}wp(s,t,n,{once:!0}),t!=="error"&&Hv(s,i,{once:!0})})}function Hv(s,t,e){typeof s.on=="function"&&wp(s,"error",t,e)}function wp(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 J;(function(s){s[s.MAJOR_EVENT=0]="MAJOR_EVENT",s[s.MINOR_EVENT=1]="MINOR_EVENT"})(J||(J={}));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 qv=new Map([[D.PRECALL_TEST_BEGIN,J.MINOR_EVENT],[D.PRECALL_TEST_COMPLETE,J.MINOR_EVENT],[D.CALL_JOIN_BEGIN,J.MAJOR_EVENT],[D.NET_QUALITY_TEST_BEGIN,J.MINOR_EVENT],[D.NET_QUALITY_TEST_END,J.MINOR_EVENT],[D.WEBSOCKET_CONNECTED,J.MINOR_EVENT],[D.TRANSPORT_CONNECTED,J.MAJOR_EVENT],[D.AUDIO_ON,J.MINOR_EVENT],[D.AUDIO_OFF,J.MINOR_EVENT],[D.VIDEO_ON,J.MINOR_EVENT],[D.VIDEO_OFF,J.MINOR_EVENT],[D.PARTICIPANT_ROLE,J.MINOR_EVENT],[D.PING_STAT,J.MAJOR_EVENT],[D.DISCONNECT,J.MAJOR_EVENT],[D.RECONNECT_ATTEMPT,J.MAJOR_EVENT],[D.SCREENSHARE_START_REQUESTED,J.MINOR_EVENT],[D.SCREENSHARE_STARTED,J.MINOR_EVENT],[D.SCREENSHARE_STOPPED,J.MINOR_EVENT],[D.TAB_CHANGE,J.MINOR_EVENT],[D.BROWSER_BACKGROUNDED,J.MINOR_EVENT],[D.BROWSER_FOREGROUNDED,J.MINOR_EVENT],[D.DOMINANT_SPEAKER,J.MINOR_EVENT],[D.AUDIO_DEVICES_UPDATES,J.MINOR_EVENT],[D.VIDEO_DEVICES_UPDATES,J.MINOR_EVENT],[D.SPEAKER_DEVICES_UPDATES,J.MINOR_EVENT],[D.SELECTED_MICROHPONE_UPDATE,J.MINOR_EVENT],[D.SELECTED_CAMERA_UPDATE,J.MINOR_EVENT],[D.SELECTED_SPEAKER_UPDATE,J.MINOR_EVENT],[D.MEDIA_PERMISSION,J.MINOR_EVENT],[D.LEGACY_SWITCH,J.MINOR_EVENT],[D.AUDIO_PLAY_FAILED,J.MINOR_EVENT],[D.VIDEO_PLAY_FAILED,J.MINOR_EVENT],[D.AUDIO_TRACK_MUTED,J.MINOR_EVENT],[D.VIDEO_TRACK_MUTED,J.MINOR_EVENT],[D.IVS_PLAYER_REBUFFERING,J.MAJOR_EVENT],[D.IVS_PLAYER_AUDIO_BLOCKED,J.MAJOR_EVENT],[D.IVS_PLAYER_PLAYBACK_BLOCKED,J.MAJOR_EVENT],[D.IVS_PLAYER_ERROR,J.MAJOR_EVENT],[D.IVS_PLAYER_RECOVERABLE_ERROR,J.MAJOR_EVENT],[D.IVS_PLAYER_WORKER_ERROR,J.MAJOR_EVENT],[D.IVS_PLAYER_NETWORK_UNAVAILABLE,J.MAJOR_EVENT],[D.LIVESTREAM_LATENCY,J.MAJOR_EVENT],[D.IVS_PLAYER_ANALYTICS_EVENT,J.MINOR_EVENT],[D.IVS_PLAYER_PLAYBACK_RATE_CHANGED,J.MINOR_EVENT],[D.IVS_PLAYER_QUALITY_CHANGED,J.MINOR_EVENT],[D.IVS_PLAYER_INITIALIZED,J.MINOR_EVENT],[D.EXPECTED_VIDEO_RESOLUTION,J.MINOR_EVENT],[D.EXPECTED_SCREENSHARE_RESOLUTION,J.MINOR_EVENT]]);class jv{constructor(){p(this,"events");this.events=[]}add(t){this.events.push(t)}flush(){return{entries:this.events.splice(0,25)}}}class Gv extends it{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 jv}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),qv.get(e.event)===J.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 bp;(function(s){s.CHROMIUM="chromum",s.FIREFOX="firefox",s.SAFARI="safari"})(bp||(bp={}));const Pp={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 wr(s){return s?s.split(".").slice(0,2).concat(["0","0"]).join("."):""}function Jc({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Kc({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}const Cp=240,kp=720,Rp=8,Ip=3,zc=10,Yc=.02,Qc=.03;function $s({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 Ap({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 Mp({packetsLost:s,packetsSent:t}){return t>0?s*100/t:0}function Op({packetsLost:s,packetsSent:t,jitter:e}){const i=$s({stat:Mp({packetsLost:s,packetsSent:t}),weight:.7,rangeMin:0,rangeMax:zc,rangeRankingDirection:"UP"}),o=$s({stat:e,weight:.3,rangeMin:Yc,rangeMax:Qc,rangeRankingDirection:"UP"});return i+o}function Wv({frameWidth:s,isScreenShare:t}){return s<(t?kp:Cp)}function Jv({framesPerSecond:s,isScreenShare:t}){return s<(t?Ip:Rp)}function Kv({framesEncoded:s}){return s===0}function Dp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsSent:r,jitter:i,isScreenShare:n,framesEncoded:o}){const c=$s({stat:Mp({packetsLost:e,packetsSent:r}),weight:1,rangeMin:0,rangeMax:zc,rangeRankingDirection:"UP"}),d=$s({stat:i,weight:1,rangeMin:Yc,rangeMax:Qc,rangeRankingDirection:"UP"}),l=Wv({frameWidth:s,isScreenShare:n}),u=Jv({framesPerSecond:t,isScreenShare:n}),h=Kv({framesEncoded:o,isScreenShare:n});return Ap({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}function Np({packetsLost:s,packetsReceived:t}){return t+s>0?s*100/(t+s):0}function Vp({concealmentEvents:s,packetsLost:t,packetsReceived:e,jitter:r}){const n=$s({stat:s,weight:.2,rangeMin:0,rangeMax:3,rangeRankingDirection:"UP"}),o=.5,c=$s({stat:Np({packetsLost:t,packetsReceived:e}),weight:o,rangeMin:0,rangeMax:zc,rangeRankingDirection:"UP"}),l=$s({stat:r,weight:.3,rangeMin:Yc,rangeMax:Qc,rangeRankingDirection:"UP"});return n+c+l}function zv({framesDecoded:s}){return s===0}function Yv({framesPerSecond:s,isScreenShare:t}){return s<(t?Ip:Rp)}function Qv({frameWidth:s,isScreenShare:t}){return s<(t?kp:Cp)}function Lp({frameWidth:s,framesPerSecond:t,packetsLost:e,packetsReceived:r,jitter:i,isScreenShare:n,framesDecoded:o}){const c=$s({stat:Np({packetsLost:e,packetsReceived:r}),weight:1,rangeMin:0,rangeMax:zc,rangeRankingDirection:"UP"}),d=$s({stat:i,weight:1,rangeMin:Yc,rangeMax:Qc,rangeRankingDirection:"UP"}),l=Qv({frameWidth:s,isScreenShare:n}),u=Yv({framesPerSecond:t,isScreenShare:n}),h=zv({framesDecoded:o,isScreenShare:n});return Ap({isLowQualityVideo:l,isVideoLagging:u,isVideoStuck:h,jitterQuality:d,packetsLostQuality:c})}class Bs{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=Bs.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=Bs.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 Wp extends ot{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new Ks(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 cT=8,dT=1/1e3;class lT extends Wp{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(Ks.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)*cT/(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*dT)})}}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 mu extends Wp{constructor(e,r=Ks.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 uT extends mu{constructor(t){super(t,Ks.isHost)}}class hT extends mu{constructor(t){super(t,Ks.isRelay)}}class pT extends mu{constructor(t){super(t,Ks.isReflexive)}}class mT{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=Ar(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=Ar(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 Jp=new mT,Kp=[{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 zp(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Yp{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 Qp extends ot{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 ot}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,P,C,O,$,L,F,Q,X,it,Ds,fn,Os;const c=e,d=new Yp,l=r.length?new Set(r):void 0,u=[],h=[],m=[],S=new Map,y=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:b}=I,B=I,Pe={nominated:T!=null?T:b,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),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=Pe);break}case"transport":{const T=I;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 b={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=b,o){if(o.producing){const B=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,B,b)}if(o.consuming){const B=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,B,b)}}break}case"remote-inbound-rtp":{const T=I,b={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,b);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(I.id))break;const T=I,b=n||this.outboundProducerMap.get(I.id),B=this.pausedProducerMap.get(b);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(b,{lastReportCalculated:!0})}this.overallProducersStatsMap[b]||(this.overallProducersStatsMap[b]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Pe=this.overallProducersStatsMap[b];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const Fe=this.callStatsInstance.producers.get(b);if(((w=Fe==null?void 0:Fe.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(b)||d.producerStreamMap.set(b,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={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 R=T,je={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped,framesPerSecond:R.framesPerSecond,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.targetBitrate,totalPacketSendDelay:R.totalPacketSendDelay,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,je),d.producerStreamMap.get(b).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(b,Pe,je)}else if(T.mediaType==="audio"||T.kind==="audio"){const R=T,je={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,je),d.producerStreamMap.get(b).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(b,Pe,je)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,b=n||this.inboundConsumerMap.get(I.id),B=this.pausedConsumerMap.get(b);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(b,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[b]||(this.overallConsumersStatsMap[b]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Pe=this.overallConsumersStatsMap[b];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(b)||d.consumerStreamMap.set(b,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Fe={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 V=T,R={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped,framesPerSecond:V.framesPerSecond,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...Fe};R.score=Gp({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((P=this.videoConsumerToStatsMap.get(b))==null?void 0:P.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(b))==null?void 0:C.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((O=this.videoConsumerToStatsMap.get(b))==null?void 0:O.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(b)}),y.set(b,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:ed({packetsLost:(R.packetsLost||0)-((($=this.videoConsumerToStatsMap.get(b))==null?void 0:$.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(b))==null?void 0:L.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(b),bitrate:((R.bytesReceived||0)-(((F=this.videoConsumerToStatsMap.get(b))==null?void 0:F.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(b,R),d.inboundVideoRtp.set(I.id,R),d.consumerStreamMap.get(b).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(b,Pe,R)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,R={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...Fe};R.score=jp({concealmentEvents:(R.concealmentEvents||0)-(((Q=this.audioConsumerToStatsMap.get(b))==null?void 0:Q.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((X=this.audioConsumerToStatsMap.get(b))==null?void 0:X.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((it=this.audioConsumerToStatsMap.get(b))==null?void 0:it.packetsReceived)||0),jitter:R.jitter||0}),y.set(b,{score:+(R.score*10).toFixed(),packetsLostPercentage:ed({packetsLost:(R.packetsLost||0)-(((Ds=this.audioConsumerToStatsMap.get(b))==null?void 0:Ds.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((fn=this.audioConsumerToStatsMap.get(b))==null?void 0:fn.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(b),bitrate:((R.bytesReceived||0)-(((Os=this.audioConsumerToStatsMap.get(b))==null?void 0:Os.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(b,R),d.inboundAudioRtp.set(I.id,R),d.consumerStreamMap.get(b).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(b,Pe,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var b,B,Pe,Fe,V,R,je,Cr,Ic,Ac,Mc,Dc,Oc,Nc,Vc,Lc,xc,Uc,$c,Bc,Fc,Hc,qc;if(I.outboundVideoRtpId.length>0){const ue=[];I.outboundVideoRtpId.forEach(Jh=>{ue.push(d.outboundVideoRtp.get(Jh))});const ee=this.getWorkingSimulcastVideoStats(ue);ee.score=Hp({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((b=ee.remoteData)==null?void 0:b.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(T))==null?void 0:B.packetsSent)||0),packetsLost:(((Pe=ee.remoteData)==null?void 0:Pe.packetsLost)||0)-(((V=(Fe=this.videoProducerToStatsMap.get(T))==null?void 0:Fe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(T))==null?void 0:R.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((je=ee.remoteData)==null?void 0:je.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:Zc({packetsSent:(ee.packetsSent||0)-(((Cr=this.videoProducerToStatsMap.get(T))==null?void 0:Cr.packetsSent)||0),packetsLost:(((Ic=ee.remoteData)==null?void 0:Ic.packetsLost)||0)-(((Mc=(Ac=this.videoProducerToStatsMap.get(T))==null?void 0:Ac.remoteData)==null?void 0:Mc.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-(((Dc=this.videoProducerToStatsMap.get(T))==null?void 0:Dc.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(I.outboundAudioRtpId.length>0){const ue=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);ue.score=Fp({packetsSent:(ue.packetsSent||0)-(((Oc=this.audioProducerToStatsMap.get(T))==null?void 0:Oc.packetsSent)||0),packetsLost:(((Nc=ue.remoteData)==null?void 0:Nc.packetsLost)||0)-(((Lc=(Vc=this.audioProducerToStatsMap.get(T))==null?void 0:Vc.remoteData)==null?void 0:Lc.packetsLost)||0),jitter:((xc=ue.remoteData)==null?void 0:xc.jitter)||0}),S.set(T,{score:+(ue.score*10).toFixed(),bitrate:((ue.bytesSent||0)-(((Uc=this.audioProducerToStatsMap.get(T))==null?void 0:Uc.bytesSent)||0))*8/7,packetsLostPercentage:Zc({packetsSent:(ue.packetsSent||0)-((($c=this.audioProducerToStatsMap.get(T))==null?void 0:$c.packetsSent)||0),packetsLost:(((Bc=ue.remoteData)==null?void 0:Bc.packetsLost)||0)-(((Hc=(Fc=this.audioProducerToStatsMap.get(T))==null?void 0:Fc.remoteData)==null?void 0:Hc.packetsLost)||0)}),jitter:((qc=ue.remoteData)==null?void 0:qc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,ue)}}),m.forEach(I=>{const T=u.find(B=>B.id===I.localCandidateId?(I.localCandidateId=B.id,B):null),b=h.find(B=>B.id===I.remoteCandidateId?(I.remoteCandidateId=B.id,B):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=Ar(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=Ar(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),b&&(I.remoteCandidateType=b.type,I.remoteCandidateAddress=Ar(b.address),I.remoteCandidatePort=b.port,I.remoteCandidateProtocol=b.protocol,I.remoteCandidateUrl=b.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 I=0,T=0;d.remoteInboundRtp.forEach((b,B)=>{b.roundTripTime&&b.roundTripTime>I&&(I=b.roundTripTime,T=b.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(I){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(I){}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||Kp},i=new Promise((u,h)=>{try{const m=new uT(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 hT(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 pT(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||Kp},d=new lT(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 Jp.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?zp(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?zp(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 gT extends Qp{}class Xp extends Qp{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,P,C,O,$,L,F,Q,X,it,Ds,fn,Os;const c=e,d=new Yp,l=r.length?new Set(r):void 0,u=[],h=[],m=[],S=new Map,y=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:b}=I,B=I,Pe={nominated:T!=null?T:b,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),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=Pe);break}case"transport":{const T=I;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 b={bytesReceived:T.bytesReceived,bytesSent:T.bytesSent,packetsSent:T.packetsSent,packetsReceived:T.packetsReceived,dtlsCipher:T.dtlsCipher,dtlsState:T.dtlsState,iceRole:T.iceRole};if(d.transport=b,o){if(o.producing){const B=this.overallProducingTransportsStatsMap[o.id];this.processProducingTransportStats(o.id,B,b)}if(o.consuming){const B=this.overallConsumingTransportsStatsMap[o.id];this.processConsumingTransportStats(o.id,B,b)}}break}case"remote-inbound-rtp":{const T=I,b={jitter:T.jitter,fractionLost:T.fractionLost,roundTripTime:T.roundTripTime,roundTripTimeMeasurements:T.roundTripTimeMeasurements,totalRoundTripTime:T.totalRoundTripTime,packetsLost:T.packetsLost};d.remoteInboundRtp.set(T.localId,b);break}case"outbound-rtp":{if(!this.outboundProducerMap.has(I.id))break;const T=I,b=n||this.outboundProducerMap.get(I.id),B=this.pausedProducerMap.get(b);if(B){if(B.lastReportCalculated===!0)break;this.pausedProducerMap.set(b,{lastReportCalculated:!0})}this.overallProducersStatsMap[b]||(this.overallProducersStatsMap[b]={totalVideoPacketsSent:0,totalAudioPacketsSent:0});const Pe=this.overallProducersStatsMap[b];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const Fe=this.callStatsInstance.producers.get(b);if(((w=Fe==null?void 0:Fe.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(b)||d.producerStreamMap.set(b,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={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 R=T,je={frameHeight:R.frameHeight,frameWidth:R.frameWidth,framesEncoded:R.framesEncoded,framesDropped:R.framesDropped?R.framesDropped:R.droppedFrames,framesPerSecond:R.framesPerSecond?R.framesPerSecond:R.framerateMean,framesSent:R.framesSent,keyFramesEncoded:R.keyFramesEncoded,firCount:R.firCount,encoderImplementation:R.encoderImplementation,hugeFramesSent:R.hugeFramesSent,pliCount:R.pliCount,qpSum:R.qpSum,qualityLimitationReason:R.qualityLimitationReason,qualityLimitationDurations:R.qualityLimitationDurations,qualityLimitationResolutionChanges:R.qualityLimitationResolutionChanges,totalEncodeTime:R.totalEncodeTime,totalPacketSendDelay:R.totalEncodeTime,retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,scalabilityMode:R.scalabilityMode,powerEfficientEncoder:R.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,je),d.producerStreamMap.get(b).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(b,Pe,je)}else if(T.mediaType==="audio"||T.kind==="audio"){const R=T,je={retransmittedBytesSent:R.retransmittedBytesSent,retransmittedPacketsSent:R.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,je),d.producerStreamMap.get(b).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(b,Pe,je)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,b=n||this.inboundConsumerMap.get(I.id),B=this.pausedConsumerMap.get(b);if(B){if(B.lastReportCalculated===!0)break;this.pausedConsumerMap.set(b,{lastReportCalculated:!0})}if(T.ssrc===1234)break;this.overallConsumersStatsMap[b]||(this.overallConsumersStatsMap[b]={totalVideoPacketsReceived:0,totalAudioPacketsReceived:0});const Pe=this.overallConsumersStatsMap[b];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(b)||d.consumerStreamMap.set(b,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const Fe={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 V=T,R={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped?V.framesDropped:V.droppedFrames,framesPerSecond:V.framesPerSecond?V.framesPerSecond:V.framerateMean,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...Fe};R.score=Gp({frameWidth:R.frameWidth||0,framesDecoded:(R.framesDecoded||0)-(((P=this.videoConsumerToStatsMap.get(b))==null?void 0:P.framesDecoded)||0),framesPerSecond:R.framesPerSecond||0,packetsLost:(R.packetsLost||0)-(((C=this.videoConsumerToStatsMap.get(b))==null?void 0:C.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((O=this.videoConsumerToStatsMap.get(b))==null?void 0:O.packetsReceived)||0),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(b)}),y.set(b,{score:+(R.score*10).toFixed(),frameWidth:R.frameWidth||0,frameHeight:R.frameHeight||0,framesPerSecond:R.framesPerSecond||0,packetsLostPercentage:ed({packetsLost:(R.packetsLost||0)-((($=this.videoConsumerToStatsMap.get(b))==null?void 0:$.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(b))==null?void 0:L.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(b),bitrate:((R.bytesReceived||0)-(((F=this.videoConsumerToStatsMap.get(b))==null?void 0:F.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(b,R),d.inboundVideoRtp.set(I.id,R),d.consumerStreamMap.get(b).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(b,Pe,R)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,R={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...Fe};R.score=jp({concealmentEvents:(R.concealmentEvents||0)-(((Q=this.audioConsumerToStatsMap.get(b))==null?void 0:Q.concealmentEvents)||0),packetsLost:(R.packetsLost||0)-(((X=this.audioConsumerToStatsMap.get(b))==null?void 0:X.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((it=this.audioConsumerToStatsMap.get(b))==null?void 0:it.packetsReceived)||0),jitter:R.jitter||0}),y.set(b,{score:+(R.score*10).toFixed(),packetsLostPercentage:ed({packetsLost:(R.packetsLost||0)-(((Ds=this.audioConsumerToStatsMap.get(b))==null?void 0:Ds.packetsLost)||0),packetsReceived:(R.packetsReceived||0)-(((fn=this.audioConsumerToStatsMap.get(b))==null?void 0:fn.packetsReceived)||0)}),jitter:R.jitter||0,isScreenShare:this.screenShareConsumers.has(b),bitrate:((R.bytesReceived||0)-(((Os=this.audioConsumerToStatsMap.get(b))==null?void 0:Os.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(b,R),d.inboundAudioRtp.set(I.id,R),d.consumerStreamMap.get(b).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(b,Pe,R)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var b,B,Pe,Fe,V,R,je,Cr,Ic,Ac,Mc,Dc,Oc,Nc,Vc,Lc,xc,Uc,$c,Bc,Fc,Hc,qc;if(I.outboundVideoRtpId.length>0){const ue=[];I.outboundVideoRtpId.forEach(Jh=>{ue.push(d.outboundVideoRtp.get(Jh))});const ee=this.getWorkingSimulcastVideoStats(ue);ee.score=Hp({frameWidth:ee.frameWidth||0,framesPerSecond:ee.framesPerSecond||0,jitter:((b=ee.remoteData)==null?void 0:b.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(ee.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(T))==null?void 0:B.packetsSent)||0),packetsLost:(((Pe=ee.remoteData)==null?void 0:Pe.packetsLost)||0)-(((V=(Fe=this.videoProducerToStatsMap.get(T))==null?void 0:Fe.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(ee.framesEncoded||0)-(((R=this.videoProducerToStatsMap.get(T))==null?void 0:R.framesEncoded)||0)}),S.set(T,{score:+(ee.score*10).toFixed(),frameWidth:ee.frameWidth||0,frameHeight:ee.frameHeight||0,framesPerSecond:ee.framesPerSecond||0,jitter:((je=ee.remoteData)==null?void 0:je.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:Zc({packetsSent:(ee.packetsSent||0)-(((Cr=this.videoProducerToStatsMap.get(T))==null?void 0:Cr.packetsSent)||0),packetsLost:(((Ic=ee.remoteData)==null?void 0:Ic.packetsLost)||0)-(((Mc=(Ac=this.videoProducerToStatsMap.get(T))==null?void 0:Ac.remoteData)==null?void 0:Mc.packetsLost)||0)}),bitrate:((ee.bytesSent||0)-(((Dc=this.videoProducerToStatsMap.get(T))==null?void 0:Dc.bytesSent)||0))*8/7,cpuLimitations:ee.qualityLimitationReason==="cpu",bandwidthLimitations:ee.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,ee)}else if(I.outboundAudioRtpId.length>0){const ue=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);ue.score=Fp({packetsSent:(ue.packetsSent||0)-(((Oc=this.audioProducerToStatsMap.get(T))==null?void 0:Oc.packetsSent)||0),packetsLost:(((Nc=ue.remoteData)==null?void 0:Nc.packetsLost)||0)-(((Lc=(Vc=this.audioProducerToStatsMap.get(T))==null?void 0:Vc.remoteData)==null?void 0:Lc.packetsLost)||0),jitter:((xc=ue.remoteData)==null?void 0:xc.jitter)||0}),S.set(T,{score:+(ue.score*10).toFixed(),bitrate:((ue.bytesSent||0)-(((Uc=this.audioProducerToStatsMap.get(T))==null?void 0:Uc.bytesSent)||0))*8/7,packetsLostPercentage:Zc({packetsSent:(ue.packetsSent||0)-((($c=this.audioProducerToStatsMap.get(T))==null?void 0:$c.packetsSent)||0),packetsLost:(((Bc=ue.remoteData)==null?void 0:Bc.packetsLost)||0)-(((Hc=(Fc=this.audioProducerToStatsMap.get(T))==null?void 0:Fc.remoteData)==null?void 0:Hc.packetsLost)||0)}),jitter:((qc=ue.remoteData)==null?void 0:qc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,ue)}}),m.forEach(I=>{const T=u.find(B=>B.id===I.localCandidateId?(I.localCandidateId=B.id,B):null),b=h.find(B=>B.id===I.remoteCandidateId?(I.remoteCandidateId=B.id,B):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=Ar(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=Ar(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),b&&(I.remoteCandidateType=b.type,I.remoteCandidateAddress=Ar(b.address),I.remoteCandidatePort=b.port,I.remoteCandidateProtocol=b.protocol,I.remoteCandidateUrl=b.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 I=0,T=0;d.remoteInboundRtp.forEach((b,B)=>{b.roundTripTime&&b.roundTripTime>I&&(I=b.roundTripTime,T=b.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(I){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(I){}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 fT extends Xp{}function id(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 Zp(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=>{id(this,t,e,o)}):n}catch(n){id(this,t,e,n)}return null},s}const Y=(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=>{id(this,s,t,d)}):c}catch(c){id(this,s,t,c)}return null},i},ST=(s,t)=>(e,r,i)=>{if(i)return Zp(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,Zp(o,s,t))}};var K=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 z=console;let W=class extends ot{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Op.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 tT({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new gT;break;case"Gecko":this.measurements=new Xp;break;case"WebKit":this.measurements=new fT;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 ot,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===Xt.AUDIO&&N.AUDIO_DEVICES_UPDATES||e===Xt.VIDEO&&N.VIDEO_DEVICES_UPDATES||e===Xt.SPEAKER&&N.SPEAKER_DEVICES_UPDATES,metaData:{deviceList:r},timestamp:i})}selectedDevice(e,r,i){this.eventHandler.callEvent({event:e===Xt.AUDIO&&N.SELECTED_MICROHPONE_UPDATE||e===Xt.VIDEO&&N.SELECTED_CAMERA_UPDATE||e===Xt.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===Xt.AUDIO&&N.AUDIO_PLAY_FAILED||e===Xt.VIDEO&&N.VIDEO_PLAY_FAILED,metaData:{deviceType:e},timestamp:r})}mediaTrackMuted(e,r){this.eventHandler.callEvent({event:e===Xt.AUDIO&&N.AUDIO_TRACK_MUTED||e===Xt.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}})}};K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerIceServers",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerConsumer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerProducer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendConsumerSharedMediaStateEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerProducingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerConsumingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"deRegisterConsumer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"deRegisterProducer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"disconnectConsumingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"disconnectProducingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPreCallTestBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendScreenShareToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendScreenShareRequestedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendActiveSpeakerEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"devices",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"selectedDevice",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaPermission",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaPlaybackFailed",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaTrackMuted",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"tabChanged",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"browserBackgrounded",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"browserForegrounded",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"legacySwitch",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"getPreCallTestResults",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendCallJoinBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendNetworkQualityTestBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendWebSocketConnectedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendTransportConnectedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendAudioToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendVideoToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendParticipantRoleToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"startPingStats",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"stopPingStats",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPingStatsEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerRebufferEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerAudioBlockEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerInitializedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerWorkerErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerRecoverableErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerAnalyticsEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerQualityChanged",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPlayerLiveLatency",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendDisconnectEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendReconnectEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"expectedVideoResolution",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"expectedScreenshareResolution",null),W=K([ST(TypeError,(s,t)=>z.error(t,s))],W);const vT=W;class em extends ot{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=Op.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 Jp.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new vT(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 em().setMaxListeners(30);class TT{constructor(){g(this,ko,void 0)}get telemetry(){var t;return(t=a(this,ko))==null?void 0:t.getValue("telemetry")}init(t){f(this,ko,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)}}ko=new WeakMap;class yT extends ot.EventEmitter{constructor(e){super();g(this,dr,void 0);g(this,lr,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,dr,new Map),f(this,lr,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,dr).set(e,[]);const i=a(this,lr).get(e).map(()=>new Promise(n=>{a(this,dr).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,dr).delete(e)}onAsync(e,r){const i=a(this,dr),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,lr).get(e)||a(this,lr).set(e,[]),a(this,lr).get(e).push(n),super.on(e,n)}reset(){f(this,dr,new Map),f(this,lr,new Map),super.removeAllListeners()}}dr=new WeakMap,lr=new WeakMap;var ET=typeof global=="object"&&global&&global.Object===Object&&global;const tm=ET;var bT=typeof self=="object"&&self&&self.Object===Object&&self,wT=tm||bT||Function("return this")();const ms=wT;var PT=ms.Symbol;const Vs=PT;var sm=Object.prototype,_T=sm.hasOwnProperty,kT=sm.toString,Wa=Vs?Vs.toStringTag:void 0;function RT(s){var t=_T.call(s,Wa),e=s[Wa];try{s[Wa]=void 0;var r=!0}catch(n){}var i=kT.call(s);return r&&(t?s[Wa]=e:delete s[Wa]),i}var CT=Object.prototype,IT=CT.toString;function AT(s){return IT.call(s)}var MT="[object Null]",DT="[object Undefined]",rm=Vs?Vs.toStringTag:void 0;function hi(s){return s==null?s===void 0?DT:MT:rm&&rm in Object(s)?RT(s):AT(s)}function Ls(s){return s!=null&&typeof s=="object"}var OT="[object Symbol]";function nd(s){return typeof s=="symbol"||Ls(s)&&hi(s)==OT}function NT(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 VT=Array.isArray;const xt=VT;var LT=1/0,im=Vs?Vs.prototype:void 0,nm=im?im.toString:void 0;function am(s){if(typeof s=="string")return s;if(xt(s))return NT(s,am)+"";if(nd(s))return nm?nm.call(s):"";var t=s+"";return t=="0"&&1/s==-LT?"-0":t}var xT=/\s/;function UT(s){for(var t=s.length;t--&&xT.test(s.charAt(t)););return t}var $T=/^\s+/;function BT(s){return s&&s.slice(0,UT(s)+1).replace($T,"")}function Zt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var om=0/0,FT=/^[-+]0x[0-9a-f]+$/i,HT=/^0b[01]+$/i,qT=/^0o[0-7]+$/i,jT=parseInt;function cm(s){if(typeof s=="number")return s;if(nd(s))return om;if(Zt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Zt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=BT(s);var e=HT.test(s);return e||qT.test(s)?jT(s.slice(2),e?2:8):FT.test(s)?om:+s}function gu(s){return s}var GT="[object AsyncFunction]",WT="[object Function]",JT="[object GeneratorFunction]",KT="[object Proxy]";function fu(s){if(!Zt(s))return!1;var t=hi(s);return t==WT||t==JT||t==GT||t==KT}var zT=ms["__core-js_shared__"];const Su=zT;var dm=function(){var s=/[^.]+$/.exec(Su&&Su.keys&&Su.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function YT(s){return!!dm&&dm in s}var QT=Function.prototype,XT=QT.toString;function pi(s){if(s!=null){try{return XT.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var ZT=/[\\^$.*+?()[\]{}|]/g,ey=/^\[object .+?Constructor\]$/,ty=Function.prototype,sy=Object.prototype,ry=ty.toString,iy=sy.hasOwnProperty,ny=RegExp("^"+ry.call(iy).replace(ZT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ay(s){if(!Zt(s)||YT(s))return!1;var t=fu(s)?ny:ey;return t.test(pi(s))}function oy(s,t){return s==null?void 0:s[t]}function mi(s,t){var e=oy(s,t);return ay(e)?e:void 0}var cy=mi(ms,"WeakMap");const vu=cy;var lm=Object.create,dy=function(){function s(){}return function(t){if(!Zt(t))return{};if(lm)return lm(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const ly=dy;function uy(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 hy(){}function um(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var py=800,my=16,gy=Date.now;function fy(s){var t=0,e=0;return function(){var r=gy(),i=my-(r-e);if(e=r,i>0){if(++t>=py)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function Sy(s){return function(){return s}}var vy=function(){try{var s=mi(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const ad=vy;var Ty=ad?function(s,t){return ad(s,"toString",{configurable:!0,enumerable:!1,value:Sy(t),writable:!0})}:gu,yy=fy(Ty);const Ey=yy;function by(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function wy(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 Py(s){return s!==s}function _y(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function ky(s,t,e){return t===t?_y(s,t,e):wy(s,Py,e)}function Ry(s,t){var e=s==null?0:s.length;return!!e&&ky(s,t,0)>-1}var Cy=9007199254740991,Iy=/^(?:0|[1-9]\d*)$/;function Tu(s,t){var e=typeof s;return t=t==null?Cy:t,!!t&&(e=="number"||e!="symbol"&&Iy.test(s))&&s>-1&&s%1==0&&s<t}function yu(s,t,e){t=="__proto__"&&ad?ad(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function Ja(s,t){return s===t||s!==s&&t!==t}var Ay=Object.prototype,My=Ay.hasOwnProperty;function hm(s,t,e){var r=s[t];(!(My.call(s,t)&&Ja(r,e))||e===void 0&&!(t in s))&&yu(s,t,e)}function Ka(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?yu(e,c,d):hm(e,c,d)}return e}var pm=Math.max;function Dy(s,t,e){return t=pm(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=pm(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),uy(s,this,c)}}function Oy(s,t){return Ey(Dy(s,t,gu),s+"")}var Ny=9007199254740991;function Eu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=Ny}function za(s){return s!=null&&Eu(s.length)&&!fu(s)}function Vy(s,t,e){if(!Zt(e))return!1;var r=typeof t;return(r=="number"?za(e)&&Tu(t,e.length):r=="string"&&t in e)?Ja(e[t],s):!1}function Ly(s){return Oy(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&&Vy(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 xy=Object.prototype;function od(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||xy;return s===e}function Uy(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var $y="[object Arguments]";function mm(s){return Ls(s)&&hi(s)==$y}var gm=Object.prototype,By=gm.hasOwnProperty,Fy=gm.propertyIsEnumerable,Hy=mm(function(){return arguments}())?mm:function(s){return Ls(s)&&By.call(s,"callee")&&!Fy.call(s,"callee")};const Ya=Hy;function qy(){return!1}var fm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Sm=fm&&typeof module=="object"&&module&&!module.nodeType&&module,jy=Sm&&Sm.exports===fm,vm=jy?ms.Buffer:void 0,Gy=vm?vm.isBuffer:void 0,Wy=Gy||qy;const yn=Wy;var Jy="[object Arguments]",Ky="[object Array]",zy="[object Boolean]",Yy="[object Date]",Qy="[object Error]",Xy="[object Function]",Zy="[object Map]",eE="[object Number]",tE="[object Object]",sE="[object RegExp]",rE="[object Set]",iE="[object String]",nE="[object WeakMap]",aE="[object ArrayBuffer]",oE="[object DataView]",cE="[object Float32Array]",dE="[object Float64Array]",lE="[object Int8Array]",uE="[object Int16Array]",hE="[object Int32Array]",pE="[object Uint8Array]",mE="[object Uint8ClampedArray]",gE="[object Uint16Array]",fE="[object Uint32Array]",Se={};Se[cE]=Se[dE]=Se[lE]=Se[uE]=Se[hE]=Se[pE]=Se[mE]=Se[gE]=Se[fE]=!0,Se[Jy]=Se[Ky]=Se[aE]=Se[zy]=Se[oE]=Se[Yy]=Se[Qy]=Se[Xy]=Se[Zy]=Se[eE]=Se[tE]=Se[sE]=Se[rE]=Se[iE]=Se[nE]=!1;function SE(s){return Ls(s)&&Eu(s.length)&&!!Se[hi(s)]}function bu(s){return function(t){return s(t)}}var Tm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Qa=Tm&&typeof module=="object"&&module&&!module.nodeType&&module,vE=Qa&&Qa.exports===Tm,wu=vE&&tm.process,TE=function(){try{var s=Qa&&Qa.require&&Qa.require("util").types;return s||wu&&wu.binding&&wu.binding("util")}catch(t){}}();const En=TE;var ym=En&&En.isTypedArray,yE=ym?bu(ym):SE;const cd=yE;var EE=Object.prototype,bE=EE.hasOwnProperty;function Em(s,t){var e=xt(s),r=!e&&Ya(s),i=!e&&!r&&yn(s),n=!e&&!r&&!i&&cd(s),o=e||r||i||n,c=o?Uy(s.length,String):[],d=c.length;for(var l in s)(t||bE.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||Tu(l,d)))&&c.push(l);return c}function bm(s,t){return function(e){return s(t(e))}}var wE=bm(Object.keys,Object);const PE=wE;var _E=Object.prototype,kE=_E.hasOwnProperty;function wm(s){if(!od(s))return PE(s);var t=[];for(var e in Object(s))kE.call(s,e)&&e!="constructor"&&t.push(e);return t}function dd(s){return za(s)?Em(s):wm(s)}function RE(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var CE=Object.prototype,IE=CE.hasOwnProperty;function AE(s){if(!Zt(s))return RE(s);var t=od(s),e=[];for(var r in s)r=="constructor"&&(t||!IE.call(s,r))||e.push(r);return e}function Xa(s){return za(s)?Em(s,!0):AE(s)}var ME=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,DE=/^\w*$/;function Pu(s,t){if(xt(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||nd(s)?!0:DE.test(s)||!ME.test(s)||t!=null&&s in Object(t)}var OE=mi(Object,"create");const Za=OE;function NE(){this.__data__=Za?Za(null):{},this.size=0}function VE(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var LE="__lodash_hash_undefined__",xE=Object.prototype,UE=xE.hasOwnProperty;function $E(s){var t=this.__data__;if(Za){var e=t[s];return e===LE?void 0:e}return UE.call(t,s)?t[s]:void 0}var BE=Object.prototype,FE=BE.hasOwnProperty;function HE(s){var t=this.__data__;return Za?t[s]!==void 0:FE.call(t,s)}var qE="__lodash_hash_undefined__";function jE(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=Za&&t===void 0?qE:t,this}function gi(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])}}gi.prototype.clear=NE,gi.prototype.delete=VE,gi.prototype.get=$E,gi.prototype.has=HE,gi.prototype.set=jE;function GE(){this.__data__=[],this.size=0}function ld(s,t){for(var e=s.length;e--;)if(Ja(s[e][0],t))return e;return-1}var WE=Array.prototype,JE=WE.splice;function KE(s){var t=this.__data__,e=ld(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():JE.call(t,e,1),--this.size,!0}function zE(s){var t=this.__data__,e=ld(t,s);return e<0?void 0:t[e][1]}function YE(s){return ld(this.__data__,s)>-1}function QE(s,t){var e=this.__data__,r=ld(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function zs(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])}}zs.prototype.clear=GE,zs.prototype.delete=KE,zs.prototype.get=zE,zs.prototype.has=YE,zs.prototype.set=QE;var XE=mi(ms,"Map");const eo=XE;function ZE(){this.size=0,this.__data__={hash:new gi,map:new(eo||zs),string:new gi}}function eb(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function ud(s,t){var e=s.__data__;return eb(t)?e[typeof t=="string"?"string":"hash"]:e.map}function tb(s){var t=ud(this,s).delete(s);return this.size-=t?1:0,t}function sb(s){return ud(this,s).get(s)}function rb(s){return ud(this,s).has(s)}function ib(s,t){var e=ud(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function Ys(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])}}Ys.prototype.clear=ZE,Ys.prototype.delete=tb,Ys.prototype.get=sb,Ys.prototype.has=rb,Ys.prototype.set=ib;var nb="Expected a function";function _u(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(nb);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(_u.Cache||Ys),e}_u.Cache=Ys;var ab=500;function ob(s){var t=_u(s,function(r){return e.size===ab&&e.clear(),r}),e=t.cache;return t}var cb=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,db=/\\(\\)?/g,lb=ob(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(cb,function(e,r,i,n){t.push(i?n.replace(db,"$1"):r||e)}),t});const ub=lb;function hb(s){return s==null?"":am(s)}function Pm(s,t){return xt(s)?s:Pu(s,t)?[s]:ub(hb(s))}var pb=1/0;function hd(s){if(typeof s=="string"||nd(s))return s;var t=s+"";return t=="0"&&1/s==-pb?"-0":t}function _m(s,t){t=Pm(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[hd(t[e++])];return e&&e==r?s:void 0}function mb(s,t,e){var r=s==null?void 0:_m(s,t);return r===void 0?e:r}function km(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var gb=bm(Object.getPrototypeOf,Object);const ku=gb;var fb="[object Object]",Sb=Function.prototype,vb=Object.prototype,Rm=Sb.toString,Tb=vb.hasOwnProperty,yb=Rm.call(Object);function Eb(s){if(!Ls(s)||hi(s)!=fb)return!1;var t=ku(s);if(t===null)return!0;var e=Tb.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&Rm.call(e)==yb}function bb(){this.__data__=new zs,this.size=0}function wb(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function Pb(s){return this.__data__.get(s)}function _b(s){return this.__data__.has(s)}var kb=200;function Rb(s,t){var e=this.__data__;if(e instanceof zs){var r=e.__data__;if(!eo||r.length<kb-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new Ys(r)}return e.set(s,t),this.size=e.size,this}function gs(s){var t=this.__data__=new zs(s);this.size=t.size}gs.prototype.clear=bb,gs.prototype.delete=wb,gs.prototype.get=Pb,gs.prototype.has=_b,gs.prototype.set=Rb;function Cb(s,t){return s&&Ka(t,dd(t),s)}function Ib(s,t){return s&&Ka(t,Xa(t),s)}var Cm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Im=Cm&&typeof module=="object"&&module&&!module.nodeType&&module,Ab=Im&&Im.exports===Cm,Am=Ab?ms.Buffer:void 0,Mm=Am?Am.allocUnsafe:void 0;function Dm(s,t){if(t)return s.slice();var e=s.length,r=Mm?Mm(e):new s.constructor(e);return s.copy(r),r}function Mb(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 Om(){return[]}var Db=Object.prototype,Ob=Db.propertyIsEnumerable,Nm=Object.getOwnPropertySymbols,Nb=Nm?function(s){return s==null?[]:(s=Object(s),Mb(Nm(s),function(t){return Ob.call(s,t)}))}:Om;const Ru=Nb;function Vb(s,t){return Ka(s,Ru(s),t)}var Lb=Object.getOwnPropertySymbols,xb=Lb?function(s){for(var t=[];s;)km(t,Ru(s)),s=ku(s);return t}:Om;const Vm=xb;function Ub(s,t){return Ka(s,Vm(s),t)}function Lm(s,t,e){var r=t(s);return xt(s)?r:km(r,e(s))}function Cu(s){return Lm(s,dd,Ru)}function $b(s){return Lm(s,Xa,Vm)}var Bb=mi(ms,"DataView");const Iu=Bb;var Fb=mi(ms,"Promise");const Au=Fb;var Hb=mi(ms,"Set");const bn=Hb;var xm="[object Map]",qb="[object Object]",Um="[object Promise]",$m="[object Set]",Bm="[object WeakMap]",Fm="[object DataView]",jb=pi(Iu),Gb=pi(eo),Wb=pi(Au),Jb=pi(bn),Kb=pi(vu),fi=hi;(Iu&&fi(new Iu(new ArrayBuffer(1)))!=Fm||eo&&fi(new eo)!=xm||Au&&fi(Au.resolve())!=Um||bn&&fi(new bn)!=$m||vu&&fi(new vu)!=Bm)&&(fi=function(s){var t=hi(s),e=t==qb?s.constructor:void 0,r=e?pi(e):"";if(r)switch(r){case jb:return Fm;case Gb:return xm;case Wb:return Um;case Jb:return $m;case Kb:return Bm}return t});const wn=fi;var zb=Object.prototype,Yb=zb.hasOwnProperty;function Qb(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&Yb.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var Xb=ms.Uint8Array;const pd=Xb;function Mu(s){var t=new s.constructor(s.byteLength);return new pd(t).set(new pd(s)),t}function Zb(s,t){var e=t?Mu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var ew=/\w*$/;function tw(s){var t=new s.constructor(s.source,ew.exec(s));return t.lastIndex=s.lastIndex,t}var Hm=Vs?Vs.prototype:void 0,qm=Hm?Hm.valueOf:void 0;function sw(s){return qm?Object(qm.call(s)):{}}function jm(s,t){var e=t?Mu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var rw="[object Boolean]",iw="[object Date]",nw="[object Map]",aw="[object Number]",ow="[object RegExp]",cw="[object Set]",dw="[object String]",lw="[object Symbol]",uw="[object ArrayBuffer]",hw="[object DataView]",pw="[object Float32Array]",mw="[object Float64Array]",gw="[object Int8Array]",fw="[object Int16Array]",Sw="[object Int32Array]",vw="[object Uint8Array]",Tw="[object Uint8ClampedArray]",yw="[object Uint16Array]",Ew="[object Uint32Array]";function bw(s,t,e){var r=s.constructor;switch(t){case uw:return Mu(s);case rw:case iw:return new r(+s);case hw:return Zb(s,e);case pw:case mw:case gw:case fw:case Sw:case vw:case Tw:case yw:case Ew:return jm(s,e);case nw:return new r;case aw:case dw:return new r(s);case ow:return tw(s);case cw:return new r;case lw:return sw(s)}}function Gm(s){return typeof s.constructor=="function"&&!od(s)?ly(ku(s)):{}}var ww="[object Map]";function Pw(s){return Ls(s)&&wn(s)==ww}var Wm=En&&En.isMap,_w=Wm?bu(Wm):Pw;const kw=_w;var Rw="[object Set]";function Cw(s){return Ls(s)&&wn(s)==Rw}var Jm=En&&En.isSet,Iw=Jm?bu(Jm):Cw;const Aw=Iw;var Mw=1,Dw=2,Ow=4,Km="[object Arguments]",Nw="[object Array]",Vw="[object Boolean]",Lw="[object Date]",xw="[object Error]",zm="[object Function]",Uw="[object GeneratorFunction]",$w="[object Map]",Bw="[object Number]",Ym="[object Object]",Fw="[object RegExp]",Hw="[object Set]",qw="[object String]",jw="[object Symbol]",Gw="[object WeakMap]",Ww="[object ArrayBuffer]",Jw="[object DataView]",Kw="[object Float32Array]",zw="[object Float64Array]",Yw="[object Int8Array]",Qw="[object Int16Array]",Xw="[object Int32Array]",Zw="[object Uint8Array]",eP="[object Uint8ClampedArray]",tP="[object Uint16Array]",sP="[object Uint32Array]",he={};he[Km]=he[Nw]=he[Ww]=he[Jw]=he[Vw]=he[Lw]=he[Kw]=he[zw]=he[Yw]=he[Qw]=he[Xw]=he[$w]=he[Bw]=he[Ym]=he[Fw]=he[Hw]=he[qw]=he[jw]=he[Zw]=he[eP]=he[tP]=he[sP]=!0,he[xw]=he[zm]=he[Gw]=!1;function to(s,t,e,r,i,n){var o,c=t&Mw,d=t&Dw,l=t&Ow;if(e&&(o=i?e(s,r,i,n):e(s)),o!==void 0)return o;if(!Zt(s))return s;var u=xt(s);if(u){if(o=Qb(s),!c)return um(s,o)}else{var h=wn(s),m=h==zm||h==Uw;if(yn(s))return Dm(s,c);if(h==Ym||h==Km||m&&!i){if(o=d||m?{}:Gm(s),!c)return d?Ub(s,Ib(o,s)):Vb(s,Cb(o,s))}else{if(!he[h])return i?s:{};o=bw(s,h,c)}}n||(n=new gs);var S=n.get(s);if(S)return S;n.set(s,o),Aw(s)?s.forEach(function(P){o.add(to(P,t,e,P,s,n))}):kw(s)&&s.forEach(function(P,C){o.set(C,to(P,t,e,C,s,n))});var y=l?d?$b:Cu:d?Xa:dd,w=u?void 0:y(s);return by(w||s,function(P,C){w&&(C=P,P=s[C]),hm(o,C,to(P,t,e,C,s,n))}),o}var rP=4;function iP(s){return to(s,rP)}var nP=1,aP=4;function Du(s){return to(s,nP|aP)}var oP="__lodash_hash_undefined__";function cP(s){return this.__data__.set(s,oP),this}function dP(s){return this.__data__.has(s)}function so(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new Ys;++t<e;)this.add(s[t])}so.prototype.add=so.prototype.push=cP,so.prototype.has=dP;function lP(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 Qm(s,t){return s.has(t)}var uP=1,hP=2;function Xm(s,t,e,r,i,n){var o=e&uP,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&hP?new so:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var y=s[h],w=t[h];if(r)var P=o?r(w,y,h,t,s,n):r(y,w,h,s,t,n);if(P!==void 0){if(P)continue;m=!1;break}if(S){if(!lP(t,function(C,O){if(!Qm(S,O)&&(y===C||i(y,C,e,r,n)))return S.push(O)})){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 pP(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function Ou(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var mP=1,gP=2,fP="[object Boolean]",SP="[object Date]",vP="[object Error]",TP="[object Map]",yP="[object Number]",EP="[object RegExp]",bP="[object Set]",wP="[object String]",PP="[object Symbol]",_P="[object ArrayBuffer]",kP="[object DataView]",Zm=Vs?Vs.prototype:void 0,Nu=Zm?Zm.valueOf:void 0;function RP(s,t,e,r,i,n,o){switch(e){case kP:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case _P:return!(s.byteLength!=t.byteLength||!n(new pd(s),new pd(t)));case fP:case SP:case yP:return Ja(+s,+t);case vP:return s.name==t.name&&s.message==t.message;case EP:case wP:return s==t+"";case TP:var c=pP;case bP:var d=r&mP;if(c||(c=Ou),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=gP,o.set(s,t);var u=Xm(c(s),c(t),r,i,n,o);return o.delete(s),u;case PP:if(Nu)return Nu.call(s)==Nu.call(t)}return!1}var CP=1,IP=Object.prototype,AP=IP.hasOwnProperty;function MP(s,t,e,r,i,n){var o=e&CP,c=Cu(s),d=c.length,l=Cu(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var m=c[h];if(!(o?m in t:AP.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 P=o;++h<d;){m=c[h];var C=s[m],O=t[m];if(r)var $=o?r(O,C,m,t,s,n):r(C,O,m,s,t,n);if(!($===void 0?C===O||i(C,O,e,r,n):$)){w=!1;break}P||(P=m=="constructor")}if(w&&!P){var L=s.constructor,F=t.constructor;L!=F&&"constructor"in s&&"constructor"in t&&!(typeof L=="function"&&L instanceof L&&typeof F=="function"&&F instanceof F)&&(w=!1)}return n.delete(s),n.delete(t),w}var DP=1,eg="[object Arguments]",tg="[object Array]",md="[object Object]",OP=Object.prototype,sg=OP.hasOwnProperty;function NP(s,t,e,r,i,n){var o=xt(s),c=xt(t),d=o?tg:wn(s),l=c?tg:wn(t);d=d==eg?md:d,l=l==eg?md:l;var u=d==md,h=l==md,m=d==l;if(m&&yn(s)){if(!yn(t))return!1;o=!0,u=!1}if(m&&!u)return n||(n=new gs),o||cd(s)?Xm(s,t,e,r,i,n):RP(s,t,d,e,r,i,n);if(!(e&DP)){var S=u&&sg.call(s,"__wrapped__"),y=h&&sg.call(t,"__wrapped__");if(S||y){var w=S?s.value():s,P=y?t.value():t;return n||(n=new gs),i(w,P,e,r,n)}}return m?(n||(n=new gs),MP(s,t,e,r,i,n)):!1}function gd(s,t,e,r,i){return s===t?!0:s==null||t==null||!Ls(s)&&!Ls(t)?s!==s&&t!==t:NP(s,t,e,r,gd,i)}var VP=1,LP=2;function xP(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 gs;if(r)var m=r(l,u,d,s,t,h);if(!(m===void 0?gd(u,l,VP|LP,r,h):m))return!1}}return!0}function rg(s){return s===s&&!Zt(s)}function UP(s){for(var t=dd(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,rg(i)]}return t}function ig(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function $P(s){var t=UP(s);return t.length==1&&t[0][2]?ig(t[0][0],t[0][1]):function(e){return e===s||xP(e,s,t)}}function BP(s,t){return s!=null&&t in Object(s)}function FP(s,t,e){t=Pm(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=hd(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&&Eu(i)&&Tu(o,i)&&(xt(s)||Ya(s)))}function HP(s,t){return s!=null&&FP(s,t,BP)}var qP=1,jP=2;function GP(s,t){return Pu(s)&&rg(t)?ig(hd(s),t):function(e){var r=mb(e,s);return r===void 0&&r===t?HP(e,s):gd(t,r,qP|jP)}}function WP(s){return function(t){return t==null?void 0:t[s]}}function JP(s){return function(t){return _m(t,s)}}function KP(s){return Pu(s)?WP(hd(s)):JP(s)}function zP(s){return typeof s=="function"?s:s==null?gu:typeof s=="object"?xt(s)?GP(s[0],s[1]):$P(s):KP(s)}function YP(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 QP=YP();const XP=QP;var ZP=function(){return ms.Date.now()};const Vu=ZP;var e_="Expected a function",t_=Math.max,s_=Math.min;function Lu(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(e_);t=cm(t)||0,Zt(e)&&(u=!!e.leading,h="maxWait"in e,n=h?t_(cm(e.maxWait)||0,t):n,m="trailing"in e?!!e.trailing:m);function S(Q){var X=r,it=i;return r=i=void 0,l=Q,o=s.apply(it,X),o}function y(Q){return l=Q,c=setTimeout(C,t),u?S(Q):o}function w(Q){var X=Q-d,it=Q-l,Ds=t-X;return h?s_(Ds,n-it):Ds}function P(Q){var X=Q-d,it=Q-l;return d===void 0||X>=t||X<0||h&&it>=n}function C(){var Q=Vu();if(P(Q))return O(Q);c=setTimeout(C,w(Q))}function O(Q){return c=void 0,m&&r?S(Q):(r=i=void 0,o)}function $(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function L(){return c===void 0?o:O(Vu())}function F(){var Q=Vu(),X=P(Q);if(r=arguments,i=this,d=Q,X){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 F.cancel=$,F.flush=L,F}function xu(s,t,e){(e!==void 0&&!Ja(s[t],e)||e===void 0&&!(t in s))&&yu(s,t,e)}function r_(s){return Ls(s)&&za(s)}function Uu(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function i_(s){return Ka(s,Xa(s))}function n_(s,t,e,r,i,n,o){var c=Uu(s,e),d=Uu(t,e),l=o.get(d);if(l){xu(s,e,l);return}var u=n?n(c,d,e+"",s,t,o):void 0,h=u===void 0;if(h){var m=xt(d),S=!m&&yn(d),y=!m&&!S&&cd(d);u=d,m||S||y?xt(c)?u=c:r_(c)?u=um(c):S?(h=!1,u=Dm(d,!0)):y?(h=!1,u=jm(d,!0)):u=[]:Eb(d)||Ya(d)?(u=c,Ya(c)?u=i_(c):(!Zt(c)||fu(c))&&(u=Gm(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),xu(s,e,u)}function ng(s,t,e,r,i){s!==t&&XP(t,function(n,o){if(i||(i=new gs),Zt(n))n_(s,t,o,e,ng,r,i);else{var c=r?r(Uu(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),xu(s,o,c)}},Xa)}function a_(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 o_="[object Map]",c_="[object Set]",d_=Object.prototype,l_=d_.hasOwnProperty;function u_(s){if(s==null)return!0;if(za(s)&&(xt(s)||typeof s=="string"||typeof s.splice=="function"||yn(s)||cd(s)||Ya(s)))return!s.length;var t=wn(s);if(t==o_||t==c_)return!s.size;if(od(s))return!wm(s).length;for(var e in s)if(l_.call(s,e))return!1;return!0}function h_(s,t){return gd(s,t)}var p_=Ly(function(s,t,e){ng(s,t,e)});const Mr=p_;var m_=1/0,g_=bn&&1/Ou(new bn([,-0]))[1]==m_?function(s){return new bn(s)}:hy;const f_=g_;var S_=200;function ag(s,t,e){var r=-1,i=Ry,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=a_;else if(n>=S_){var l=t?null:f_(s);if(l)return Ou(l);o=!1,i=Qm,d=new so}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 v_(s){return s&&s.length?ag(s):[]}function T_(s,t){return s&&s.length?ag(s,zP(t)):[]}function fd(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 y_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},og={STAGING:"staging",PROD:"prod"},ro={baseURL:"http://localhost:5000",createdAt:"2021-08-05T10:49:56.602Z",description:"Develop plugins locally",id:"09259e3b-7be8-46f6-9801-106bf1866e1c",name:"Localhost Dev",organizationId:"4ad15a19-80e2-4105-bf43-48039fd2963e",picture:"https://dyte-uploads.s3.ap-south-1.amazonaws.com/dyte.png",private:!1,published:!0,staggered:!1,tags:["#localhost","#dev"],type:"self_hosted",updatedAt:"2021-08-05T10:50:07.681Z"},E_={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 b_({baseURI:s}){return s.includes("staging.realtime")?og.STAGING:og.PROD}function _n({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function w_(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 P_='<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>',__='<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path d="M4 12.02c0 1.06.2 2.1.6 3.08l.6 1.42c.22.55.64 1.01 1.17 1.29.27.14.56.21.86.21h2.55c.77 0 1.49-.41 1.87-1.08.5-.87 1.02-1.7 1.72-2.43l1.32-1.39c.44-.46.97-.84 1.49-1.23l.59-.45a.6.6 0 0 0 .23-.47c0-.75-.54-1.57-1.22-1.79a3.34 3.34 0 0 0-2.78.29V4.5a1.5 1.5 0 0 0-2.05-1.4 1.5 1.5 0 0 0-2.9 0A1.5 1.5 0 0 0 6 4.5v.09A1.5 1.5 0 0 0 4 6v6.02ZM8 4.5v4a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0v5a.5.5 0 0 0 1 0v-4a.5.5 0 0 1 1 0v6a.5.5 0 0 0 .85.37h.01c.22-.22.44-.44.72-.58.7-.35 2.22-.57 2.4.5l-.53.4c-.52.4-1.04.78-1.48 1.24l-1.33 1.38c-.75.79-1.31 1.7-1.85 2.63-.21.36-.6.58-1.01.58H7.23a.87.87 0 0 1-.4-.1 1.55 1.55 0 0 1-.71-.78l-.59-1.42a7.09 7.09 0 0 1-.53-2.7V6a.5.5 0 0 1 1 0v3.5a.5.5 0 0 0 1 0v-5a.5.5 0 0 1 1 0Z" fill="currentColor"></path></svg>',Sd=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})},Si={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"}},k_=["b3924730-93a3-4561-a9e5-441fb860aadb","f3eeb01c-13d9-4d89-ade4-62acbe36a91b","0b80d104-96aa-4de9-b907-2af213aecee8","b1f57ddb-02d3-43f9-9d19-b87ae060d754","0ea29cac-8161-4cb4-ac22-24b98a2d0ac0","ae3c467c-f261-4307-8a32-11454edb8619","f4fc4c6a-976e-4261-b063-c5a5fefe1fd7","2479fcba-5032-415e-96b9-0d789dbe6723","b340c4f8-43bc-4edb-a54c-5ab083bd9b16","b7703581-6e68-4bc1-bf1e-c95b3d61930a","f4776519-87bb-4d2c-b801-25ac11f96ac5","80a57014-1efe-44f8-b929-b8fca1cf18a1","4f43a422-f420-40f0-968e-c0515fb73c47","cd18cbda-0c13-41e5-a881-e99ef2f00995","da1258f4-666a-48fc-ab3b-21f69c17bddd","10ad9660-3bec-43f9-8304-acd5d4284180","ff830eaa-8c28-44b6-92de-527315f24552","32a8de63-bd77-4e2d-bd04-0048a3dbdf9c","e0d26ea8-066c-47bb-b0cf-57b79d68346a","3830f724-13ee-487f-b62f-2f039d76a09e","54c140a4-e4ff-402b-85d1-ce23182ad3e3","49f9e74a-bf03-4aac-a9c2-3db9f8fdfa41","7f11749e-d90b-4e41-be70-cc9f80641129","f7174bfd-c67c-4ee1-891f-4329333a28f8","e4d08973-cba5-434f-b38a-fc7908a0ea48","31e11e56-1705-4b52-963a-2cfa4af80142","ec8139f6-fe0f-4c09-a030-b97728c4c451","46a9290b-3d63-4ded-94a4-ab3cca22eec0","39d1d29a-aa47-444a-a77c-d075bca8a08a","531356db-519b-4d0f-a5da-086cc02bbafa","546de108-91aa-4bf8-a535-18110c3f57d8","6c7371c7-bc57-4cf9-8ab6-e377e8cedc0b","e8882a98-6276-4db0-b3a8-a216259dfb31","66292cea-49de-4acb-b695-d77153897a23","5f1d6cab-a385-48df-b6c9-a7f48ed7c58d","bdb1f51a-5eb8-4664-95b3-ee933075194e","6615e115-f38b-4cbb-bd50-acadaa16380e","4a1e79f2-0aab-43d4-ab15-d3a42b3ebd1f"],R_=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/;function cg(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(Si.baseURI.staging)),e=!!((n=(i=s==null?void 0:s.getValue("modules"))==null?void 0:i.devTools)!=null&&n.logs);return t||e}function C_(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 dg(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"?dg(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function lg(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=dg(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
|
|
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=Dr.getContext(Dr.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 Td(s,t,e,r){if(r instanceof k)throw r;if(r instanceof t){const i=new k(r.message,e);throw i.stack=r.stack,i}else throw r}function ug(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){Td(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){Td(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=>{Td(this,t,e,o)}):n}catch(n){Td(this,t,e,n)}},s}function D_(s,t){return(e,r,i)=>{if(i)return ug(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,ug(o,s,t))}}}const ct=s=>D_(Error,s);var Qs=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(Qs||{}),H=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(H||{});typeof process!="undefined"&&(CS=process==null?void 0:process.env)!=null&&CS.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var hg=[-2,-1,0,1,2],O_=[0,1,2,3,4];function N_(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 V_=(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)]},L_=(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]},x_=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},pg=(s,t=hg,e=.4)=>{const r=[],[i,n,o]=N_(s),[c,d,l]=L_(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(P=>P===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 P of t){let C;P<0?C=u+P*w*e:P>0?C=u+P*y*e:C=u;const[O,$,L]=V_(c,d,C/100);r.push(x_(O,$,L))}return r},mg={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"}},U_=s=>{const[t,e,r,i,n]=pg(s,hg);return{300:t,400:e,500:r,600:i,700:n}},$_=s=>{if(s==="#FFFFFF")return mg.light.background;if(s==="#000000")return mg.dark.background;const[t,e,r,i,n]=pg(s,O_);return{1e3:t,900:e,800:r,700:i,600:n}},B_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:U_("#2160FD"),background:$_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function gg(){return Du(B_)}var F_={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:gg(),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 H_(){return Du(F_)}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:gg(),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 $u(){return Du(q_)}function j_(){fe.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 _=(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))(_||{});class kn extends ot.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 Ut extends ot.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 G_(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 fg=1080,Sg=1920,W_=(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,P,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),P=l/(m/r),S=(d-w)*o,y=(l-P)*c,S<0&&(S=0),y<0&&(y=0),w>d&&(w=d),P>l&&(P=l),[S,y,w,P,s,t,e,r]},Wh=class extends Ut{constructor(e,r,i,n){const o=e.getValue("logger");super(o);g(this,ss,void 0);g(this,Ai,void 0);g(this,lt,void 0);g(this,rs,void 0);g(this,Oe,{height:fg,width:Sg});g(this,ws,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,ur,void 0);g(this,Et,{});g(this,Ue,void 0);g(this,$n,void 0);g(this,Bn,void 0);g(this,hr,void 0);g(this,Fn,!1);p(this,"cleanupEventListeners",()=>{a(this,Ai).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,Ai).getValue("peerSessionStore").emit(_.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,hr)==="active"){this.disable(!0);return}a(this,Et)!==void 0&&this.paintCanvas(),a(this,ur)!==void 0&&f(this,ur,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,hr,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,ur)),e!==!0&&document.body.removeChild(a(this,lt)),f(this,ur,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,Ai,e),f(this,hr,"idle"),f(this,Ue,r),f(this,ws,{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 Sd(P_),n=await Sd(__)}catch(o){}return new Wh(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 Sd(r));break;case"pin":f(this,$n,await Sd(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,lt,document.createElement("div")),a(this,lt).style.width="0.1px",a(this,lt).style.height="0.1px",a(this,lt).style.overflow="hidden",a(this,lt).style.position="absolute",a(this,lt).style.bottom="0",a(this,lt).style.right="0",a(this,lt).style.opacity="0",a(this,lt).appendChild(a(this,rs))}setupEventListeners(){a(this,Ai).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,Oe).height,e.width=a(this,Oe).width,f(this,ss,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,Et)).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,ss)===void 0)return;const o=a(this,ss).getContext("2d"),c=a(this,ss).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,P=S*(h+d)+d,{displayText:C,image:O}=n!=null?n:{};o.fillStyle=C||O?a(this,ws).videoBackground:a(this,ws).background,o.strokeStyle=a(this,ws).brand,o.beginPath(),o.moveTo(w+l,P),o.arcTo(w+u,P,w+u,P+l,l),o.arcTo(w+u,P+h,w+u-l,P+h,l),o.arcTo(w,P+h,w,P+h-l,l),o.arcTo(w,P,w+l,P,l),o.closePath(),o.fill(),o.stroke();const $=u/6,L=u/2+w,F=h/2+P;o.save(),(C||O)&&(o.beginPath(),o.arc(L,F,$,0,Math.PI*2),o.fillStyle=a(this,ws).brand,o.fill(),O?(o.clip(),o.drawImage(O,L-$,F-$,$*2,$*2),o.restore()):C&&(o.fillStyle=a(this,ws).textOnBrand,o.font=`${$/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(C,L,F)),this.drawIcons(n,w,P,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,ss).getContext("2d");S.save(),S.fillStyle=a(this,ws).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,ws).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,ss)===void 0)return;const n=a(this,ss).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,[S,y,w,P,C,O,$,L]=W_(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,P,-1*C,O,-1*$,L),n.restore()):n.drawImage(m,S,y,w,P,C,O,$,L),this.drawIcons(o[d],C,O,Math.max($,L))}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,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,lt))try{document.body.removeChild(a(this,lt))}catch(e){}this.removeAllSources(),f(this,ss,void 0),f(this,rs,void 0),f(this,ur,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:fg,width:r!=null?r:Sg}),i.height=a(this,Oe).height,i.width=a(this,Oe).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,ss).captureStream(24),f(this,rs,i),a(this,rs).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,rs).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,Et)[e]!==void 0&&(a(this,Et)[e].enabled=!0)}disableSource(e){a(this,Et)[e]!==void 0&&(a(this,Et)[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,Et)[e]={id:e,element:r,enabled:i,pinned:n,displayText:o?G_(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,Et)[e];i&&(a(this,Et)[e]={...i,...r})}removeSource(e){delete a(this,Et)[e]}removePinnedSource(){Object.values(a(this,Et)).forEach(r=>{r.pinned&&this.removeSource(r.id)})}removeAllSources(){f(this,Et,{})}enable(){f(this,hr,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,Ue).videoEnabled),this.updateMediaSession("MIC",a(this,Ue).audioEnabled),document.body.appendChild(a(this,lt)),f(this,ur,requestAnimationFrame(()=>this.animate())),a(this,rs).onloadedmetadata=()=>{a(this,rs).requestPictureInPicture().then(()=>{f(this,hr,"active")})},a(this,rs).readyState===4&&a(this,rs).requestPictureInPicture().then(()=>{f(this,hr,"active")})}};let Bu=Wh;ss=new WeakMap,Ai=new WeakMap,lt=new WeakMap,rs=new WeakMap,Oe=new WeakMap,ws=new WeakMap,ur=new WeakMap,Et=new WeakMap,Ue=new WeakMap,$n=new WeakMap,Bn=new WeakMap,hr=new WeakMap,Fn=new WeakMap;function Fu(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function J_(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let Xs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),yd=[];for(let s=0;s<Xs.length;s++)yd[Xs[s].charCodeAt(0)]=s;yd["-".charCodeAt(0)]=Xs.indexOf("+"),yd["_".charCodeAt(0)]=Xs.indexOf("/");function K_(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=yd[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 z_(s){let t="",e=0,r,i=0;for(let n=0;n<s.length;n++)switch(r=s[n],e){case 0:t+=Xs[r>>2],i=(r&3)<<4,e=1;break;case 1:t+=Xs[i|r>>4],i=(r&15)<<2,e=2;break;case 2:t+=Xs[i|r>>6],t+=Xs[r&63],e=0;break}return e&&(t+=Xs[i],t+="=",e==1&&(t+="=")),t}var Ed;(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])})(Ed||(Ed={}));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 Y_(){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 Hu(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 bd=(1<<16)*(1<<16);function vg(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>=bd&&(i=i+(r/bd|0),r=r%bd)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function qu(s,t){if(t>>>0<=2097151)return""+(bd*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 Tg(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 Q_(){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 le;function X_(){const s=new DataView(new ArrayBuffer(8));le=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}X_();function yg(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const Eg=/^-?[0-9]+$/,wd=4294967296,Pd=2147483648;class bg{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*wd+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class dt extends bg{static from(t){if(le)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=le.C(t);case"number":if(t===0)return this.ZERO;t=le.C(t);case"bigint":if(!t)return this.ZERO;if(t<le.UMIN)throw new Error("signed value for ulong");if(t>le.UMAX)throw new Error("ulong too large");return le.V.setBigUint64(0,t,!0),new dt(le.V.getInt32(0,!0),le.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Eg.test(t))throw new Error("string is no integer");let[e,r,i]=vg(t);if(e)throw new Error("signed value for ulong");return new dt(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 dt(t,t/wd)}throw new Error("unknown value "+typeof t)}toString(){return le?this.toBigInt().toString():qu(this.lo,this.hi)}toBigInt(){return yg(le),le.V.setInt32(0,this.lo,!0),le.V.setInt32(4,this.hi,!0),le.V.getBigUint64(0,!0)}}dt.ZERO=new dt(0,0);class pe extends bg{static from(t){if(le)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=le.C(t);case"number":if(t===0)return this.ZERO;t=le.C(t);case"bigint":if(!t)return this.ZERO;if(t<le.MIN)throw new Error("signed long too small");if(t>le.MAX)throw new Error("signed long too large");return le.V.setBigInt64(0,t,!0),new pe(le.V.getInt32(0,!0),le.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!Eg.test(t))throw new Error("string is no integer");let[e,r,i]=vg(t);if(e){if(i>Pd||i==Pd&&r!=0)throw new Error("signed long too small")}else if(i>=Pd)throw new Error("signed long too large");let n=new pe(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 pe(t,t/wd):new pe(-t,-t/wd).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&Pd)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new pe(e,t)}toString(){if(le)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+qu(t.lo,t.hi)}return qu(this.lo,this.hi)}toBigInt(){return yg(le),le.V.setInt32(0,this.lo,!0),le.V.setInt32(4,this.hi,!0),le.V.getBigInt64(0,!0)}}pe.ZERO=new pe(0,0);const wg={readUnknownField:!0,readerFactory:s=>new ek(s)};function Z_(s){return s?Object.assign(Object.assign({},wg),s):wg}class ek{constructor(t,e){this.varint64=Y_,this.uint32=Q_,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 pe(...this.varint64())}uint64(){return new dt(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new pe(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 dt(this.sfixed32(),this.sfixed32())}sfixed64(){return new pe(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let 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 se(s,t){if(!s)throw new Error(t)}const tk=34028234663852886e22,sk=-34028234663852886e22,rk=4294967295,ik=2147483647,nk=-2147483648;function io(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>ik||s<nk)throw new Error("invalid int 32: "+s)}function _d(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>rk||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>tk||s<sk))throw new Error("invalid float 32: "+s)}const Pg={writeUnknownFields:!0,writerFactory:()=>new ok};function ak(s){return s?Object.assign(Object.assign({},Pg),s):Pg}class ok{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(_d(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return io(t),Tg(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){_d(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){io(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return io(t),t=(t<<1^t>>31)>>>0,Tg(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=pe.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=dt.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=pe.from(t);return Hu(e.lo,e.hi,this.buf),this}sint64(t){let e=pe.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return Hu(i,n,this.buf),this}uint64(t){let e=dt.from(t);return Hu(e.lo,e.hi,this.buf),this}}const _g={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},kg={ignoreUnknownFields:!1};function ck(s){return s?Object.assign(Object.assign({},kg),s):kg}function dk(s){return s?Object.assign(Object.assign({},_g),s):_g}const Rg=Symbol.for("protobuf-ts/message-type");function Cg(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 A;(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"})(A||(A={}));var xs;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(xs||(xs={}));var kd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(kd||(kd={}));function lk(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:Cg(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:Cg(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:kd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function uk(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 hk{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(!uk(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,A.INT32,i):this.scalar(t,A.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),A.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 A.UINT64:case A.FIXED64:case A.INT64:case A.SFIXED64:case A.SINT64:switch(r){case xs.BIGINT:return i=="bigint";case xs.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case A.BOOL:return i=="boolean";case A.STRING:return i=="string";case A.BYTES:return t instanceof Uint8Array;case A.DOUBLE:case A.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 A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case A.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,xs.STRING)}}}function fs(s,t){switch(t){case xs.BIGINT:return s.toBigInt();case xs.NUMBER:return s.toNumber();default:return s.toString()}}class pk{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=Fu(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(J_(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==A.BOOL&&(y=y=="true"?!0:y=="false"?!1:y),y=this.scalar(y,c.K,xs.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"&&se(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 se(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:(se(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}se(!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 A.DOUBLE:case A.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==A.FLOAT&&ju(o),o;case A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.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==A.UINT32?_d(c):io(c),c;case A.INT64:case A.SFIXED64:case A.SINT64:if(t===null)return fs(pe.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return fs(pe.from(t),r);case A.FIXED64:case A.UINT64:if(t===null)return fs(dt.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return fs(dt.from(t),r);case A.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case A.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 A.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return K_(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class mk{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);se(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){se(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);se(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);se(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){se(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);se(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){se(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);se(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){se(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);se(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);se(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){se(i);return}if(!(e===0&&!n&&!i))return se(typeof e=="number"),se(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){se(i);return}const o=n||i;switch(t){case A.INT32:case A.SFIXED32:case A.SINT32:return e===0?o?0:void 0:(io(e),e);case A.FIXED32:case A.UINT32:return e===0?o?0:void 0:(_d(e),e);case A.FLOAT:ju(e);case A.DOUBLE:return e===0?o?0:void 0:(se(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case A.STRING:return e===""?o?"":void 0:(se(typeof e=="string"),e);case A.BOOL:return e===!1?o?!1:void 0:(se(typeof e=="boolean"),e);case A.UINT64:case A.FIXED64:se(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=dt.from(e);return c.isZero()&&!o?void 0:c.toString();case A.INT64:case A.SFIXED64:case A.SINT64:se(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=pe.from(e);return d.isZero()&&!o?void 0:d.toString();case A.BYTES:return se(e instanceof Uint8Array),e.byteLength?z_(e):o?"":void 0}}}function Gu(s,t=xs.STRING){switch(s){case A.BOOL:return!1;case A.UINT64:case A.FIXED64:return fs(dt.ZERO,t);case A.INT64:case A.SFIXED64:case A.SINT64:return fs(pe.ZERO,t);case A.DOUBLE:case A.FLOAT:return 0;case A.BYTES:return new Uint8Array(0);case A.STRING:return"";default:return 0}}class gk{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?Ed.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"?A.INT32:d.T,S=d.kind=="scalar"?d.L:void 0;if(u){let P=l[h];if(c==Le.LengthDelimited&&m!=A.STRING&&m!=A.BYTES){let C=t.uint32()+t.pos;for(;t.pos<C;)P.push(this.scalar(t,m,S))}else P.push(this.scalar(t,m,S))}else l[h]=this.scalar(t,m,S);break;case"message":if(u){let P=l[h],C=d.T().internalBinaryRead(t,t.uint32(),r);P.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==A.BOOL?o=e.bool().toString():o=this.scalar(e,t.K,xs.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=Gu(t.K);o=t.K==A.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=Gu(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 A.INT32:return t.int32();case A.STRING:return t.string();case A.BOOL:return t.bool();case A.DOUBLE:return t.double();case A.FLOAT:return t.float();case A.INT64:return fs(t.int64(),r);case A.UINT64:return fs(t.uint64(),r);case A.FIXED64:return fs(t.fixed64(),r);case A.FIXED32:return t.fixed32();case A.BYTES:return t.bytes();case A.UINT32:return t.uint32();case A.SFIXED32:return t.sfixed32();case A.SFIXED64:return fs(t.sfixed64(),r);case A.SINT32:return t.sint32();case A.SINT64:return fs(t.sint64(),r)}}}class fk{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"?A.INT32:n.T;if(d)if(se(Array.isArray(o)),d==kd.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?se(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){se(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":se(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?Ed.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 A.INT32:case A.FIXED32:case A.UINT32:case A.SFIXED32:case A.SINT32:o=Number.parseInt(i);break;case A.BOOL:se(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,A.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;se(e!==A.BYTES&&e!==A.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 A.INT32:i="int32";break;case A.STRING:o=n||!e.length,r=Le.LengthDelimited,i="string";break;case A.BOOL:o=e===!1,i="bool";break;case A.UINT32:i="uint32";break;case A.DOUBLE:r=Le.Bit64,i="double";break;case A.FLOAT:r=Le.Bit32,i="float";break;case A.INT64:o=n||pe.from(e).isZero(),i="int64";break;case A.UINT64:o=n||dt.from(e).isZero(),i="uint64";break;case A.FIXED64:o=n||dt.from(e).isZero(),r=Le.Bit64,i="fixed64";break;case A.BYTES:o=n||!e.byteLength,r=Le.LengthDelimited,i="bytes";break;case A.FIXED32:r=Le.Bit32,i="fixed32";break;case A.SFIXED32:r=Le.Bit32,i="sfixed32";break;case A.SFIXED64:o=n||pe.from(e).isZero(),r=Le.Bit64,i="sfixed64";break;case A.SINT32:i="sint32";break;case A.SINT64:o=n||pe.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function Sk(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Rg,{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]=Gu(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function Wu(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 vk(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"?A.INT32:r.T;if(!(r.repeat?Ag(c,n,o):Ig(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?Mg(r.V.T(),Rd(n),Rd(o)):Ag(r.V.kind=="enum"?A.INT32:r.V.T,Rd(n),Rd(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?Mg(d,n,o):d.equals(n,o)))return!1;break}}return!0}const Rd=Object.values;function Ig(s,t,e){if(t===e)return!0;if(s!==A.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 Ag(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Ig(s,t[r],e[r]))return!1;return!0}function Mg(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 Tk=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class v{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(lk),this.options=r!=null?r:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},Tk),{[Rg]:{value:this}})),this.refTypeCheck=new hk(this),this.refJsonReader=new pk(this),this.refJsonWriter=new mk(this),this.refBinReader=new gk(this),this.refBinWriter=new fk(this)}create(t){let e=Sk(this);return t!==void 0&&Wu(this,e,t),e}clone(t){let e=this.create();return Wu(this,e,t),e}equals(t,e){return vk(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){Wu(this,t,e)}fromBinary(t,e){let r=Z_(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,ck(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,dk(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=ak(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 ${Fu(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 Zs;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(Zs||(Zs={}));var er;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(er||(er={}));class yk 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 Dg=new yk;class Ek 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 bk=new Ek;class wk extends v{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new wk;class Pk extends v{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Zs]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const Ss=new Pk;class _k 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 kk=new _k;class Rk 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:()=>Ss},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>kk}])}}const Ck=new Rk;class Ik 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 Ak=new Ik;class Mk extends v{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ss},{no:3,name:"transcription_enabled",kind:"scalar",opt:!0,T:8},{no:4,name:"producer_ids",kind:"scalar",repeat:2,T:9}])}}const Og=new Mk;class Dk extends v{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ss}])}}const Ok=new Dk;class Nk extends v{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ss}])}}new Nk;class Vk 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 Lk=new Vk;class xk 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 Uk=new xk;class $k 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 $k;class Bk 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 Bk;class Fk extends v{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",er]},{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:()=>Dg}])}}const no=new Fk;class Hk extends v{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>no},{no:3,name:"producer_track",kind:"message",T:()=>Uk},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const qk=new Hk;class jk extends v{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>qk}}])}}const Ng=new jk;class Gk extends v{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>xg},{no:2,name:"receiver",kind:"message",T:()=>xg}])}}const Vg=new Gk;class Wk extends v{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Dg},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>bk}])}}const Lg=new Wk;class Jk extends v{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Lg},{no:2,name:"video",kind:"message",T:()=>Lg}])}}const xg=new Jk;class Kk 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 zk=new Kk;class Yk 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 Ug=new Yk;class Qk 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 Xk=new Qk;class Zk 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:()=>Xk},{no:9,name:"capabilities",kind:"message",T:()=>Vg}])}}const eR=new Zk;class tR extends v{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const sR=new tR;class rR extends v{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const iR=new rR;class nR 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 nR;class aR 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:()=>zk},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Ug}])}}const oR=new aR;class cR extends v{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>oR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const dR=new cR;class lR extends v{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Ug},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const uR=new lR;class hR extends v{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>uR},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const pR=new hR;class mR 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:()=>Ss},{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 gR=new mR;class fR extends v{constructor(){super("media.edge.SelectedPeersRequest",[])}}new fR;class SR extends v{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const vR=new SR;class TR 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 Cd=new TR;class yR 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 yR;class ER extends v{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>Ss},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const bR=new ER;class wR 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:()=>Ss},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const PR=new wR;class _R extends v{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new _R;class kR extends v{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const $g=new kR;class RR 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 CR=new RR;class IR 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 AR=new IR;class MR 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 DR=new MR;class OR 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 NR=new OR;class VR 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 LR=new VR;class xR extends v{constructor(){super("media.edge.EmptyResponse",[])}}new xR;class UR 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:()=>no},{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:()=>Vg}])}}const Bg=new UR;class $R 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 Ju=new $R;class BR 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 FR=new BR;class HR extends v{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>FR}])}}const Fg=new HR;class qR extends v{constructor(){super("media.edge.PeerJoinResponse",[])}}new qR;class jR extends v{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>NR},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Bg},{no:3,name:"selected_peers",kind:"message",T:()=>Ju},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const Ku=new jR;class GR extends v{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const WR=new GR;class JR extends v{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Ng}])}}new JR;class KR extends v{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Ng},{no:3,name:"description",kind:"message",T:()=>Ss}])}}const zR=new KR;class YR 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:()=>Ss}])}}const QR=new YR;class XR extends v{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>Lk}])}}new XR;class ZR 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 ZR;class eC extends v{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new eC;class tC extends v{constructor(){super("media.edge.ProducerToggleResponse",[])}}new tC;class sC extends v{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new sC;class rC extends v{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ss}])}}const iC=new rC;class nC extends v{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>Ss}])}}const aC=new nC;class oC extends v{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new oC;class cC extends v{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new cC;class dC extends v{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new dC;class lC extends v{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const uC=new lC;class hC extends v{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const pC=new hC;class mC extends v{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const gC=new mC;class fC extends v{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Bg}])}}const Hg=new fC;class SC extends v{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const qg=new SC;class vC extends v{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>qg},{no:3,name:"screenshare",kind:"message",T:()=>qg}])}}const TC=new vC;class yC extends v{constructor(){super("media.edge.PeerProducingTransportCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"transport_details",kind:"message",T:()=>Og},{no:3,name:"track_subscriptions",kind:"message",repeat:1,T:()=>TC}])}}new yC;class EC extends v{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>no}])}}const bC=new EC;class wC extends v{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>no},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const jg=new wC;class PC extends v{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>no}])}}const _C=new PC;class kC extends v{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const zu=new kC;class RC extends v{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Gg=new RC;class CC extends v{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new CC;class IC extends v{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new IC;class AC extends v{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new AC;class MC 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 MC;class DC extends v{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new DC;class OC extends v{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new OC;class NC 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 Yu=new NC;class VC 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 VC;class LC 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 xC=new LC;var vi;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(vi||(vi={}));var tr;(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"})(tr||(tr={}));var Qu;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Qu||(Qu={}));var Xu;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(Xu||(Xu={}));var Id;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(Id||(Id={}));class UC 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 $C=new UC;class BC 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",tr,"STAGE_TYPE_"]},{no:5,name:"custom_participant_id",kind:"scalar",opt:!0,T:9},{no:6,name:"preset_id",kind:"scalar",opt:!0,T:9},{no:7,name:"display_picture_url",kind:"scalar",opt:!0,T:9},{no:8,name:"waitlisted",kind:"scalar",T:8},{no:9,name:"flags",kind:"message",T:()=>$C}])}}const Ad=new BC;class FC extends v{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Ad}])}}const Rn=new FC;class HC 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",tr,"STAGE_TYPE_"]}])}}const Wg=new HC;class qC 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 jC=new qC;class GC extends v{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Ad}])}}const Zu=new GC;class WC extends v{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const Jg=new WC;class JC 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:()=>zC},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Kg=new JC;class KC 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",vi]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const zC=new KC;class YC extends v{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Kg}])}}const zg=new YC;class QC extends v{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Yg=new QC;class XC 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 XC;class ZC extends v{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Ad},{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",Id,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const e0=new ZC;class t0 extends v{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Ad},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const s0=new t0;class r0 extends v{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Kg}])}}new r0;class i0 extends v{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new i0;class n0 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 eh=new n0;class a0 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 o0=new a0;class c0 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:()=>o0}])}}const Qg=new c0;class d0 extends v{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>Qg},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>Qg}])}}const l0=new d0;class u0 extends v{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const h0=new u0;class p0 extends v{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>h0}])}}const m0=new p0;class g0 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:()=>eh}])}}const f0=new g0;class S0 extends v{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>f0}])}}const Xg=new S0;class v0 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 T0=new v0;class y0 extends v{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>T0}])}}new y0;class E0 extends v{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const b0=new E0;class w0 extends v{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>b0}])}}const P0=new w0;class _0 extends v{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>C0}])}}const k0=new _0;class R0 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:()=>eh}])}}const C0=new R0;class I0 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 A0=new I0;class M0 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:()=>A0}])}}const D0=new M0;class O0 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:()=>eh}])}}const Zg=new O0;class N0 extends v{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Zg}])}}new N0;class V0 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 L0=new V0;class x0 extends v{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>B0}])}}const U0=new x0;class $0 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 B0=new $0;class F0 extends v{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const ef=new F0;class H0 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",Xu,"BROADCAST_TYPE_"]}])}}const ao=new H0;class q0 extends v{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const j0=new q0;class G0 extends v{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const W0=new G0;class J0 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 K0=new J0;class z0 extends v{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>K0}])}}const tf=new z0;class Y0 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 sf=new Y0;var th;(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"})(th||(th={}));var Or;(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"})(Or||(Or={}));class Q0 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 X0=new Q0;class Z0 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 eI=new Z0;class tI 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 sI=new tI;class rI 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 iI=new rI;class nI extends v{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>sI},{no:2,name:"private",kind:"message",T:()=>iI}])}}const aI=new nI;class oI 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 cI=new oI;class dI extends v{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Or,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",Or,"STREAM_PERMISSION_TYPE_"]}])}}const sh=new dI;class lI extends v{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>sh},{no:2,name:"audio",kind:"message",T:()=>sh},{no:3,name:"screenshare",kind:"message",T:()=>sh}])}}const uI=new lI;class hI extends v{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>X0},{no:2,name:"plugins",kind:"message",T:()=>eI},{no:3,name:"chat",kind:"message",T:()=>aI},{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",th,"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",Qu,"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:()=>cI},{no:23,name:"media",kind:"message",T:()=>uI}])}}const rh=new hI;class pI extends v{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const mI=new pI;class gI 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 fI=new gI;class SI extends v{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>fI}])}}const vI=new SI;class TI extends v{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>rh}])}}const rf=new TI;class yI extends v{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>rf}])}}const EI=new yI;class bI extends v{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>rf}])}}const nf=new bI;class wI 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 PI=new wI;class _I extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>PI},{no:2,name:"patch",kind:"message",T:()=>rh}])}}new _I;class kI extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>rh}])}}new kI;class RI 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 Nr=new RI;class CI 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 II=new CI;class AI 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:()=>II}])}}const MI=new AI;class DI extends v{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Nr},{no:2,name:"next",kind:"scalar",T:8}])}}const OI=new DI;class NI extends v{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Nr}])}}const af=new NI;class VI 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 LI=new VI;class xI extends v{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Nr}])}}const ih=new xI;class UI 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 $I=new UI;class BI extends v{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Nr}])}}const nh=new BI;class FI 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 FI;class HI extends v{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Nr}])}}new HI;class qI 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 jI=new qI;class GI 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 WI=new GI;class JI 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:()=>Nr}])}}const Md=new JI;class KI extends v{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Nr}])}}const Dd=new KI;class zI 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 YI=new zI;class QI 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 Od=new QI;class XI 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 ZI=new XI;class eA 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 eA;class tA extends v{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new tA;class sA 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 sA;class rA 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 rA;class iA extends v{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new iA;class nA extends v{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new nA;class aA extends v{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Nr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const oA=new aA;class cA 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:()=>oA},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const dA=new cA;class lA extends v{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>dA}])}}new lA;class uA 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 hA=new uA;class pA extends v{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>hA}])}}new pA;class mA extends v{constructor(){super("socket.plugin.AddPluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const gA=new mA;class fA extends v{constructor(){super("socket.plugin.RemovePluginRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9},{no:2,name:"staggered",kind:"scalar",T:8}])}}const SA=new fA;class vA extends v{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const TA=new vA;class yA extends v{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}const EA=new yA;class bA 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}])}}const wA=new bA;class PA 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}])}}const _A=new PA;class kA 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}])}}const RA=new kA;class CA 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}])}}const IA=new CA;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 ah=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:()=>ah}])}}const of=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:()=>ah}])}}const OA=new DA;class NA 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:()=>ah}])}}const VA=new NA;class LA 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}])}}const xA=new LA;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 oh=new UA;class $A extends v{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>oh}])}}const BA=new $A;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}])}}const cf=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 df=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}])}}const lf=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 uf=new WA;class JA extends v{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const hf=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 ch=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 pf=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 mf=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:()=>mf}])}}const dh=new uM;class hM extends v{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>mf}])}}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",vi]}])}}const gf=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=pe.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(pe.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=pe.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=pe.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 "+Fu(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=pe.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 lh=new fM;class SM extends v{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>lh}])}}new SM;class vM extends v{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>lh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>lh}])}}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},RM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},ff={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 oo(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function Sf(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const x=oo(TM,PM),qe=oo(yM,_M),j=oo(EM,kM),sr=oo(bM,RM),Vr=Sf(ff,16777216),vs=Sf(ff,50331648),Nd=oo(wM,CM);var IM=Object.defineProperty,AM=Object.getOwnPropertyDescriptor,Lr=(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},es=(s=>(s[s.TEXT=0]="TEXT",s[s.IMAGE=1]="IMAGE",s[s.FILE=2]="FILE",s[s.CUSTOM=3]="CUSTOM",s))(es||{});class rr{constructor(t,e){g(this,qt,void 0);g(this,Hn,void 0);f(this,qt,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,qt).sendMessagePromise(qe.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,qt).sendMessagePromise(qe.getPaginatedMessages,MI.toBinary(n));return o.payload?OI.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,qt).sendMessage(qe.sendMessageToRoom,LI.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,qt).sendMessage(qe.sendMessageToPeers,$I.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,qt).sendMessagePromise(qe.editMessage,jI.toBinary(n));return Dd.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,qt).sendMessagePromise(qe.deleteMessage,YI.toBinary(e));return{id:Od.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,qt).sendMessagePromise(qe.searchChannelMessages,ZI.toBinary(r));return af.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,qt).sendMessagePromise(qe.pinMessage,WI.toBinary(r));return Md.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case qe.sendMessageToRoom:{r=ih.fromBinary.bind(ih),i=ih.create();break}case qe.sendMessageToPeers:{r=nh.fromBinary.bind(nh),i=nh.create();break}case qe.editMessage:{r=Dd.fromBinary.bind(Dd),i=Dd.create();break}case qe.pinMessage:{r=Md.fromBinary.bind(Md),i=Md.create();break}case qe.deleteMessage:{r=Od.fromBinary.bind(Od),i=Od.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,qt).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)})}}qt=new WeakMap,Hn=new WeakMap,Lr([E.trace("SocketService.getChatMessages")],rr.prototype,"getChatMessages",1),Lr([E.trace("SocketService.getChatMessagesPaginated")],rr.prototype,"getChatMessagesPaginated",1),Lr([E.trace("SocketService.sendMessageToRoom")],rr.prototype,"sendMessageToRoom",1),Lr([E.trace("SocketService.sendMessageToPeers")],rr.prototype,"sendMessageToPeers",1),Lr([E.trace("SocketService.sendMessage")],rr.prototype,"sendMessage",1),Lr([E.trace("SocketService.editMessage")],rr.prototype,"editMessage",1),Lr([E.trace("SocketService.deleteMessage")],rr.prototype,"deleteMessage",1),Lr([E.trace("SocketService.searchMessages")],rr.prototype,"searchMessages",1);function MM(s){return s.replace(/([-_]\w)/g,t=>t[1].toUpperCase())}function Us(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>Us(e));const t={};return Object.keys(s).forEach(e=>{const r=uu(e)?e:MM(e);t[r]=Us(s[e])}),t}function DM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function vf(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>vf(e));const t={};return Object.keys(s).forEach(e=>{const r=uu(e)?e:DM(e);t[r]=s[e]}),t}function Vd(s,t={}){return s==null?{}:(Object.getOwnPropertyNames(s).forEach(e=>{if(typeof s[e]!="function"){if(typeof s[e]=="object"){Vd(s[e],t[e]={});return}t[e]=s[e]}}),t)}class uh extends Error{constructor(e){var t=(...DN)=>{super(...DN);p(this,"status");p(this,"response");p(this,"isTimeout")};e instanceof Error?(t(e.message),this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(t(`Request failed with status ${e.status}`),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 Tf{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 P=y.headers.get("content-type");P&&P.includes("application/json")?w=await y.json():w=await y.text();const C={};y.headers.forEach(($,L)=>{C[L]=$});const O={data:w,status:y.status,statusText:y.statusText,headers:C,config:t};if(!y.ok)throw O;return O}catch(m){if(m instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,u)),this.defaults.baseURL===Si.apiBase.prod?this.defaults.baseURL=Si.apiBase.prodAlternate:this.defaults.baseURL===Si.apiBase.prodAlternate&&(this.defaults.baseURL=Si.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,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,"pluginInformation");p(this,"userDetails");p(this,"roomDetails");p(this,"context");this.context=t;const{timeout:r=VM,retry:i=OM,retryDelay:n=NM,baseURL:o=Si.apiBase.prod,authToken:c,cachedUserDetails:d}=e||{};this.iceServers=d==null?void 0:d.iceServers,this.pluginInformation=d==null?void 0:d.pluginInformation,this.userDetails=d==null?void 0:d.userDetails,this.roomDetails=d==null?void 0:d.roomDetails,this.requests=new Tf({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new Tf({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,P;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 k("Unknown network error occurred","0011");if(C instanceof k||C instanceof uh)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:(P=C.config)==null?void 0:P.method,isOnline:navigator.onLine?"online":"offline"}});const O=C instanceof Error&&C.message||"Network request failed";throw new k(O,"0011"),new uh(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,$s=(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 Ts 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 getPlugins(){var n,o,c,d,l;if(this.pluginInformation)return this.pluginInformation;const{plugins:e}=(await this.requests.get("/v2/plugins/user")).data.data,r=k_,i=e.reduce((u,h)=>(u[r.includes(h.id)?"v1":"v2"].push({...h,name:h.name.replace("v2","")}),u),{v1:[],v2:[]});return(c=(o=(n=this.context.getValue("modules"))==null?void 0:n.devTools)==null?void 0:o.plugins)!=null&&c.length&&((l=(d=this.context.getValue("modules"))==null?void 0:d.devTools)==null||l.plugins.forEach(u=>{var m,S,y;const h={...ro,tags:[...ro.tags],baseUrl:`http://localhost:${u.port}`,name:u.name,picture:(m=u.picture)!=null?m:ro.picture,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),id:u.id,organizationId:this.organizationId,description:(S=u.description)!=null?S:ro.description,staggered:(y=u.staggered)!=null?y:ro.staggered};i.v2.push(h)})),i.v2}async getPluginDetails(e){const{plugin:r}=(await this.requests.get(`/v2/plugins/view/${e}`)).data.data;return r}async getPluginConfig(e){return(await this.fetchClient.get(`${e}/dyte-config.json`)).data}async authorizePlugin(e){const r={peerId:this.peerId},{token:i}=(await this.requests.post(`/v2/plugins/authorize/${e}`,r)).data.data;return i}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=Us(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=Us((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 Us(e)}async startRecording(e,r){return(await this.requests.post("/v2/recordings",{...vf(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 k("Cant fetch transcript s3 url","1801")}}}$s([E.trace("APIClient.getICEServers")],Ts.prototype,"getICEServers",1),$s([E.trace("APIClient.getPlugins")],Ts.prototype,"getPlugins",1),$s([E.trace("APIClient.startLivestreaming")],Ts.prototype,"startLivestreaming",1),$s([E.trace("APIClient.stopLivestreaming")],Ts.prototype,"stopLivestreaming",1),$s([E.trace("APIClient.getActiveLivestream")],Ts.prototype,"getActiveLivestream",1),$s([E.trace("APIClient.getUserDetails")],Ts.prototype,"getUserDetails",1),$s([E.trace("APIClient.startRecording")],Ts.prototype,"startRecording",1),$s([E.trace("APIClient.stopRecording")],Ts.prototype,"updateRecording",1),$s([E.trace("APIClient.getActiveRecording")],Ts.prototype,"getActiveRecording",1),$s([E.trace("APIClient.getActiveTranscript")],Ts.prototype,"getActiveTranscript",1);let hh;function $M(s,t){return hh=new Ts(s,t),hh}function vt(){return hh}const Cn={maxInvocations:5,period:1};function It(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 k(`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,ys=(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"],Ld={maxInvocations:180,period:60};let $t=(IS=class extends Ut{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,pl);g(this,Ro);p(this,"messages");g(this,te,void 0);g(this,Mi,void 0);g(this,Qe,void 0);g(this,qn,void 0);p(this,"maxTextLimit",2e3);f(this,qn,t),f(this,Qe,e),f(this,te,r),f(this,Mi,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 k("Max character limit breached","0503");if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.text))throw this.logger.error("sendTextMessage::private_chat_permission_denied"),new k("Could not send message to private chat.","0501")}else if(!((c=(o=a(this,te).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,te).permissions)==null?void 0:d.chatPublic)!=null&&l.text))throw this.logger.error("sendTextMessage::public_chat_permission_denied"),new k("Could not send message to public chat.","0501");if(!t)throw this.logger.error("sendTextMessage::message_can_not_be_empty"),new k("Message can not be empty.","0502");let r=[];e&&e.length>0&&(e.push(a(this,te).id),r=a(this,Mi).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,te).userId)),a(this,Qe).sendMessage(t,es.TEXT,e)}async sendImageMessageInternal(t,e){var i,n,o,c,d,l;if(e&&e.length>0){if(!((i=a(this,te).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,te).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,te).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,te).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=vt(),{getLocation:h,putLocation:m}=await u.getPresignedUrls(t.name);await u.uploadFile(t,m);let S=[];e&&e.length>0&&(e.push(a(this,te).id),S=a(this,Mi).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),S.push(a(this,te).userId)),a(this,Qe).sendMessage(h,es.IMAGE,e)}catch(u){throw new k("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,te).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,te).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,te).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,te).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=vt(),{getLocation:u,putLocation:h}=await l.getPresignedUrls(t.name);await l.uploadFile(t,h);let m=[];e&&e.length>0&&(e.push(a(this,te).id),m=a(this,Mi).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),m.push(a(this,te).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,Qe).sendMessage(S,es.FILE,e)}catch(l){throw new k("Error sending file message.","0500",this.logger)}}get rateLimits(){return Ld}updateRateLimits(t,e){Ld.maxInvocations=t,Ld.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,P,C,O,$;if(e&&e.length>0){if(!((n=a(this,te).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,te).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,te).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,te).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,te).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((S=(m=a(this,te).permissions)==null?void 0:m.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async L=>{try{if(typeof L=="string")return{link:L};const F=vt(),{getLocation:Q,putLocation:X}=await F.getPresignedUrls(L.name);return await F.uploadFile(L,X),{link:Q,type:L.type,name:L.name,size:L.size}}catch(F){throw new k("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 L=>r(L))),images:await Promise.all((C=(P=t.images)!=null?P:[])==null?void 0:C.map(async L=>r(L))),videos:await Promise.all(($=(O=t.videos)!=null?O:[])==null?void 0:$.map(async L=>r(L)))};a(this,Qe).sendMessage(JSON.stringify(i),es.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,te).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,te).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,Qe).editMessage(t,e,es.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,te).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,te).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=vt(),{getLocation:l,putLocation:u}=await d.getPresignedUrls(e.name);await d.uploadFile(e,u),a(this,Qe).editMessage(t,l,es.IMAGE)}catch(d){throw new k("Error editing image message.","0500",this.logger)}}async editFileMessage(t,e){var r,i,n,o;if(!((i=(r=a(this,te).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,te).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=vt(),{getLocation:d,putLocation:l}=await c.getPresignedUrls(e.name);await c.uploadFile(e,l),a(this,Qe).editMessage(t,JSON.stringify({link:d,name:e.name,size:"size"in e?e.size:0}),es.FILE)}catch(c){throw new k("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,Qe).deleteMessage(t)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!a(this,Ro,zh))throw new k("Can`t pin message without joining room","0505");try{await a(this,Qe).setPinState(t,!0)}catch(e){throw new k(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,Ro,zh))throw new k("Can`t unpin message without joining room","0505");try{await a(this,Qe).setPinState(t,!1)}catch(e){throw new k(`No message found with id: ${t}`,"0504")}}async fetchPublicMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,Qe).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>ts.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,Qe).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>ts.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,Qe).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>ts.formatSocketPeerMessage(o))}async getMessages(t,e,r,i=0){const n=await a(this,Qe).getChatMessagesPaginated(t,e,r);return{messages:n.messages.map(o=>ts.formatSocketPeerMessage(o)),next:n.next}}async searchMessages(t,e){throw new k("searchMessages is disabled! Please use `fetchPublicMessages` method instead.","0506")}get pinned(){return this.messages.filter(t=>t.pinned)}},te=new WeakMap,Mi=new WeakMap,Qe=new WeakMap,qn=new WeakMap,pl=new WeakSet,KS=function(){return a(this,qn).getValue("connectionHandler")},Ro=new WeakSet,zh=function(){return a(this,pl,KS).socketJoined===!0},IS);ys([E.trace("Chat.sendTextMessage"),It(Ld)],$t.prototype,"sendTextMessage",1),ys([E.trace("Chat.sendImageMessage"),It({maxInvocations:20,period:60})],$t.prototype,"sendImageMessage",1),ys([E.trace("Chat.sendFileMessage"),It({maxInvocations:20,period:60})],$t.prototype,"sendFileMessage",1),ys([E.trace("Chat.sendMessage"),It({maxInvocations:180,period:60})],$t.prototype,"sendMessage",1),ys([E.trace("Chat.editTextMessage")],$t.prototype,"editTextMessage",1),ys([E.trace("Chat.editImageMessage")],$t.prototype,"editImageMessage",1),ys([E.trace("Chat.editFileMessage")],$t.prototype,"editFileMessage",1),ys([E.trace("Chat.editMessage")],$t.prototype,"editMessage",1),ys([E.trace("Chat.deleteMessage")],$t.prototype,"deleteMessage",1),ys([E.trace("Chat.searchMessages")],$t.prototype,"searchMessages",1),$t=ys([ct("0500")],$t);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 xr=(AS=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");g(this,Di,void 0);f(this,Di,s),this.chatSocketHandler=t,this.chat=new $t(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,Di).getValue("telemetry")}get logger(){return a(this,Di).getValue("logger")}static async init(s,t,e,r){return new xr(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 es.TEXT:{e.message=s.payload;break}case es.IMAGE:{e.link=s.payload;break}case es.FILE:{const{link:r,name:i,size:n}=JSON.parse(s.payload);e.link=r,e.name=i,e.size=n;break}case es.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 xr.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=af.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>xr.formatSocketPeerMessage(e))}setupEvents(){a(this,Di).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(qe.sendMessageToRoom,s=>{if(!s.message)return;const t=xr.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(qe.sendMessageToPeers,s=>{const t=xr.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(qe.editMessage,s=>{if(!s.message)return;const t=xr.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(qe.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(qe.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=xr.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})})}},Di=new WeakMap,AS);let ts=xr;GM([E.trace("ChatController.setupEvents")],ts.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 ph=(MS=class extends Ut{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,Co,void 0);f(this,Co,t),f(this,jn,e),f(this,Gn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,gl,YS))throw new k("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,zS=function(){return a(this,Co).getValue("connectionHandler")},gl=new WeakSet,YS=function(){var t;return((t=a(this,ml,zS))==null?void 0:t.socketJoined)===!0},jn=new WeakMap,Gn=new WeakMap,Co=new WeakMap,MS);ph=KM([ct("0700")],ph);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=(DS=class{constructor(s,t,e){p(this,"polls");g(this,Jr,void 0);g(this,Wn,void 0);g(this,Oi,void 0);this.polls=new ph(s,t,e),f(this,Wn,t),f(this,Jr,s),f(this,Oi,e),this.setupEvents()}get telemetry(){return a(this,Jr).getValue("telemetry")}get logger(){return a(this,Jr).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={[sr.createPoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))},[sr.updatePoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))},[sr.votePoll]:r=>{r.poll&&this.updatePoll(In.formatSocketServicePoll(r.poll))}},t=()=>{a(this,Jr).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Oi).on(r,s[r])})},e=()=>{a(this,Jr).getValue("peerSessionStore").on(_.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}}},Jr=new WeakMap,Wn=new WeakMap,Oi=new WeakMap,DS);let yf=In;QM([E.trace("PollController.setupEvents")],yf.prototype,"setupEvents",1);var XM=Object.defineProperty,ZM=Object.getOwnPropertyDescriptor,e1=(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},Ef=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(Ef||{});let mh=(OS=class extends Ut{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);g(this,Io);p(this,"selfActiveTab");p(this,"broadcastTabChanges");g(this,Jn,void 0);g(this,Ni,void 0);g(this,Ao,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,Jn,t),f(this,Ni,e),this.viewType=r,f(this,Ao,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Io,Yh).socketState}get mediaState(){return a(this,Io,Yh).mediaState}get meetingId(){return a(this,Jn).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,Ni).permissions.canSpotlight)throw this.logger.error("Spotlight::setSpotlighted::permission_denied"),new k("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,Ni).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,Ao).broadcastMessage("spotlight",{userId:a(this,Ni).userId,currentTab:this.selfActiveTab})}},Jn=new WeakMap,Io=new WeakSet,Yh=function(){return a(this,Jn).getValue("connectionHandler")},Ni=new WeakMap,Ao=new WeakMap,OS);mh=e1([ct("0800")],mh);function t1(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
|
|
14
|
-
`).map(e=>Ur.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=vt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Ur.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)}},Mo=new WeakMap,NS);bf([E.trace("Ai.getActiveTranscript")],Ur.prototype,"getActiveTranscript",1),Ur=bf([ct("0000")],Ur);var i1=Object.defineProperty,n1=Object.getOwnPropertyDescriptor,a1=(s,t,e,r)=>{for(var i=r>1?void 0:r?n1(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&&i1(t,e,i),i};const wf=(VS=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");g(this,Kr,void 0);g(this,Kn,void 0);p(this,"aiSocketHandler");g(this,jt,void 0);f(this,jt,s),this.meta=new mh(s,t,t.config.viewType,e,n),this.ai=r,f(this,Kr,t),f(this,Kn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,jt).getValue("telemetry")}get logger(){return a(this,jt).getValue("logger")}static async init(s,t,e,r,i){const n=await Ur.init(s,t.permissions.transcriptionEnabled);return new wf(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,Ef.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,jt).getValue("peerSessionStore").on(_.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,jt).getValue("peerSessionStore").on(_.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,jt).getValue("peerSessionStore").on(_.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,jt).getValue("peerSessionStore").on(_.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,Kr).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,Kn).broadcastMessage("spotlight",{userId:a(this,Kr).userId,currentTab:this.meta.selfActiveTab})),a(this,jt).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async s=>{a(this,Kr).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,Kn).broadcastToPeers("spotlight",[s.id],{userId:a(this,Kr).userId,currentTab:this.meta.selfActiveTab})}),a(this,jt).getValue("peerSessionStore").on(_.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,jt).getValue("peerSessionStore").on(_.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(x.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Ur.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),this.meta.emit("transcript",i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},Kr=new WeakMap,Kn=new WeakMap,jt=new WeakMap,VS);let Pf=wf;a1([E.trace("MetaController.setupEvents")],Pf.prototype,"setupEvents",1);const co={},ir={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(co[u]){const P=new Error(`Unsupported concurrent calls on method: ${s}.`);throw P.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:P.stack},locker:{methodName:s,lockName:u}}),P}co[u]=!0;const m=setTimeout(()=>delete co[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete co[u],clearTimeout(m)}).catch(()=>{delete co[u],clearTimeout(m)}),S},n}}};var o1=Object.defineProperty,c1=Object.getOwnPropertyDescriptor,Ti=(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 $r extends Ut{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);g(this,Oo);g(this,zn);g(this,is,void 0);g(this,fl,void 0);g(this,ne,void 0);g(this,Do,void 0);g(this,Bs,void 0);g(this,Xe,void 0);f(this,Xe,e),f(this,is,n),f(this,fl,o),f(this,ne,r),f(this,Do,i),f(this,Bs,[]),this.setupEvents()}get telemetry(){return a(this,Xe).getValue("telemetry")}get status(){return a(this,Xe).getValue("stageStatus")}setupEvents(){const e={[_.GET_STAGE_REQUESTS]:async n=>{f(this,Bs,n)},[_.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Bs).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,Xe).getValue("peerSessionStore").onAsync(n,o)})},i=()=>{Object.entries(e).forEach(([n,o])=>{a(this,Xe).getValue("peerSessionStore").removeListener(n,o)})};a(this,ne).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,ne).permissions.acceptStageRequests?(r(),a(this,is).getStageRequests()):(i(),f(this,Bs,[]),this.emit("stageAccessRequestUpdate",a(this,Bs))))}),a(this,ne).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::get_access_request::permission_denied"),new k("You do not have permission to perform this action","2001");const e=a(this,Do).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Bs,e),{stageRequests:a(this,Bs)}}async requestAccess(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(this.status!=="OFF_STAGE")throw new k(`Unable to request access you are currently ${this.status}`,"2006");if(a(this,ne).permissions.stageAccess===H.Allowed){U(this,zn,au).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,is).requestAccess(),U(this,zn,au).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");a(this,is).cancelRequestAccess(),U(this,zn,au).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,ne).roomJoined)throw new k("Can`t grant for participant without joining room");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::grant_access::permission_denied"),new k("You do not have permission to perform this action","2001");return a(this,is).grantAccess(e)}denyAccess(e){if(!a(this,ne).roomJoined)throw new k("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::deny_access::permission_denied"),new k("You do not have permission to perform this action","2001");return a(this,is).denyAccess(e)}get peerId(){return a(this,Xe).getValue("peerId")}async join(){const e=a(this,Xe).getValue("viewType");if(this.status==="ON_STAGE")throw new k("You are already on stage.","2006");if(this.status!=="ACCEPTED_TO_JOIN_STAGE"||a(this,ne).permissions.stageAccess===H.NotAllowed)throw new k(`Unable to join stage you are currently ${this.status}`,"2006");if(a(this,Xe).setValue("stageStatus","ON_STAGE",!1),await a(this,is).joinStage(),e===Qs.Livestream){await a(this,Xe).getValue("selfController").joinRoom();return}a(this,Xe).notify("stageStatus"),a(this,ne).audioEnabled&&a(this,Oo,Qh).shareMic(a(this,ne).audioTrack),a(this,ne).videoEnabled&&a(this,Oo,Qh).shareWebcam(a(this,ne).videoTrack)}async leave(){if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!(this.status==="ON_STAGE"||this.status==="ACCEPTED_TO_JOIN_STAGE"))throw new k(`Unable to leave stage you are currently ${this.status}`,"2006");a(this,ne).setIsPinned(!1),a(this,Xe).setValue("stageStatus","OFF_STAGE",!1),await a(this,is).leaveStage(a(this,ne).userId);try{await a(this,Xe).getValue("peerSessionStore").emitAsync(_.LEAVE_MEDIA_ROOM,"stageLeft")}catch(e){this.logger.error("Stage::leave::emitAsync::failed",{error:e})}a(this,Xe).notify("stageStatus")}async kick(e){if(!a(this,ne).roomJoined)throw new k("Can`t kick participant without joining room","2005");if(!a(this,ne).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new k("Stage is disabled","2003");if(!a(this,ne).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new k("You do not have permissions for kick","2001");return a(this,is).kick(e)}}is=new WeakMap,fl=new WeakMap,ne=new WeakMap,Do=new WeakMap,Bs=new WeakMap,Xe=new WeakMap,Oo=new WeakSet,Qh=function(){return a(this,Xe).getValue("roomNodeClient")},zn=new WeakSet,au=async function(e){this.status!==e&&a(this,Xe).setValue("stageStatus",e)},Ti([E.trace("Stage.getStageRequests")],$r.prototype,"getAccessRequests",1),Ti([E.trace("Stage.requestAccess")],$r.prototype,"requestAccess",1),Ti([E.trace("Stage.cancelRequestAccess")],$r.prototype,"cancelRequestAccess",1),Ti([E.trace("Stage.grantAccess")],$r.prototype,"grantAccess",1),Ti([E.trace("Stage.denyAccess")],$r.prototype,"denyAccess",1),Ti([ir.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],$r.prototype,"join",1),Ti([E.trace("Stage.leaveStage")],$r.prototype,"leave",1);function d1(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function gh(s){switch(s){case tr.UNSPECIFIED:return"OFF_STAGE";case tr.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case tr.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case tr.OFF_STAGE:return"OFF_STAGE";case tr.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}var l1=Object.defineProperty,u1=Object.getOwnPropertyDescriptor,h1=(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};class _f{constructor(t,e,r,i,n){p(this,"stage");g(this,zr,void 0);g(this,Ps,void 0);g(this,Yr,void 0);g(this,No,0);g(this,bt,void 0);f(this,bt,t),this.stage=new $r(t,i,n,e,r),f(this,Yr,e),f(this,zr,i),f(this,Ps,n),this.setupEvents()}get telemetry(){return a(this,bt).getValue("telemetry")}get logger(){return a(this,bt).getValue("logger")}setupEvents(){a(this,bt).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,Yr).on(x.grantStageAccess,()=>{a(this,zr).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,Yr).on(x.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,zr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,Yr).on(x.denyStageAccess,()=>{a(this,zr).permissions.stageAccess!==H.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,Yr).on(x.getStageRequests,async t=>{var r;if(a(this,zr).permissions.stageAccess!==H.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,bt).getValue("peerSessionStore").emitAsync(_.GET_STAGE_REQUESTS,e),a(this,No)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,No,e.length),this.stage.emit("stageAccessRequestUpdate",e)})}getCurrentStageRequests(){return a(this,Ps).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,bt).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=gh(t.stageType),r=a(this,bt).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,bt).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,bt).setValue("stageStatus","ACCEPTED_TO_JOIN_STAGE",!1),this.stage.leave();break}}async peerStageStatusHandler(t){const e=a(this,Ps).joined.get(t.peerId),r=a(this,Ps).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,bt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,Ps).viewMode,page:a(this,Ps).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,bt).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,Ps).viewMode,page:a(this,Ps).currentPage});break}a(this,bt).getValue("peerSessionStore").emit(_.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}zr=new WeakMap,Ps=new WeakMap,Yr=new WeakMap,No=new WeakMap,bt=new WeakMap,h1([E.trace("Stage.setupEvents")],_f.prototype,"setupEvents",1);var p1=Object.defineProperty,m1=Object.getOwnPropertyDescriptor,xd=(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};const Ae={getPeer:14,getPeers:15,chatMessage:16,getRoomName:17,getDisplayTitle:18,getPluginInitiator:19,customPluginEventToParent:20,peerJoined:22,peerLeft:23,sendData:24,stageStatusUpdate:25,peerStageStatusUpdate:26};let An=(LS=class extends kn{constructor(t,{baseURL:e,createdAt:r,description:i,id:n,name:o,organizationId:c,picture:d,private:l,published:u,staggered:h,tags:m,type:S,updatedAt:y},w,P,C,O,$){const L=t.getValue("logger");super(L);g(this,ut,void 0);p(this,"baseURL");p(this,"createdAt");p(this,"description");p(this,"id");p(this,"name");g(this,Gt,void 0);g(this,Yn,void 0);g(this,Qn,void 0);p(this,"organizationId");p(this,"picture");p(this,"private");p(this,"published");p(this,"staggered");p(this,"tags");p(this,"type");p(this,"updatedAt");g(this,pr,void 0);p(this,"config");g(this,Xn,void 0);p(this,"active");p(this,"iframes");p(this,"enabledBy");g(this,Qr,void 0);g(this,Zn,void 0);f(this,Qr,t),this.baseURL=e,this.createdAt=new Date(r),this.description=i,this.id=n,this.name=o,f(this,Gt,P),this.organizationId=c,this.picture=d,this.private=l,this.published=u,this.staggered=h,this.tags=m,this.type=S,this.updatedAt=new Date(y),this.active=!1,this.iframes=new Map,f(this,ut,w),f(this,Yn,C),f(this,Qn,O),this.enabledBy="",f(this,Zn,$)}get telemetry(){return a(this,Qr).getValue("telemetry")}sendIframeEvent(t){this.iframes.size&&this.iframes.forEach(e=>{const{iframe:r}=e;r&&(navigator.isReactNative?r.postMessage(JSON.stringify(t)):r.contentWindow.postMessage(t,"*"))})}async handleIframeMessage(t){var o;if(!this.active)return;const e=t,{payload:r,uuid:i,type:n}=e;switch(n){case j.customPluginEventToRoom:{a(this,ut).customPluginEventToRoom(this.id,r,i);break}case j.customPluginEventToPeers:{a(this,ut).customPluginEventToPeers(this.id,r.peerIds,r,i);break}case j.enablePluginForRoom:{a(this,ut).enablePluginForRoom(this.id,i);break}case j.enablePluginForPeers:{a(this,ut).enablePluginForPeers(this.id,r.peerIds,i);break}case j.disablePluginForRoom:{a(this,ut).disablePluginForRoom(this.id,i);break}case j.disablePluginForPeers:{a(this,ut).disablePluginForPeers(this.id,r.peerIds,i);break}case j.storeInsertKeys:{a(this,ut).storeInsertKeys(this.id,r.store,r.insertKeys,i);break}case j.storeGetKeys:{a(this,ut).storeGetKeys(this.id,r.store,r.getKeys,i);break}case j.storeDeleteKeys:{a(this,ut).storeDeleteKeys(this.id,r.store,r.deleteKeys,i);break}case j.storeDelete:{a(this,ut).storeDelete(this.id,r.store,i);break}case Ae.chatMessage:{const{messagePayload:c,peerIds:d}=r;if(!a(this,Qn)){this.sendIframeEvent({type:Ae.chatMessage,uuid:e.uuid,payload:{error:"Chat is disabled for this room."}});return}try{await a(this,Qn).sendMessage(c,d),this.sendIframeEvent({type:Ae.chatMessage,uuid:e.uuid,payload:{success:!0}})}catch(l){this.sendIframeEvent({type:Ae.chatMessage,uuid:e.uuid,payload:{error:l}})}break}case Ae.getPeer:{let c;const{peerId:d}=r,l={...a(this,Gt),id:a(this,Gt).id,isRecorder:(o=a(this,Gt).permissions)==null?void 0:o.isRecorder,isHidden:a(this,Gt).permissions.hiddenParticipant,stageStatus:a(this,Gt).stageStatus};d?(c=a(this,Yn).joined.get(r.peerId),a(this,Gt).id===d&&(c=l)):c=l,this.sendIframeEvent({type:Ae.getPeer,payload:{peer:c&&Vd(c)},uuid:e.uuid});break}case Ae.getPeers:{const c=a(this,Yn).joined.toArray().map(d=>Vd(d));this.sendIframeEvent({type:Ae.getPeers,payload:{peers:c},uuid:e.uuid});break}case Ae.getPluginInitiator:{this.sendIframeEvent({type:Ae.getPluginInitiator,payload:{enabledBy:this.enabledBy},uuid:e.uuid});break}case Ae.getDisplayTitle:{this.sendIframeEvent({type:Ae.getDisplayTitle,payload:{displayTitle:a(this,Zn)},uuid:e.uuid});break}case Ae.getRoomName:{this.sendIframeEvent({type:Ae.getRoomName,payload:{roomName:a(this,Qr).getValue("meetingId")},uuid:e.uuid});break}case Ae.customPluginEventToParent:{this.emit(e.payload.eventName,e.payload.data);break}}}sendData(t){this.active&&(this.logger.info("Plugin::SendData",{plugin:{id:this.id,name:this.name,data:{eventName:t.eventName}}}),this.sendIframeEvent({type:Ae.sendData,uuid:"",payload:t}))}removePluginView(t="default"){var i;const{iframe:e,listener:r}=(i=this.iframes.get(t))!=null?i:{};(e||r)&&(navigator.isReactNative?e.props.onMessage=void 0:window.removeEventListener("message",r),this.iframes.delete(t))}addPluginView(t,e="default"){var o;if(!a(this,Xn))throw this.logger.error("Plugin::addPluginView::no_auth_token_set_for_plugin"),new k("No auth token set for plugin.","0602");if(!t)throw this.logger.error("Plugin::addPluginView::iframe_was_not_provided"),new k("Iframe was not provided.","0603");this.removePluginView(e);const r=t,i=new URL(this.baseURL),n={auth:a(this,Xn),parent:navigator.isReactNative?this.baseURL:window.location.origin,backend:a(this,Qr).getValue("apiBase"),pluginId:this.id,roomName:(o=a(this,Qr).getValue("meetingId"))!=null?o:"",displayTitle:a(this,Zn)};if(Object.keys(n).forEach(c=>{i.searchParams.set(c,n[c])}),r.src=i.href,r.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",r.title=e,navigator.isReactNative)r.props.onMessage=c=>{this.handleIframeMessage(JSON.parse(c.nativeEvent.data))},this.iframes.set(e,{iframe:r});else{const c=async d=>{d.source===t.contentWindow&&await this.handleIframeMessage(d.data)};window.addEventListener("message",c),this.iframes.set(e,{iframe:r,listener:c})}}setActive(t){var e,r;if(this.active=t,t){this.emit("stateUpdate",{active:this.active,pluginId:this.id,bind:this.addPluginView.bind(this),views:(e=this.config)==null?void 0:e.views});return}this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id,views:(r=this.config)==null?void 0:r.views})}async activateForSelf(){const t=vt(),e=await t.authorizePlugin(this.id);f(this,Xn,e),f(this,pr,new Date);try{const r=await t.getPluginConfig(this.baseURL);this.config=r}catch(r){this.logger.error("Plugin::activateForSelf",{error:r})}this.setActive(!0),this.emit("enabled")}deactivateForSelf(){Array.from(this.iframes.keys()).forEach(t=>{this.removePluginView(t)}),f(this,pr,void 0),this.iframes.clear(),this.setActive(!1),this.emit("closed")}async enable(){return this.activateForSelf()}disable(){return this.deactivateForSelf()}async activate(){var t,e;this.active||(e=(t=a(this,Gt).permissions)==null?void 0:t.plugins)!=null&&e.canStart&&(a(this,ut).addPlugin(this.id,this.staggered),f(this,pr,new Date),this.logger.info("plugin::activated",{plugin:{id:this.id,enabledBy:this.enabledBy,name:this.name}}))}async deactivate(){var t,e;this.active&&(!((e=(t=a(this,Gt).permissions)==null?void 0:t.plugins)!=null&&e.canClose)&&this.enabledBy!==a(this,Gt).id||(a(this,ut).removePlugin(this.id),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:a(this,pr)?new Date().getTime()-a(this,pr).getTime():0}}),f(this,pr,void 0)))}},ut=new WeakMap,Gt=new WeakMap,Yn=new WeakMap,Qn=new WeakMap,pr=new WeakMap,Xn=new WeakMap,Qr=new WeakMap,Zn=new WeakMap,LS);xd([It({maxInvocations:5,period:1})],An.prototype,"sendData",1),xd([E.trace("Plugin.activatePlugin")],An.prototype,"activate",1),xd([E.trace("Plugin.deactivatePlugin")],An.prototype,"deactivate",1),An=xd([ct("0600")],An);class kf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();g(this,$e,void 0);g(this,Vi,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,Vi,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,Vi).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,Vi).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,Vi).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,Vi=new WeakMap;class Rf extends kf{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 g1=Object.defineProperty,f1=Object.getOwnPropertyDescriptor,S1=(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};let fh=class{constructor(s){p(this,"all");p(this,"active");this.all=new Rf(s),this.active=new Rf(s)}};fh=S1([ct("0600")],fh);var v1=Object.defineProperty,T1=Object.getOwnPropertyDescriptor,Ud=(s,t,e,r)=>{for(var i=r>1?void 0:r?T1(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 Cf=(xS=class{constructor(s,t,e,r){p(this,"plugins");g(this,ns,void 0);g(this,ea,void 0);g(this,_s,void 0);f(this,ns,t),f(this,ea,e),f(this,_s,s),this.plugins=r,this.setupEvents()}get telemetry(){return a(this,_s).getValue("telemetry")}get logger(){return a(this,_s).getValue("logger")}static async init(s,t,e,r,i,n,o,c){const d=s.getValue("logger"),l=new fh(d);return t.forEach(u=>{const h=new An(s,u,e,n,o,i,c);l.all.add(h)}),new Cf(s,e,r,l)}async getRoomPlugins(){var t;const{plugins:s}=await a(this,ns).getActivePlugins();(t=this.plugins.active)==null||t.toArray().forEach(e=>{this.disablePlugin({id:e.id})}),await Promise.all(s.map(e=>this.enablePlugin({id:e.pluginId,enabledBy:e.enabledBy})))}async enablePlugin({id:s,enabledBy:t}){const e=this.plugins.all.get(s);e&&(await e.activateForSelf(),e.enabledBy=t)}async disablePlugin({id:s}){const t=this.plugins.all.get(s);t&&t.deactivateForSelf()}sendIframeEvent(s,t,e,r){const i=this.plugins.all.get(t);i&&i.sendIframeEvent({type:s,uuid:e,payload:r})}broadcastIframeEvent(s,t){this.plugins.active.forEach(e=>{this.sendIframeEvent(s,e.id,"",t)})}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,_s).getValue("peerSessionStore").onAsync(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{await this.getRoomPlugins(),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to fetch plugins.")}),a(this,ns).on(j.addPlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active||await this.enablePlugin({id:t,enabledBy:s.enabledBy})}),a(this,ns).on(j.removePlugin,async s=>{var e;const t=s.pluginId;(e=this.plugins.all.get(t))!=null&&e.active&&await this.disablePlugin({id:t})}),[j.enablePluginForPeers,j.enablePluginForRoom].forEach(s=>{a(this,ns).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{enabledBy:t.enabledBy})})}),[j.disablePluginForPeers,j.disablePluginForRoom].forEach(s=>{a(this,ns).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{disabledBy:t.disabledBy})})}),[j.customPluginEventToPeers,j.customPluginEventToRoom].forEach(s=>{a(this,ns).on(s,async(t,e)=>{this.sendIframeEvent(s,t.pluginId,e,{data:JSON.parse(new TextDecoder().decode(t.pluginData))})})}),[j.storeInsertKeys,j.storeGetKeys,j.storeDeleteKeys].forEach(s=>{a(this,ns).on(s,async(t,e)=>{var i;const r=(i=t.storeItems)==null?void 0:i.map(n=>{var o;return{timestamp:n.timestamp,peerId:n.peerId,payload:JSON.parse((o=n.payload)!=null&&o.length?new TextDecoder().decode(n.payload):"{}"),key:n.storeKey}});this.sendIframeEvent(s,t.pluginId,e,{storeName:t.storeName,storeItems:r})})}),a(this,ns).on(j.storeDelete,async(s,t)=>{this.sendIframeEvent(j.storeDelete,s.pluginId,t,{storeName:s.storeName})}),a(this,ea).on(qe.sendMessageToPeers,s=>{const t=ts==null?void 0:ts.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(Ae.chatMessage,{message:t})}),a(this,ea).on(qe.sendMessageToRoom,s=>{const t=ts==null?void 0:ts.formatSocketPeerMessage(s.message);this.broadcastIframeEvent(Ae.chatMessage,{message:t})}),a(this,_s).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,s=>{const t=Vd(s);this.broadcastIframeEvent(Ae.peerJoined,t)}),a(this,_s).getValue("peerSessionStore").on(_.PEER_CLOSED,s=>{this.broadcastIframeEvent(Ae.peerLeft,s)}),a(this,_s).getValue("peerSessionStore").on(_.UPDATE_PEER_STAGE_STATUS,s=>{this.broadcastIframeEvent(Ae.peerStageStatusUpdate,s)}),a(this,_s).subscribe("stageStatus",s=>{this.broadcastIframeEvent(Ae.stageStatusUpdate,s)})}},ns=new WeakMap,ea=new WeakMap,_s=new WeakMap,xS);let lo=Cf;Ud([E.trace("PluginController.getRoomPlugins")],lo.prototype,"getRoomPlugins",1),Ud([E.trace("PluginController.enableForSelf")],lo.prototype,"enablePlugin",1),Ud([E.trace("PluginController.disableForSelf")],lo.prototype,"disablePlugin",1),Ud([E.trace("PluginController.setupEvents")],lo.prototype,"setupEvents",1);class y1{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");g(this,Vo,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,Vo,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,Vo).getValue("peerSessionStore").emit(_.SOCKET_STATE_UPDATE,r),this.socketState=r)}}Vo=new WeakMap;var E1=Object.defineProperty,b1=Object.getOwnPropertyDescriptor,uo=(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&&E1(t,e,i),i};let yi=(US=class extends Ut{constructor(t,e){const r=t.getValue("logger");super(r);g(this,ra);g(this,ta,void 0);g(this,sa,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,sa,t),f(this,ta,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,sa).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,ta).permissions.canRecord)throw this.logger.error("Recording::start::permission_denied"),new k("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 k(`Cant start recording, recordingState irregular: ${this.recordingState}`,"1005");try{const e=vt(),{recording:r={}}=a(this,sa).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 k("Error while starting recording","1000",this.logger)}}async stop(t){await U(this,ra,ou).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await U(this,ra,ou).call(this,"pause",["RECORDING"],t)}async resume(t){await U(this,ra,ou).call(this,"resume",["PAUSED"],t)}},ta=new WeakMap,sa=new WeakMap,ra=new WeakSet,ou=async function(t,e,r){if(!a(this,ta).permissions.canRecord)throw this.logger.error("Recording::stop::permission_denied"),new k("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 k("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 vt().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 k("Error while stopping recording","1000",this.logger)}})},US);uo([E.trace("Recording.start")],yi.prototype,"start",1),uo([E.trace("Recording.stop")],yi.prototype,"stop",1),uo([E.trace("Recording.stop")],yi.prototype,"pause",1),uo([E.trace("Recording.stop")],yi.prototype,"resume",1),yi=uo([ct("1000")],yi);var w1=Object.defineProperty,P1=Object.getOwnPropertyDescriptor,_1=(s,t,e,r)=>{for(var i=r>1?void 0:r?P1(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&&w1(t,e,i),i};class If{constructor(t,e,r){p(this,"recording");p(this,"room");g(this,Li,void 0);f(this,Li,t),this.recording=new yi(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,Li).getValue("telemetry")}get logger(){return a(this,Li).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,Li).getValue("peerSessionStore").on(_.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(x.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(x.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(x.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Li=new WeakMap,_1([E.trace("RecordingController.setupEvents")],If.prototype,"setupEvents",1);class k1{constructor(t){g(this,xi,void 0);f(this,xi,t)}hasFeature(t){return a(this,xi).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,xi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,xi).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}xi=new WeakMap;class Sh{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=fe,this.callStats=i}static init(t){return new Sh(t.getValue("authToken"),t.getValue("logger"),new k1(t),t.getValue("callstats"))}}class vh{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=Sh.init(t);return new vh(e)}}var R1=Object.defineProperty,C1=Object.getOwnPropertyDescriptor,Bt=(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&&R1(t,e,i),i};class At extends kn{constructor(e,r,i=Bd,n=!0){const o=e.getValue("logger");super(o);g(this,Ge,void 0);g(this,ye,void 0);g(this,me,void 0);g(this,mr,void 0);g(this,as,void 0);g(this,Lo,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,Ge,new xf(e,r)),f(this,ye,new rD(e,a(this,Ge),void 0,i)),f(this,me,new lD(e,a(this,Ge),void 0,i)),f(this,as,new oD(a(this,Ne),a(this,Ge))),f(this,mr,new nD(e,a(this,Ge))),f(this,Lo,n),a(this,ye).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,ye).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,me).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,me).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,as).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,Ge).getAudioAndVideoTrack(a(this,ye).userSelectedDevice,a(this,me).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,Ge).getAudioTrack(!1,a(this,ye).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,Ge).getVideoTrack(a(this,me).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,ye).setMediaTrack(i),await a(this,me).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,mr).currentDevice)!=null&&o.deviceId&&a(this,Ne).getValue("callstats").selectedDevice("SPEAKER",a(this,mr).currentDevice),a(this,Ge).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,ye).currentDevice,video:a(this,me).currentDevice,speaker:a(this,mr).currentDevice}}get permissions(){return a(this,Ge).permissions}getAllDevices(){return a(this,Ge).getAvailableDevices()}getDeviceById(e,r){return a(this,Ge).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,ye).mediaTrack}get audioTrack(){return a(this,ye).transformedMediaTrack}get audioEnabled(){return a(this,ye).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,ye).enableTrack(!1,e):await a(this,ye).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,ye).mediaTrack&&!a(this,ye).isCustomTrack?a(this,ye).muteTrack():a(this,ye).disableTrack()}getAudioDevices(e){return a(this,Ge).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,ye).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,mr).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,mr).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,me).mediaTrack}get videoTrack(){return a(this,me).transformedMediaTrack}get videoEnabled(){return a(this,me).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,me).enableTrack(!1,e):await a(this,me).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,me).disableTrack()}getVideoDevices(e){return a(this,Ge).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,me).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,me).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,as).audioMediaTrack,video:a(this,as).videoMediaTrack}}get screenShareEnabled(){return a(this,as).trackEnabled}async enableScreenShare(){await a(this,as).enableScreenShare()}async disableScreenShare(){a(this,as).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,as).updateConstraints(e)}getSpeakerDevices(e){return a(this,Ge).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,ye).addMiddleware(e)}removeAudioMiddleware(e){return a(this,ye).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,ye).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,me).addMiddleware(e)}removeVideoMiddleware(e){return a(this,me).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,me).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,me).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,ye).disableTrack(),a(this,me).disableTrack(),a(this,me).terminateMiddlewareWebWorker(),a(this,as).disableScreenShare(),a(this,Ge).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,Lo))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,ye).disableTrack()}removeVideoTrack(){a(this,me).disableTrack(),a(this,me).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}Ge=new WeakMap,ye=new WeakMap,me=new WeakMap,mr=new WeakMap,as=new WeakMap,Lo=new WeakMap,Ne=new WeakMap,Bt([E.trace("MediaHandler.setupStreams")],At.prototype,"setupStreams",1),Bt([E.trace("MediaHandler.enableAudio")],At.prototype,"enableAudio",1),Bt([E.trace("MediaHandler.disableAudio")],At.prototype,"disableAudio",1),Bt([E.trace("MediaHandler.setAudioDevice")],At.prototype,"setAudioDevice",1),Bt([E.trace("MediaHandler.enableVideo")],At.prototype,"enableVideo",1),Bt([E.trace("MediaHandler.disableVideo")],At.prototype,"disableVideo",1),Bt([E.trace("MediaHandler.setVideoDevice")],At.prototype,"setVideoDevice",1),Bt([E.trace("MediaHandler.updateVideoConstraints")],At.prototype,"updateVideoConstraints",1),Bt([E.trace("MediaHandler.enableScreenShare")],At.prototype,"enableScreenShare",1),Bt([E.trace("MediaHandler.disableScreenShare")],At.prototype,"disableScreenShare",1),Bt([E.trace("MediaHandler.updateScreenshareConstraints")],At.prototype,"updateScreenshareConstraints",1),Bt([E.trace("MediaHandler.destruct")],At.prototype,"destruct",1),Bt([E.trace("MediaHandler.onDeviceChange")],At.prototype,"onDeviceChange",1);function $d(s,t,e){switch(!0){case fe.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case fe.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case fe.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 I1=["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=fe._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:I1.some(i=>t==null?void 0:t.includes(i))}async function A1(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 M1=s=>(t,e)=>(s.set(t,e),e),Af=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Mf=536870912,Df=Mf*2,D1=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<Df?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Mf){for(;e.has(i);)i=Math.floor(Math.random()*Df);return s(e,i)}if(e.size>Af)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()*Af);return s(e,i)},Of=new WeakMap,O1=M1(Of),Fd=D1(O1,Of),N1=s=>s.method!==void 0&&s.method==="call",V1=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(N1(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(V1(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})}}))})();`),Nf=s=>Hd().clearInterval(s),L1=s=>Hd().clearTimeout(s),Vf=(s,t)=>Hd().setInterval(s,t),Lf=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Nf,clearTimeout:L1,setInterval:Vf,setTimeout:(s,t)=>Hd().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class x1{constructor(t){g(this,Ui,void 0);g(this,xo,void 0);f(this,xo,t)}get logger(){return a(this,xo).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Ui))try{Nf(a(this,Ui)),f(this,Ui,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:Lf})));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,Ui,Vf(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Ui=new WeakMap,xo=new WeakMap;const U1={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}}},$1=[[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}]]],B1=(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=$1,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 Me=(s=>(s.WEBCAM="webcam",s.WEBCAM_BACKUP="webcam_backup",s.MIC="mic",s.SCREENSHARE_VIDEO="screenshare_video",s.SCREENSHARE_AUDIO="screenshare_audio",s))(Me||{});const F1=H_(),Mn=Us(F1.config.media);function H1(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 q1{constructor(t,e){g(this,$i,void 0);g(this,Sl,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,m,S,y,w,P,C;const t=(l=a(this,$i))==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=(P=t==null?void 0:t.frameRate)==null?void 0:P.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,$i))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return fe.isFirefox()||fe.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,$i))==null?void 0:o.video,i=iP(U1);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,Sl,t),f(this,$i,e)}getUpdatedVideoConstraints(t){return t}}$i=new WeakMap,Sl=new WeakMap;class Th extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class j1{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 G1=Object.defineProperty,W1=Object.getOwnPropertyDescriptor,Es=(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};let Ft=($S=class extends j1{constructor(t,e){super();g(this,ia,void 0);g(this,os,void 0);g(this,Ze,void 0);f(this,Ze,t),f(this,os,new q1(t,e)),f(this,ia,new AbortController)}get telemetry(){return a(this,Ze).getValue("telemetry")}get logger(){return a(this,Ze).getValue("logger")}get constraintsBuilder(){return a(this,os)}async destruct(){var t;(t=a(this,ia))==null||t.abort()}handlePermissionErrors(t,e){const r=$d(t,e.name,e.message);return this.permissions[t]=r,a(this,Ze).getValue("peerSessionStore").emit(_.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,os).getAudioConstraints(u).audio,video:a(this,os).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 P=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",P.label.includes("OBS Virtual")){const O=(await this.getVideoInputDevices()).find($=>$.label.includes("OBS Virtual"));P=await this.getVideoTrack(O.deviceId)}return a(this,Ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:w,videoTrack:P}}catch(c){throw this.logger.error("WebMediaInterface.getAudioAndVideoTrack",{error:c}),new k("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,Ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),new k("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,os).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 Th(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,os).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,Ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"})),l}catch(l){throw l.constraints&&this.handlePermissionErrors("audio",l),new k(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,Ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),new k("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:P}=m.width;S.applyConstraints({width:{ideal:P},height:{ideal:Math.floor(w*P/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 Th(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,os).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,os).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Ze).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"})),h}catch(u){throw u.constraints&&this.handlePermissionErrors("video",u),new k(u.message,"1602")}}async getScreenShareTracks(){const t=async e=>{try{this.logger.info("getDisplayMediaWithoutTimeout::requesting_display_media",{constraints:JSON.stringify(e)}),a(this,Ze).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 Th(r.name,r.message,e),o={video:!0};if(h_(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,os).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Ze).getValue("peerSessionStore").emit(_.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 k(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 k("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 k("Failed to get device","1609")}}async onDeviceChange(t){if(fe.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,Ze).getValue("callstats").devices("AUDIO",o==null?void 0:o.filter(m=>m.kind==="audioinput")),h.some(m=>m.kind==="videoinput")&&a(this,Ze).getValue("callstats").devices("VIDEO",o==null?void 0:o.filter(m=>m.kind==="videoinput")),h.some(m=>m.kind==="audiooutput")&&a(this,Ze).getValue("callstats").devices("SPEAKER",o==null?void 0:o.filter(m=>m.kind==="audiooutput")),t(r,d,!1)}},{signal:a(this,ia).signal})}}},ia=new WeakMap,os=new WeakMap,Ze=new WeakMap,$S);Es([E.trace("WebMediaInterface.destruct")],Ft.prototype,"destruct",1),Es([E.trace("WebMediaInterface.handlePermissionErrors")],Ft.prototype,"handlePermissionErrors",1),Es([E.trace("WebMediaInterface.getAudioAndVideoTrack")],Ft.prototype,"getAudioAndVideoTrack",1),Es([E.trace("WebMediaInterface.getAudioTrack")],Ft.prototype,"getAudioTrack",1),Es([E.trace("WebMediaInterface.getVideoTrack")],Ft.prototype,"getVideoTrack",1),Es([E.trace("WebMediaInterface.getScreenShareTracks")],Ft.prototype,"getScreenShareTracks",1),Es([E.trace("WebMediaInterface.getAvailableDevices")],Ft.prototype,"getAvailableDevices",1),Es([E.trace("WebMediaInterface.getAvailableDevicesByKind")],Ft.prototype,"getAvailableDevicesByKind",1),Es([E.trace("WebMediaInterface.getDevice")],Ft.prototype,"getDevice",1),Es([E.trace("WebMediaInterface.onDeviceChange")],Ft.prototype,"onDeviceChange",1),Ft=Es([ct("1600")],Ft);const xf=Ft,Ei={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}},J1=(s=0)=>new Promise(t=>setTimeout(t,s)),K1=(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):J1().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},z1=typeof AudioContext!="undefined"?AudioContext:null;class yh{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:z1,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:yh}})}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 Uf=new yh,Y1=3,Q1=250;function X1(s){const t={},e=Uf.getOrCreate(t);let r=Y1;function i(){return r-=1,K1(e,s.srcObject,Q1).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Uf.release(t)})}async function $f(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 X1(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 Z1=Object.defineProperty,eD=Object.getOwnPropertyDescriptor,Bf=(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&&Z1(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=>Ei.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ei.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 k("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 k("No device received!","1603");this.userSelectedDevice=t.deviceId,e&&this.setUserPreferredDevice(t.deviceId),await this.onSetDevice(t)}async addMiddleware(t){if(fe.isWebKitBased()&&!(fe.isSafari()&&R_.test(fe.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))}};Bf([E.trace("BaseMediaHandler.unmuteTrack")],qd.prototype,"unmuteTrack",1),qd=Bf([ct("1600")],qd);const Ff=qd;var tD=Object.defineProperty,sD=Object.getOwnPropertyDescriptor,Eh=(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 bh="[Realtimekit]nonSilentDeviceLabels";class jd extends Ff{async onSetDevice(t){if(!t)throw this.logger.warn("AudioMediaHandler.setDevice No device received"),new k("No device received!","1603");if(t.kind!=="audioinput")throw this.logger.warn("AudioMediaHandler.setDevice Received non audio device"),new k("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 k(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 A1(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(Ei.getItem(bh,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await $f(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return Ei.setItem(bh,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 $f(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return Ei.setItem(bh,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}Eh([E.trace("AudioMediaHandler.setTransformedTrack")],jd.prototype,"setTransformedTrack",1),Eh([E.trace("AudioMediaHandler.onTrackEnded")],jd.prototype,"onTrackEnded",1),Eh([E.trace("AudioMediaHandler.conditionallyChangeTrack")],jd.prototype,"conditionallyChangeTrack",1);const rD=jd;class iD{constructor(t,e){g(this,Bi,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>Ei.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>Ei.getItem(this.userPreferredDeviceKey,this.logger));f(this,Bi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,Bi).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,Bi)instanceof xf))return;let r=t;if(t||([r]=(await a(this,Bi).getAvailableDevicesByKind("audiooutput")).filter(d=>!Bd(d))),!r)throw new k("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){}})}}Bi=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,Uo,void 0);f(this,Uo,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,Uo).getValue("peerSessionStore").emit(_.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 k("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new k("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)),fe.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")}}Uo=new WeakMap;const oD=aD;var cD=Object.defineProperty,dD=Object.getOwnPropertyDescriptor,Gd=(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 ho extends Ff{constructor(e,r,i,n){super(e,r,i,n);g(this,na,void 0);g(this,$o,{disablePerFrameCanvasRendering:!1});f(this,na,new x1(e))}async onSetDevice(e){if(!e)throw this.logger.warn("VideoMediaHandler.setDevice No device received"),new k("No device received!","1603");if(e.kind!=="videoinput")throw this.logger.warn("VideoMediaHandler.setDevice Received non video device",{devices:[e]}),new k("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 k("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,na).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,$o)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,$o,e)}async updateConstraints(e){if(!this._mediaTrack)throw new k("No media track enabled!","1610");const r=this.mediaInterface;if(!r.constraintsBuilder)throw new k("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,na).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}}na=new WeakMap,$o=new WeakMap,Gd([E.trace("VideoMediaHandler.setTransformedTrack")],ho.prototype,"setTransformedTrack",1),Gd([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],ho.prototype,"setVideoMiddlewareGlobalConfig",1),Gd([E.trace("VideoMediaHandler.onTrackEnded")],ho.prototype,"onTrackEnded",1),Gd([E.trace("VideoMediaHandler.conditionallyChangeTrack")],ho.prototype,"conditionallyChangeTrack",1);const lD=ho,Hf=Us($u()),oa=class{constructor(t){g(this,wt,void 0);g(this,Fi,void 0);g(this,Bo,void 0);g(this,aa,void 0);if(!t)throw new k("Could not load preset.","0904");f(this,wt,t.config),f(this,Bo,t.name),f(this,Fi,t.ui||Us($u().ui)),f(this,aa,t.permissions.plugins.config)}static fromResponse(t){return new oa(t)}static default(){return new oa(Hf)}static init(t,e=!0){return!t||e?new oa(Hf):new oa(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,Fi).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,wt).viewType}get livestreamViewerQualities(){return a(this,wt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,wt).maxVideoStreams}get maxScreenShareCount(){return a(this,wt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,aa)).filter(t=>a(this,aa)[t].disabled)}get designTokens(){return a(this,Fi).designTokens}get configDiff(){return a(this,Fi).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,wt))==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,P,C,O,$,L,F,Q,X,it;return{audio:{enableStereo:(i=(r=(e=(t=a(this,wt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:Mn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,wt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:Mn.audio.enableHighBitrate},video:{quality:(m=(h=(u=(l=a(this,wt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?m:Mn.video.quality,frameRate:(P=(w=(y=(S=a(this,wt))==null?void 0:S.media)==null?void 0:y.video)==null?void 0:w.frameRate)!=null?P:Mn.video.frameRate},screenshare:{quality:(L=($=(O=(C=a(this,wt))==null?void 0:C.media)==null?void 0:O.screenshare)==null?void 0:$.quality)!=null?L:Mn.screenshare.quality,frameRate:(it=(X=(Q=(F=a(this,wt))==null?void 0:F.media)==null?void 0:Q.screenshare)==null?void 0:X.frameRate)!=null?it:Mn.screenshare.frameRate}}}get name(){return a(this,Bo)}};let wh=oa;wt=new WeakMap,Fi=new WeakMap,Bo=new WeakMap,aa=new WeakMap;var uD=Object.defineProperty,hD=Object.getOwnPropertyDescriptor,qf=(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 Ph extends Ut{constructor(e,r){const i=e.getValue("logger");super(i);g(this,ca,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");g(this,Fo,void 0);f(this,ca,r),f(this,Fo,e),this.viewerCount=0}get telemetry(){return a(this,Fo).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,ca).permissions.canLivestream)throw this.logger.error("Livestream::start::permission_denied"),new k("User does not have permission to start livestreaming","1901");this.setLivestreamState("STARTING");try{const r=vt(),{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 k("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,ca).permissions.canLivestream)throw this.logger.error("Livestream::stop::permission_denied"),new k("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 k("Livestream not started yet","1902");try{this.setLivestreamState("STOPPING"),await vt().stopLivestreaming()}catch(e){throw this.logger.error("Livestream::stop::livestream_failed_to_stop",{error:e}),this.setLivestreamState("STOPPING"),new k("Error while stopping livestream","1900",this.logger)}}}ca=new WeakMap,Fo=new WeakMap,qf([E.trace("livestream.start")],Ph.prototype,"start",1),qf([E.trace("livestream.stop")],Ph.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 jf{constructor(t,e,r){p(this,"livestream");g(this,da,void 0);g(this,la,void 0);g(this,gr,void 0);g(this,Fs,void 0);f(this,Fs,t),f(this,la,e),this.livestream=new Ph(t,e),f(this,gr,r),this.setupEvents()}get logger(){return a(this,Fs).getValue("logger")}get telemetry(){return a(this,Fs).getValue("telemetry")}async fetchInitialLivestreamingState(){const t=vt(),{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,gr).on(x.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,la).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,gr).on(x.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,la).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,gr).on(x.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,gr).on(x.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,gr).on(x.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Fs).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,da,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Fs).getValue("peerSessionStore").on(_.PEER_CLOSED,t=>{t.id===a(this,da)&&(f(this,da,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Fs).getValue("peerSessionStore").onAsync(_.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,Fs).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}da=new WeakMap,la=new WeakMap,gr=new WeakMap,Fs=new WeakMap,gD([E.trace("LivestreamController.setupEvents")],jf.prototype,"setupEvents",1);var fD=Object.defineProperty,SD=Object.getOwnPropertyDescriptor,po=(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&&fD(t,e,i),i};class Dn{constructor({name:t,socketHandler:e,meetingId:r}){g(this,vl);p(this,"name","");g(this,ht,{});g(this,Xr,"");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,Xr,r)}async set(t,e,r=!0,i=!1){a(this,ht)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,ht)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,ht)[t]})))}remoteSet(t,e){a(this,Zr).storeInsertKeys(a(this,Xr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,ht)[e]=r}),a(this,Zr).storeInsertKeys(a(this,Xr),this.name,t)}async update(t,e,r=!0){U(this,vl,QS).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,ht)[t]&&delete a(this,ht)[t],e)return a(this,Zr).storeDeleteKeys(a(this,Xr),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,ht)[e]&&delete a(this,ht)[e]}),a(this,Zr).storeDeleteKeys(a(this,Xr),this.name,t)}get(t){if(a(this,ht)[t])return a(this,ht)[t]}getAll(){return a(this,ht)}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,ht,t)}}ht=new WeakMap,Xr=new WeakMap,Zr=new WeakMap,vl=new WeakSet,QS=function(t,e,r=!0){let i;const n=a(this,ht)[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)},po([It(Cn,"rateLimitConfig")],Dn.prototype,"remoteSet",1),po([It(Cn,"bulkRateLimitConfig")],Dn.prototype,"bulkSet",1),po([It(Cn,"rateLimitConfig")],Dn.prototype,"update",1),po([It(Cn,"rateLimitConfig")],Dn.prototype,"delete",1),po([It(Cn,"bulkRateLimitConfig")],Dn.prototype,"bulkDelete",1);class vD{constructor(t,e){g(this,Ho);g(this,Tl);p(this,"stores",new Map);g(this,Hi,void 0);g(this,qi,"");g(this,qo,void 0);g(this,ei,new Map);f(this,Hi,e),f(this,qi,t.getValue("meetingId")),f(this,qo,t),U(this,Tl,XS).call(this)}create(t){const e=new Dn({name:t,socketHandler:a(this,Hi),meetingId:a(this,qi)});return a(this,Hi).storeGetKeys(a(this,qi),t,[]),new Promise((i,n)=>{const o=setTimeout(()=>n(Error("Failed")),3e3);a(this,ei).set(t,{rejectTimeout:o,resolve:i,store:e})})}}Hi=new WeakMap,qi=new WeakMap,Ho=new WeakSet,Xh=function(){return a(this,qo).getValue("peerId")},qo=new WeakMap,ei=new WeakMap,Tl=new WeakSet,XS=function(){[j.storeInsertKeys,j.storeGetKeys,j.storeDeleteKeys].forEach(t=>{a(this,Hi).on(t,async e=>{var n,o;if(e.pluginId!==a(this,qi))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===j.storeGetKeys){const c=a(this,ei).get(e.storeName),d=this.stores.get(e.storeName)||(c==null?void 0:c.store);a(this,ei).get(e.storeName)&&(this.stores.set(e.storeName,c.store),c.resolve(d),clearTimeout(c.rejectTimeout),a(this,ei).delete(e.storeName)),r.forEach(l=>{d.set(l.key,l.payload,!1,!1)});return}const i=this.stores.get(e.storeName)||((o=a(this,ei).get(e.storeName))==null?void 0:o.store);i!==void 0&&(t===j.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,Ho,Xh)&&i.set(c,l,!1,!0)}),t===j.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,Ho,Xh)&&i.delete(c,!1,!0)}))})})};function bi(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 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 nr=(BS=class extends Ut{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,ji);g(this,ti);g(this,Gi);g(this,yl);g(this,Wi);g(this,Go);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,ua,void 0);p(this,"supportsRemoteControl",!1);g(this,ha,void 0);p(this,"presetName");g(this,Wt,void 0);g(this,fr,void 0);g(this,jo,void 0);g(this,si,new Map);g(this,Sr,1);g(this,El,Lu(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,Sr)===1?(f(this,Sr,0),a(this,Wt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Sr)})):d<ED&&a(this,Sr)===0&&(f(this,Sr,1),a(this,Wt).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,Sr)}))},2e3));f(this,Wt,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:m,clientSpecificId:S,stageStatus:y,customParticipantId:w,audioMuted:P,audioTrack:C,videoEnabled:O=!1,videoTrack:$,producers:L,metadata:F}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=m,this.manualProducerConfig=y_,f(this,ha,y!=null?y:"ON_STAGE"),this.customParticipantId=w!=null?w:S,this.audioEnabled=!P,this.audioTrack=C,this.videoEnabled=O,this.videoTrack=$,this.screenShareTracks={audio:void 0,video:void 0},this.producers=L!=null?L:[],this.presetName=F==null?void 0:F.preset_name,f(this,ua,!1),f(this,fr,r),f(this,jo,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),U(this,Go,Zh).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,ha)}get telemetry(){return a(this,Wt).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...bi(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...bi(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",U(this,Go,Zh)),a(this,ti,qa)&&(this.on("audioUpdate",U(this,bl,ev)),this.on("screenShareUpdate",U(this,wl,tv)))}async pin(){if(!a(this,Gi,Gc))throw new k("Can`t pin participant without joining room","1205");if(!a(this,fr).permissions.pinParticipant)throw new k("You do not have permission to pin participants.","1201");return a(this,ji,jc).pinPeer(this.id)}async unpin(){if(!a(this,Gi,Gc))throw new k("Can`t unpin participant without joining room","1205");if(!a(this,fr).permissions.pinParticipant)throw new k("You do not have permission to unpin participants.","1201");return a(this,ji,jc).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,ua,t);const r=t?"pinned":"unpinned";(i=a(this,Wi,Wc))==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,Gc))throw new k("Can`t disable participant audio without joining room","1205");if(a(this,fr).permissions.canDisableParticipantAudio)return a(this,ji,jc).disableAudio(t);throw this.logger.error("Participant::unauthorized_disable_audio",{participant:{id:t}}),new k("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,ZS))throw new k("Can`t kick participant without joining room","1205");if(a(this,fr).permissions.kickParticipant){await a(this,Wt).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t});return}throw this.logger.error("Participant::unauthorized_kick",{participant:{id:t}}),new k("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,Gc))throw new k("Can`t disable participant video without joining room","1205");if(a(this,fr).permissions.canDisableParticipantVideo)return a(this,ji,jc).disableVideo(t);throw this.logger.error("Participant::unauthorized_disable_video",{participant:{id:t}}),new k("Unauthorized: User does not have permission to disable participant video.","1201")}async getPermissions(){return a(this,jo).getUserPermissions(this.userId)}setStageStatus(t){f(this,ha,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,ua)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,si).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,si).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Wi,Wc))==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,Wc))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,si).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,si).delete(t),(n=a(this,Wi,Wc))==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"}},ua=new WeakMap,ha=new WeakMap,Wt=new WeakMap,ji=new WeakSet,jc=function(){return a(this,Wt).getValue("roomNodeClient")},ti=new WeakSet,qa=function(){return a(this,Wt).getValue("audioPlayback")},Gi=new WeakSet,Gc=function(){return a(this,Wt).getValue("connectionHandler").mediaJoined},yl=new WeakSet,ZS=function(){return a(this,Wt).getValue("connectionHandler").socketJoined},fr=new WeakMap,jo=new WeakMap,si=new WeakMap,Wi=new WeakSet,Wc=function(){return a(this,Wt).getValue("pip")},Sr=new WeakMap,El=new WeakMap,Go=new WeakSet,Zh=function(){Array.from(a(this,si).keys()).forEach(this.updateVideo)},bl=new WeakSet,ev=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,ti,qa))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,ti,qa))==null||e.removeParticipantTrack(this.id)},wl=new WeakSet,tv=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,ti,qa))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,ti,qa))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},BS);On([E.trace("Participant.disableAudio")],nr.prototype,"disableAudio",1),On([E.trace("Participant.kick")],nr.prototype,"kick",1),On([E.trace("Participant.disableVideo")],nr.prototype,"disableVideo",1),On([E.trace("Participant.getPermissions")],nr.prototype,"getPermissions",1),On([E.trace("Participant.setStageStatus")],nr.prototype,"setStageStatus",1),nr=On([ct("1200")],nr);class mo extends kf{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,ri,void 0);f(this,ri,new Map)}__set(e,r){return a(this,ri).set(e,r)}__clear(){return a(this,ri).clear()}get(e){return a(this,ri).get(e)}toArray(){return Array.from(a(this,ri).values())}}ri=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 Gf=new _D;var kD=Object.defineProperty,RD=Object.getOwnPropertyDescriptor,Ht=(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&&kD(t,e,i),i};const CD=["ACTIVE_GRID","PAGINATED","MANUAL"];let Tt=(FS=class extends Ut{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Wo);g(this,Ji);g(this,pa);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");g(this,Re,void 0);g(this,Ki,void 0);g(this,Dt,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"viewMode");p(this,"currentPage");p(this,"lastActiveSpeaker");p(this,"selectedPeers",Gf);f(this,Re,t),f(this,Ki,e),f(this,Dt,r),this.waitlisted=new mo(i),this.joined=new mo(i),this.videoSubscribed=new mo(i),this.audioSubscribed=new mo(i),this.active=this.videoSubscribed,this.pinned=new mo(i),this.all=new wD(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Re).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Re).getValue("telemetry")}setupEvents(){a(this,Re).getValue("peerSessionStore").on(_.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Re).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,Re).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,Re))==null?void 0:t.getValue("maxPreferredStreams")}setMaxActiveParticipantsCount(t){if(t<0||t>24)throw new k("0 <= Max active participants count limit <= 24","1203");a(this,Re).setValue("maxPreferredStreams",t),a(this,pa,cu)&&a(this,Re).getValue("peerSessionStore").emit(_.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,Jc))throw new k("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,Dt).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,Dt).acceptWaitingRoomRequest(e)}async rejectWaitingRoomRequest(t){var r,i;if(!a(this,Ji,Jc))throw new k("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,Dt).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=>CD.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 k(`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,Re).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Re).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Re).getValue("peerSessionStore").emit(_.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 k("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,Re).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:this.viewMode,page:this.currentPage})}async unsubscribe(t,e=["audio","video","screenshareAudio","screenshareVideo"]){if(this.viewMode!=="MANUAL")throw new k("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,Re).getValue("peerSessionStore").emit(_.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 k(`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,Re).getValue("peerSessionStore").emit(_.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,pa,cu))throw new k("Can`t disable all audio without joining room","1205");if(a(this,Ki).permissions.canAllowParticipantAudio)return a(this,Wo,ep).muteAll(t);throw this.logger.error("Participants::unauthorized_disable_all_audio",{actions:{disableAllAudio:{allowUnmute:t}}}),new k("Unauthorized: User does not have permission to disable peer audio.","1201")}async disableAllVideo(){if(this.logger.info("Participants::disable_all_video"),!a(this,pa,cu))throw new k("Can`t disable all video without joining room","1205");if(a(this,Ki).permissions.canAllowParticipantVideo)return a(this,Wo,ep).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new k("Unauthorized: User does not have permission to disable peer video.","1201")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await a(this,Re).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t})}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Re).getValue("viewType")!=="LIVESTREAM"&&!a(this,Ji,Jc))throw new k("Can`t kick all without joining room","1205");if(!a(this,Ki).permissions.kickParticipant)throw this.logger.error("Participants::unauthorized_kick_all"),new k("Unauthorized: User does not have permission to kick peers.","1201");const e=!0;a(this,Dt).kickAll(e)}async broadcastMessage(t,e,r){if(this.logger.info("Participants::broadcastMessage"),!a(this,Ji,Jc))throw new k("Can`t broadcast message without joining room","1205");if(!(t!=null&&t.trim()))throw new k("`type` must be a non-empty string.","1209");if(r)if("meetingIds"in r)await a(this,Dt).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,Dt).broadcastToPeers(t,i,e)}else await a(this,Dt).broadcastMessage(t,e)}async getAllJoinedPeers(t,e,r){return(await a(this,Dt).getRoomPeers(t,e,r)).peers.map(ar.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 k("Cannot update permissions, no valid userIDs found","1204");a(this,Dt).updatePermissions(i,e)}async getParticipantsInMeetingPreJoin(){return a(this,Dt).getRoomPeersNonPaginated()}},Re=new WeakMap,Wo=new WeakSet,ep=function(){return a(this,Re).getValue("roomNodeClient")},Ji=new WeakSet,Jc=function(){var t;return((t=a(this,Re).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},pa=new WeakSet,cu=function(){var t;return((t=a(this,Re).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ki=new WeakMap,Dt=new WeakMap,FS);Ht([E.trace("Participants.setViewMode")],Tt.prototype,"setViewMode",1),Ht([E.trace("Participants.setPage")],Tt.prototype,"setPage",1),Ht([E.trace("Participants.disableAllAudio")],Tt.prototype,"disableAllAudio",1),Ht([E.trace("Participants.disableAllVideo")],Tt.prototype,"disableAllVideo",1),Ht([E.trace("Participants.disablePeerAudio")],Tt.prototype,"disableAudio",1),Ht([E.trace("Participants.disablePeerVideo")],Tt.prototype,"disableVideo",1),Ht([E.trace("Participants.kickPeer")],Tt.prototype,"kick",1),Ht([E.trace("Participants.kickAll")],Tt.prototype,"kickAll",1),Ht([E.trace("Participants.broadcastMessage"),It(Cn,"rateLimitConfig")],Tt.prototype,"broadcastMessage",1),Ht([E.trace("Participants.getAllJoinedPeers"),It({maxInvocations:10,period:60})],Tt.prototype,"getAllJoinedPeers",1),Ht([E.trace("Participant.updatePermissions"),It({maxInvocations:1e3,period:60})],Tt.prototype,"updatePermissions",1),Ht([E.trace("Participants.getParticipantsInMeetingPreJoin")],Tt.prototype,"getParticipantsInMeetingPreJoin",1),Tt=Ht([ct("1200")],Tt);var ID=Object.defineProperty,AD=Object.getOwnPropertyDescriptor,wi=(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 Wf=(HS=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",Gf);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);g(this,cs,{mode:"ACTIVE_GRID",page:0});g(this,ks,!1);g(this,ma,!1);p(this,"updateConsumerSpatialLayers",Lu(()=>{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,ks)}`);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 Tt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=vs,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(x.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(_.SOCKET_PEERS,async s=>{s==null||s.forEach(t=>{t.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(t))})}),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(_.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(_.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(_.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,ks)}, 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(_.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(_.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(_.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,ks)}, 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 nr(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,cs).mode!==s&&(a(this,cs).mode=s),e&&a(this,cs).page!==e&&(a(this,cs).page=e);const{mode:r,page:i}=a(this,cs);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,cs))==null?void 0:e.mode)==="PAGINATED"&&!a(this,ks)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,cs))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,ks)}, Delay: ${t}, Page: ${(i=a(this,cs))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var o,c,d,l,u;if(((d=(c=(o=this.context.getValue("connectionHandler"))==null?void 0:o.mediaState)==null?void 0:c.recv)==null?void 0:d.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,ks)){f(this,ma,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,ks,!0),f(this,ma,!1);let s=[];this.participants.videoSubscribed.forEach(h=>{var y,w;const m=this.participants.joined.get(h.id),S=(w=(y=h.producers)==null?void 0:y.filter(P=>P.kind==="video"))!=null?w:[];m&&(S!=null&&S.length)&&S.forEach(P=>{var $,L,F,Q;const C=((L=($=m.manualProducerConfig)==null?void 0:$.video)!=null?L:!0)&&P.kind==="video"&&!P.screenShare,O=((Q=(F=m.manualProducerConfig)==null?void 0:F.screenshareVideo)!=null?Q:!0)&&P.kind==="video"&&P.screenShare;(C||O)&&(P.pause||s.push(P))})}),this.participants.audioSubscribed.forEach(h=>{var y,w;const m=this.participants.joined.get(h.id),S=(w=(y=h.producers)==null?void 0:y.filter(P=>P.kind==="audio"))!=null?w:[];m&&(S!=null&&S.length)&&S.forEach(P=>{var $,L,F,Q;const C=((L=($=m.manualProducerConfig)==null?void 0:$.audio)!=null?L:!0)&&P.kind==="audio"&&!P.screenShare,O=((Q=(F=m.manualProducerConfig)==null?void 0:F.screenshareAudio)!=null?Q:!0)&&P.kind==="audio"&&P.screenShare;(C||O)&&s.push(P)})}),s=T_(s,h=>h.producerId);const t=new Map;s.forEach(h=>{t.set(h.producerId,h)});const e=(l=this.roomNodeClient)==null?void 0:l.getConsumers(),r=s.filter(h=>!(e!=null&&e.has(h.producerId))),i=[];let n=Array.from((u=e==null?void 0:e.values())!=null?u:[]).map(h=>h.peerId);n=v_(n),n==null||n.forEach(h=>{var S;const m=this.participants.joined.get(h);if(!m){this.logger.warn(`Peer with ${h} doesn't exist in joined list but producers of it are being consumed.`);return}(S=m.producers)!=null&&S.length&&m.producers.forEach(y=>{const w=y.consumer&&e.has(y.consumer.id);!t.has(y.producerId)&&(e.has(y.producerId)||w)&&i.push(y)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(h=>h.producerId).join(", ")}], RemoveProducers: ${i.length} [${i.map(h=>h.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||i.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${i.length}.`),await this.updateConsumers(r,i),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(h){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:h})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,ks,!1)}a(this,ma)&&(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=Wf.formatSocketPeerMessage(s);return new nr(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===er.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===er.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===er.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(_.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(x.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(x.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(_.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(_.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),this.context.getValue("peerSessionStore").on(_.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(_.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(_.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(_.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(_.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(_.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(_.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(_.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,cs).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(_.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(_.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(_.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(_.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(_.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(_.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(_.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(_.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(_.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=gh(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(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},cs=new WeakMap,ks=new WeakMap,ma=new WeakMap,HS);let ar=Wf;wi([E.trace("ParticipantController.setupEvents")],ar.prototype,"setupEvents",1),wi([E.trace("ParticipantController.setupEvents")],ar.prototype,"setupEventsGlobal",1),wi([E.trace("ParticipantController.processMedia")],ar.prototype,"processMedia",1),wi([E.trace("ParticipantController.processConsumerClosed")],ar.prototype,"processConsumerClosed",1),wi([E.trace("ParticipantController.processConsumerResumed")],ar.prototype,"processConsumerResumed",1),wi([E.trace("ParticipantController.processConsumerPaused")],ar.prototype,"processConsumerPaused",1),wi([E.trace("ParticipantController.processNewConsumer")],ar.prototype,"processNewConsumer",1);const ve=Us($u().permissions),Sa=class extends Ut{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);g(this,Pt);g(this,q,void 0);g(this,ga,void 0);g(this,fa,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&&Mr(a(this,q).chat.private,r.private),r.public&&Mr(a(this,q).chat.public,r.public),this.emit("chatUpdate")),i&&Mr(a(this,q).connectedMeetings,i),c){const m=y=>{switch(y){case Or.NONE:return H.Allowed;case Or.ALLOWED:return H.Allowed;case Or.NOT_ALLOWED:return H.NotAllowed;case Or.CAN_REQUEST:return H.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)}),Mr(a(this,q).media,S)}n&&(Mr(a(this,q).plugins,n),this.emit("pluginsUpdate")),o&&(Mr(a(this,q).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&Mr(a(this,q),d),this.emit("permissionsUpdate",e)});if(!r)throw this.logger.error("PermissionPreset::load_preset_permissions_failed"),new k("Could not load preset permissions.","0904");f(this,fa,e),f(this,ga,i),f(this,q,r),n&&this.setupEvents()}setupEvents(){a(this,fa).getValue("peerSessionStore").on(_.UPDATE_PERMISSIONS,a(this,Pl))}static fromResponse(e,r,i){return new Sa(i,e,r,!0)}static default(e,r){return new Sa(e,ve,r)}static init(e,r,i){let n;return i?n=new Sa(e,i,r,!0):n=new Sa(e,ve,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,q))==null?void 0:e.stageEnabled)||a(this,ga)===Qs.Webinar||a(this,ga)===Qs.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,q))==null?void 0:e.acceptStageRequests)||((r=a(this,q))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,q))==null?void 0:e.stageAccess)===H.NotAllowed?H.NotAllowed:((r=a(this,q))==null?void 0:r.stageAccess)===H.CanRequest?H.CanRequest:((i=a(this,q))==null?void 0:i.stageAccess)===H.Allowed||a(this,q).media.audio.canProduce===H.Allowed||a(this,q).media.video.canProduce===H.Allowed||a(this,q).media.screenshare.canProduce===H.Allowed?H.Allowed:a(this,q).media.audio.canProduce===H.CanRequest||a(this,q).media.video.canProduce===H.CanRequest||a(this,q).media.screenshare.canProduce===H.CanRequest?H.CanRequest:H.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,q))==null?void 0:e.acceptWaitingRequests)!=null?r:ve.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===H.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,q))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===H.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,q))==null?void 0:e.disableParticipantAudio)!=null?r:ve.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canAcceptProductionRequests)!=null?r:ve.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,q))==null?void 0:e.disableParticipantVideo)!=null?r:ve.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.kickParticipant)!=null?r:ve.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.pinParticipant)!=null?r:ve.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canRecord)!=null?r:ve.canRecord}get waitingRoomType(){var e,r;return(r=(e=a(this,q))==null?void 0:e.waitingRoomType)!=null?r:ve.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,q))==null?void 0:e.waitingRoomType)!=null?r:ve.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,q))==null?void 0:e.plugins)!=null?r:ve.plugins}get polls(){var e,r;return(r=(e=a(this,q))==null?void 0:e.polls)!=null?r:ve.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return a(this,q).media.audio.canProduce===H.CanRequest||a(this,q).media.video.canProduce===H.CanRequest||a(this,q).media.screenshare.canProduce===H.CanRequest}get canProduceVideo(){var r;const e=(r=a(this,q).media.video.canProduce)!=null?r:ve.media.video.canProduce;return this.stageEnabled&&(a(this,Pt,Yt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,Yt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Pt,Yt)==="OFF_STAGE"||a(this,Pt,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=a(this,q).media.screenshare.canProduce)!=null?r:ve.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Pt,Yt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,Yt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Pt,Yt)==="OFF_STAGE"||a(this,Pt,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=a(this,q).media.audio.canProduce)!=null?r:ve.media.audio.canProduce;return this.stageEnabled&&(a(this,Pt,Yt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Pt,Yt)==="ON_STAGE")&&e===H.CanRequest?H.Allowed:this.stageEnabled&&(a(this,Pt,Yt)==="OFF_STAGE"||a(this,Pt,Yt)==="REQUESTED_TO_JOIN_STAGE")&&e===H.Allowed?H.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:ve.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,q))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:ve.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,q))==null?void 0:e.connectedMeetings)!=null?r:ve==null?void 0:ve.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,q))==null?void 0:e.hiddenParticipant)!=null?r:ve.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,q).showParticipantList)!=null?e:ve.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:ve.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,q))==null?void 0:e.canChangeParticipantPermissions)!=null?r:ve.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return a(this,q).media.audio.canProduce===H.Allowed||a(this,q).media.video.canProduce===H.Allowed||a(this,q).media.screenshare.canProduce===H.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=a(this,q).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return a(this,q).isRecorder}get canSpotlight(){return a(this,q).canSpotlight}get canLivestream(){return a(this,q).canLivestream}get transcriptionEnabled(){return a(this,q).transcriptionEnabled}};let _h=Sa;q=new WeakMap,ga=new WeakMap,fa=new WeakMap,Pl=new WeakMap,Pt=new WeakSet,Yt=function(){return a(this,fa).getValue("stageStatus")};class Jf extends Ut{constructor(e,r){super(r);p(this,"localMediaHandler");g(this,Jt,void 0);f(this,Jt,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,Jt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_ERROR,m):a(this,Jt).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,m)};if(fe.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,Jt))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,Jt))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,Jt))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,Jt))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,Jt))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(fe.init(),i&&f(this,Jt,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 At(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(_.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(_.MEDIA_PERMISSION_ERROR,async S=>{const{kind:y,message:w,constraints:P}=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:P,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,Jt,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})}}Jt=new WeakMap;var MD=Object.defineProperty,DD=Object.getOwnPropertyDescriptor,yt=(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&&MD(t,e,i),i};let ze=(qS=class extends Jf{constructor(t,e,r,i,n){var c;const o=t.getValue("logger");super(t,o);g(this,vr);g(this,tt);g(this,ya);g(this,Be);g(this,Jo);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");g(this,va,void 0);g(this,_t,void 0);g(this,Ta,void 0);p(this,"role");p(this,"userId");p(this,"organizationId");p(this,"supportsRemoteControl",!1);p(this,"device");g(this,et,void 0);p(this,"hidden",!1);p(this,"presetName");p(this,"roomState","init");g(this,Ea,new Set);g(this,ba,new Set);f(this,et,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(c=e.customParticipantId)!=null?c:e.clientSpecificId,this.waitlistStatus="none",f(this,_t,r),f(this,va,i),this.hidden=!1,f(this,Ta,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=fe.isElectron(),this.device=fe.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),U(this,Jo,tp).call(this)}get telemetry(){return a(this,et).getValue("telemetry")}get stageStatus(){return a(this,et).getValue("stageStatus")}get producers(){var t,e;return Array.from((e=(t=a(this,tt,ft).getProducers())==null?void 0:t.values())!=null?e:[])}get id(){return this.peerId}get peerId(){return a(this,et).getValue("peerId")}static async __init__(t,e,r,i,n,o=!1){var m,S,y,w,P,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 ze(t,e,r,i,n),u=H1(i.mediaConstraints);Mr(u,(P=t.getValue("defaults"))==null?void 0:P.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,_t).removeAllListeners("permissionsUpdate")}setupEvents(){this.on("videoUpdate",U(this,Jo,tp));const t=a(this,ya,du);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...bi(this)}),a(this,Be,Ke)&&this.audioEnabled)try{await a(this,tt,ft).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",{...bi(this)}),a(this,Be,Ke)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,Be,Ke))try{await a(this,tt,ft).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,ya,du))==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,Ke)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,tt,ft).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",{...bi(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",{...bi(this)})}),this.localMediaHandler.on("AUDIO_TRACK_SILENT",()=>{var e;(e=a(this,et))==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,Ke)&&await a(this,tt,ft).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(e=a(this,et))==null||e.getValue("callstats").videoOff()}),a(this,_t).on("permissionsUpdate",e=>{var r,i,n;(r=e==null?void 0:e.media)!=null&&r.audio&&a(this,_t).canProduceAudio!==H.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,_t).canProduceVideo!==H.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,_t).canProduceScreenshare!==H.Allowed&&(this.disableScreenShare(),this.logger.info(`Disabled screenshare due to dynamic preset change: canProduceScreenshare: ${this.permissions.canProduceScreenshare}`))})}get permissions(){return a(this,_t)}get config(){return a(this,va)}get roomJoined(){var t;return a(this,va).viewType===Qs.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,et).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,Be,Ke)}setName(t){if(!t)throw new k("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!==H.NotAllowed&&!(a(this,_t).canProduceAudio===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.audioEnabled){if((e=a(this,et))==null||e.getValue("callstats").audioOn(),await this.localMediaHandler.enableAudio(t),a(this,Be,Ke)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,tt,ft).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,_t).canProduceVideo!==H.NotAllowed&&!(a(this,_t).canProduceVideo===H.CanRequest&&(this.stageStatus==="OFF_STAGE"||this.stageStatus==="REQUESTED_TO_JOIN_STAGE"))&&!this.videoEnabled){if((e=a(this,et))==null||e.getValue("callstats").videoOn(),await this.localMediaHandler.enableVideo(t),a(this,Be,Ke)&&this.stageStatus==="ON_STAGE")try{await a(this,tt,ft).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",{...bi(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new k("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,Be,Ke))throw new k("Can`t enable screenshare without joining room","1105");if(a(this,_t).canProduceScreenshare!==H.NotAllowed&&!(a(this,_t).canProduceScreenshare===H.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,tt,ft).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 k("Unsupported","1102");await this.localMediaHandler.updateScreenshareConstraints(t)}async disableAudio(){var t;this.audioEnabled&&(this.localMediaHandler.disableAudio(),a(this,Be,Ke)&&a(this,tt,ft).muteSelf(),this.emit("audioUpdate",{audioEnabled:this.audioEnabled,audioTrack:this.audioTrack}),(t=a(this,et))==null||t.getValue("callstats").audioOff())}async disableVideo(){var t;this.videoEnabled&&(await this.localMediaHandler.disableVideo(),a(this,Be,Ke)&&await a(this,tt,ft).pauseWebcam(),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}),(t=a(this,et))==null||t.getValue("callstats").videoOff())}async disableScreenShare(){this.screenShareEnabled&&(await this.localMediaHandler.disableScreenShare(),a(this,Be,Ke)&&await a(this,tt,ft).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,Ta,t);const r=t?"pinned":"unpinned";(i=a(this,vr,Sn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,Ta)}async pin(){if(!a(this,Be,Ke))throw new k("Can`t pin participants without joining room","1105");return this.show(),a(this,tt,ft).pinPeer(this.id)}async unpin(){if(!a(this,Be,Ke))throw new k("Can`t unpin participants without joining room","1105");return a(this,tt,ft).pinPeer(null)}async hide(){if(!a(this,Be,Ke))throw new k("Can`t toggle participant tile without joining room","1105");this.hidden=!0,this.emit("toggleTile",{hidden:this.hidden})}show(){if(!a(this,Be,Ke))throw new k("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 k("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,Ke)&&await a(this,tt,ft).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,Ke)&&await a(this,tt,ft).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,ya,du))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,Ea).add(t):a(this,ba).add(t),this.updateVideo(t),e||(i=a(this,vr,Sn))==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,vr,Sn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,Ea).delete(t):(a(this,ba).delete(t),a(this,vr,Sn).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,vr,Sn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,vr,Sn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},va=new WeakMap,_t=new WeakMap,Ta=new WeakMap,et=new WeakMap,vr=new WeakSet,Sn=function(){return a(this,et).getValue("pip")},tt=new WeakSet,ft=function(){return a(this,et).getValue("roomNodeClient")},ya=new WeakSet,du=function(){return a(this,et).getValue("audioPlayback")},Be=new WeakSet,Ke=function(){var t;return((t=a(this,et).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},Ea=new WeakMap,ba=new WeakMap,Jo=new WeakSet,tp=function(){Array.from(a(this,ba)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,Ea)).forEach(t=>this.updateVideo(t,!0))},qS);yt([E.trace("Self.cleanupEvents")],ze.prototype,"cleanupEvents",1),yt([E.trace("Self.setupEvents")],ze.prototype,"setupEvents",1),yt([E.trace("Self.setupTracks")],ze.prototype,"setupTracks",1),yt([E.trace("Self.destructMediaHandler")],ze.prototype,"destructMediaHandler",1),yt([E.trace("Self.removeDocumentEventListeners")],ze.prototype,"removeDocumentEventListeners",1),yt([ir.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],ze.prototype,"enableAudio",1),yt([ir.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],ze.prototype,"enableVideo",1),yt([E.trace("Self.updateVideoConstraints")],ze.prototype,"updateVideoConstraints",1),yt([E.trace("Self.enableScreenShare"),ir.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],ze.prototype,"enableScreenShare",1),yt([E.trace("Self.updateScreenshareConstraints")],ze.prototype,"updateScreenshareConstraints",1),yt([ir.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],ze.prototype,"disableAudio",1),yt([ir.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],ze.prototype,"disableVideo",1),yt([ir.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],ze.prototype,"disableScreenShare",1),yt([E.trace("Self.setDevice")],ze.prototype,"setDevice",1),ze=yt([ct("1100")],ze);class kh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,kh)}}class Rh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Rh)}}class Ch{constructor(t,e=!1){p(this,"pendingTasks",new Map);p(this,"nextTaskId",0);p(this,"stopping",!1);g(this,Ko,void 0);this.log=e,f(this,Ko,{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 kh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new Rh)}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,Ko).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)}}}Ko=new WeakMap;function OD(s,t){const e=new Error(t);return e.name=s,e}class go extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,go):this.stack=new Error(t).stack}}class Mt extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Mt):this.stack=new Error(t).stack}}class Br extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Mt):this.stack=new Error(t).stack}}const Kf=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 Kf(o*(c+1)):i==="exponential"&&await Kf(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 Wd(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:Wd(t),video:Wd(e)};return{sender:{audio:Wd(r),video:Wd(i)},receiver:n}}class xD{constructor(t){g(this,st,void 0);p(this,"events");f(this,st,t),this.events=vs}async joinRoom(t,e,r,i=!1){const n={roomUuid:t,displayName:e,prejoined:i,capabilities:r};return(await a(this,st).sendMessagePromiseWithTimeout({event:this.events.joinRoom,protobuf:eR.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,st).sendMessagePromise(this.events.createWebRTCTransport,Ck.toBinary(t))).payload,{transportId:r,description:i,producerIds:n}=Og.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,st).sendMessagePromise(this.events.produce,gR.toBinary(t))).payload,r=QR.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,st).sendMessagePromise(this.events.consume,dR.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=zR.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,st).sendMessagePromise(this.events.closeProducer,bR.toBinary(t))).payload,{description:r}=iC.fromBinary(e);return r}async closeConsumer(t){return(await a(this,st).sendMessagePromise(this.events.closeConsumer,PR.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,st).sendMessagePromise(this.events.updateConsumersSimulcastConfig,pR.toBinary(t))).payload}async hostControlForPeer(t,e){const r={audio:e==="audio",screeShare:!1,video:e==="video",participantId:t},i=(await a(this,st).sendMessagePromise(this.events.hostControlPeer,AR.toBinary(r))).payload;if(!i)return!1;const{status:n}=uC.fromBinary(i);return n==="success"}async hostControlForAll(t){const e={audio:t==="audio",screenShare:!1,video:t==="video"},r=(await a(this,st).sendMessagePromise(this.events.hostControlAllPeers,DR.toBinary(e))).payload;if(!r)return!1;const{status:i}=pC.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,st).sendMessagePromise(x.kickAll,$g.toBinary(t))}async kickPeer(t){a(this,st).sendMessagePromise(x.kick,ef.toBinary(t))}async changeDisplayName(t){const e=(await a(this,st).sendMessagePromise(this.events.changeDisplayName,CR.toBinary(t))).payload;if(!e)return!1;const{status:r}=gC.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,st).sendMessagePromise(this.events.selfJoinComplete,sR.toBinary(t))).payload;return Ku.fromBinary(e)}async audioActivity(t){a(this,st).sendMessage(this.events.audioActivity,Ak.toBinary(t))}}st=new WeakMap;var Nn=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(Nn||{});class Jd extends ot.EventEmitter{constructor(e){super();g(this,zo,void 0);f(this,zo,e),this.setMaxListeners(1/0)}get logger(){return a(this,zo).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)}})}}zo=new WeakMap;class Ih 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 Ah extends Ih{static createFactory(t){return()=>new Ah(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 Yf={},Kd={},UD={get exports(){return Kd},set exports(s){Kd=s}},Qf=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(Qf).forEach(function(s){var t=Qf[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}})})}}(Yf);var Mh=Kd,$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""}})},fo=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){Mh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(fo(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(fo(n,o,c))})})}),s.media.forEach(function(n){i.push(fo("m",Mh.m[0],n)),r.forEach(function(o){Mh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(fo(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(fo(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 xp extends it{constructor(e){super();p(this,"call");p(this,"timeOut");this.call=new Bs(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 Xv=8,Zv=1/1e3;class eT extends xp{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(Bs.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)*Xv/(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*Zv)})}}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 nu extends xp{constructor(e,r=Bs.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 nu{constructor(t){super(t,Bs.isHost)}}class sT extends nu{constructor(t){super(t,Bs.isRelay)}}class rT extends nu{constructor(t){super(t,Bs.isReflexive)}}class iT{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=wr(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=wr(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 Up=new iT,$p=[{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 Bp(s){const[t,e]=s.split(",");return{coords:{latitude:Number(t),longitude:Number(e)}}}class Fp{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 Hp extends it{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 it}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,b,R,N,U,L,F,H,ie,ut,Us,Ps,un;const c=e,d=new Fp,l=r.length?new Set(r):void 0,u=[],h=[],m=[],S=new Map,y=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:P}=I,B=I,be={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(be),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=be);break}case"transport":{const T=I;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=I,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(I.id))break;const T=I,P=n||this.outboundProducerMap.get(I.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 be=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const De=this.callStatsInstance.producers.get(P);if(((w=De==null?void 0:De.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={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 k=T,Be={frameHeight:k.frameHeight,frameWidth:k.frameWidth,framesEncoded:k.framesEncoded,framesDropped:k.framesDropped,framesPerSecond:k.framesPerSecond,framesSent:k.framesSent,keyFramesEncoded:k.keyFramesEncoded,firCount:k.firCount,encoderImplementation:k.encoderImplementation,hugeFramesSent:k.hugeFramesSent,pliCount:k.pliCount,qpSum:k.qpSum,qualityLimitationDurations:k.qualityLimitationDurations,qualityLimitationReason:k.qualityLimitationReason,qualityLimitationResolutionChanges:k.qualityLimitationResolutionChanges,totalEncodeTime:k.targetBitrate,totalPacketSendDelay:k.totalPacketSendDelay,retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,scalabilityMode:k.scalabilityMode,powerEfficientEncoder:k.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,Be),d.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,be,Be)}else if(T.mediaType==="audio"||T.kind==="audio"){const k=T,Be={retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,Be),d.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,be,Be)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,P=n||this.inboundConsumerMap.get(I.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 be=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const De={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 V=T,k={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped,framesPerSecond:V.framesPerSecond,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...De};k.score=Lp({frameWidth:k.frameWidth||0,framesDecoded:(k.framesDecoded||0)-(((b=this.videoConsumerToStatsMap.get(P))==null?void 0:b.framesDecoded)||0),framesPerSecond:k.framesPerSecond||0,packetsLost:(k.packetsLost||0)-(((R=this.videoConsumerToStatsMap.get(P))==null?void 0:R.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),y.set(P,{score:+(k.score*10).toFixed(),frameWidth:k.frameWidth||0,frameHeight:k.frameHeight||0,framesPerSecond:k.framesPerSecond||0,packetsLostPercentage:Kc({packetsLost:(k.packetsLost||0)-(((U=this.videoConsumerToStatsMap.get(P))==null?void 0:U.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((k.bytesReceived||0)-(((F=this.videoConsumerToStatsMap.get(P))==null?void 0:F.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,k),d.inboundVideoRtp.set(I.id,k),d.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,be,k)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,k={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...De};k.score=Vp({concealmentEvents:(k.concealmentEvents||0)-(((H=this.audioConsumerToStatsMap.get(P))==null?void 0:H.concealmentEvents)||0),packetsLost:(k.packetsLost||0)-(((ie=this.audioConsumerToStatsMap.get(P))==null?void 0:ie.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((ut=this.audioConsumerToStatsMap.get(P))==null?void 0:ut.packetsReceived)||0),jitter:k.jitter||0}),y.set(P,{score:+(k.score*10).toFixed(),packetsLostPercentage:Kc({packetsLost:(k.packetsLost||0)-(((Us=this.audioConsumerToStatsMap.get(P))==null?void 0:Us.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((Ps=this.audioConsumerToStatsMap.get(P))==null?void 0:Ps.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((k.bytesReceived||0)-(((un=this.audioConsumerToStatsMap.get(P))==null?void 0:un.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,k),d.inboundAudioRtp.set(I.id,k),d.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,be,k)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var P,B,be,De,V,k,Be,hn,bc,Pc,_c,Cc,kc,Rc,Ic,Ac,Mc,Oc,Dc,Nc,Vc,Lc,xc;if(I.outboundVideoRtpId.length>0){const le=[];I.outboundVideoRtpId.forEach(Uh=>{le.push(d.outboundVideoRtp.get(Uh))});const X=this.getWorkingSimulcastVideoStats(le);X.score=Dp({frameWidth:X.frameWidth||0,framesPerSecond:X.framesPerSecond||0,jitter:((P=X.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(X.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(T))==null?void 0:B.packetsSent)||0),packetsLost:(((be=X.remoteData)==null?void 0:be.packetsLost)||0)-(((V=(De=this.videoProducerToStatsMap.get(T))==null?void 0:De.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(X.framesEncoded||0)-(((k=this.videoProducerToStatsMap.get(T))==null?void 0:k.framesEncoded)||0)}),S.set(T,{score:+(X.score*10).toFixed(),frameWidth:X.frameWidth||0,frameHeight:X.frameHeight||0,framesPerSecond:X.framesPerSecond||0,jitter:((Be=X.remoteData)==null?void 0:Be.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:Jc({packetsSent:(X.packetsSent||0)-(((hn=this.videoProducerToStatsMap.get(T))==null?void 0:hn.packetsSent)||0),packetsLost:(((bc=X.remoteData)==null?void 0:bc.packetsLost)||0)-(((_c=(Pc=this.videoProducerToStatsMap.get(T))==null?void 0:Pc.remoteData)==null?void 0:_c.packetsLost)||0)}),bitrate:((X.bytesSent||0)-(((Cc=this.videoProducerToStatsMap.get(T))==null?void 0:Cc.bytesSent)||0))*8/7,cpuLimitations:X.qualityLimitationReason==="cpu",bandwidthLimitations:X.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,X)}else if(I.outboundAudioRtpId.length>0){const le=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);le.score=Op({packetsSent:(le.packetsSent||0)-(((kc=this.audioProducerToStatsMap.get(T))==null?void 0:kc.packetsSent)||0),packetsLost:(((Rc=le.remoteData)==null?void 0:Rc.packetsLost)||0)-(((Ac=(Ic=this.audioProducerToStatsMap.get(T))==null?void 0:Ic.remoteData)==null?void 0:Ac.packetsLost)||0),jitter:((Mc=le.remoteData)==null?void 0:Mc.jitter)||0}),S.set(T,{score:+(le.score*10).toFixed(),bitrate:((le.bytesSent||0)-(((Oc=this.audioProducerToStatsMap.get(T))==null?void 0:Oc.bytesSent)||0))*8/7,packetsLostPercentage:Jc({packetsSent:(le.packetsSent||0)-(((Dc=this.audioProducerToStatsMap.get(T))==null?void 0:Dc.packetsSent)||0),packetsLost:(((Nc=le.remoteData)==null?void 0:Nc.packetsLost)||0)-(((Lc=(Vc=this.audioProducerToStatsMap.get(T))==null?void 0:Vc.remoteData)==null?void 0:Lc.packetsLost)||0)}),jitter:((xc=le.remoteData)==null?void 0:xc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,le)}}),m.forEach(I=>{const T=u.find(B=>B.id===I.localCandidateId?(I.localCandidateId=B.id,B):null),P=h.find(B=>B.id===I.remoteCandidateId?(I.remoteCandidateId=B.id,B):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=wr(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=wr(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=wr(P.address),I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.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 I=0,T=0;d.remoteInboundRtp.forEach((P,B)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(I){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(I){}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||$p},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 sT(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 rT(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||$p},d=new eT(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 Up.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?Bp(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?Bp(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 nT extends Hp{}class qp extends Hp{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,b,R,N,U,L,F,H,ie,ut,Us,Ps,un;const c=e,d=new Fp,l=r.length?new Set(r):void 0,u=[],h=[],m=[],S=new Map,y=new Map;for(const I of c.values()){if(l){if(l.size===0)break;if(l.has(I.type))i&&l.delete(I.type);else continue}switch(I.type){case"local-candidate":{u.push(this.getIceCandidateStats(I));break}case"remote-candidate":{h.push(this.getIceCandidateStats(I));break}case"candidate-pair":{const{nominated:T}=I,{selected:P}=I,B=I,be={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(be),(I.nominated===!0||I.selected===!0)&&(d.candidatePair=be);break}case"transport":{const T=I;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=I,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(I.id))break;const T=I,P=n||this.outboundProducerMap.get(I.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 be=this.overallProducersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.outboundProducerMap.has(I.id)){d.staleProducerStreamMap=!0;break}const De=this.callStatsInstance.producers.get(P);if(((w=De==null?void 0:De.track)==null?void 0:w.readyState)==="ended")break;d.producerStreamMap.has(P)||d.producerStreamMap.set(P,{outboundVideoRtpId:[],outboundAudioRtpId:[]});const V={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 k=T,Be={frameHeight:k.frameHeight,frameWidth:k.frameWidth,framesEncoded:k.framesEncoded,framesDropped:k.framesDropped?k.framesDropped:k.droppedFrames,framesPerSecond:k.framesPerSecond?k.framesPerSecond:k.framerateMean,framesSent:k.framesSent,keyFramesEncoded:k.keyFramesEncoded,firCount:k.firCount,encoderImplementation:k.encoderImplementation,hugeFramesSent:k.hugeFramesSent,pliCount:k.pliCount,qpSum:k.qpSum,qualityLimitationReason:k.qualityLimitationReason,qualityLimitationDurations:k.qualityLimitationDurations,qualityLimitationResolutionChanges:k.qualityLimitationResolutionChanges,totalEncodeTime:k.totalEncodeTime,totalPacketSendDelay:k.totalEncodeTime,retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,scalabilityMode:k.scalabilityMode,powerEfficientEncoder:k.powerEfficientEncoder,...V};d.outboundVideoRtp.set(I.id,Be),d.producerStreamMap.get(P).outboundVideoRtpId.push(I.id),this.processOutboundProducerVideoStats(P,be,Be)}else if(T.mediaType==="audio"||T.kind==="audio"){const k=T,Be={retransmittedBytesSent:k.retransmittedBytesSent,retransmittedPacketsSent:k.retransmittedPacketsSent,...V};d.outboundAudioRtp.set(I.id,Be),d.producerStreamMap.get(P).outboundAudioRtpId.push(I.id),this.processOutboundProducerAudioStats(P,be,Be)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Outbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}case"inbound-rtp":{if(!this.inboundConsumerMap.has(I.id))break;const T=I,P=n||this.inboundConsumerMap.get(I.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 be=this.overallConsumersStatsMap[P];if(["video","audio"].includes(T.mediaType)||["video","audio"].includes(T.kind)){if(!this.inboundConsumerMap.has(I.id)){d.staleConsumerStreamMap=!0;break}d.consumerStreamMap.has(P)||d.consumerStreamMap.set(P,{inboundVideoRtpId:[],inboundAudioRtpId:[]});const De={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 V=T,k={frameHeight:V.frameHeight,frameWidth:V.frameWidth,framesDecoded:V.framesDecoded,framesDropped:V.framesDropped?V.framesDropped:V.droppedFrames,framesPerSecond:V.framesPerSecond?V.framesPerSecond:V.framerateMean,framesReceived:V.framesReceived,keyFramesDecoded:V.keyFramesDecoded,firCount:V.firCount,decoderImplementation:V.decoderImplementation,pliCount:V.pliCount,totalProcessingDelay:V.totalProcessingDelay,qpSum:V.qpSum||0,totalAssemblyTime:V.totalAssemblyTime||0,totalDecodeTime:V.totalDecodeTime||0,totalFreezesDuration:V.totalFreezesDuration||0,totalInterFrameDelay:V.totalInterFrameDelay||0,totalPausesDuration:V.totalPausesDuration||0,totalSquaredInterFrameDelay:V.totalSquaredInterFrameDelay||0,freezeCount:V.freezeCount||0,pauseCount:V.pauseCount||0,powerEfficientDecoder:V.powerEfficientDecoder,...De};k.score=Lp({frameWidth:k.frameWidth||0,framesDecoded:(k.framesDecoded||0)-(((b=this.videoConsumerToStatsMap.get(P))==null?void 0:b.framesDecoded)||0),framesPerSecond:k.framesPerSecond||0,packetsLost:(k.packetsLost||0)-(((R=this.videoConsumerToStatsMap.get(P))==null?void 0:R.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((N=this.videoConsumerToStatsMap.get(P))==null?void 0:N.packetsReceived)||0),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P)}),y.set(P,{score:+(k.score*10).toFixed(),frameWidth:k.frameWidth||0,frameHeight:k.frameHeight||0,framesPerSecond:k.framesPerSecond||0,packetsLostPercentage:Kc({packetsLost:(k.packetsLost||0)-(((U=this.videoConsumerToStatsMap.get(P))==null?void 0:U.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((L=this.videoConsumerToStatsMap.get(P))==null?void 0:L.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((k.bytesReceived||0)-(((F=this.videoConsumerToStatsMap.get(P))==null?void 0:F.bytesReceived)||0))*8/7}),this.videoConsumerToStatsMap.set(P,k),d.inboundVideoRtp.set(I.id,k),d.consumerStreamMap.get(P).inboundVideoRtpId.push(I.id),this.processInboundConsumerVideoStats(P,be,k)}else if(T.mediaType==="audio"||T.kind==="audio"){const V=T,k={audioLevel:V.audioLevel,concealedSamples:V.concealedSamples,concealmentEvents:V.concealmentEvents,totalAudioEnergy:V.totalAudioEnergy,totalSamplesDuration:V.totalSamplesDuration,totalSamplesReceived:V.totalSamplesReceived,fecPacketsDiscarded:V.fecPacketsDiscarded||0,fecPacketsReceived:V.fecPacketsReceived||0,insertedSamplesForDeceleration:V.insertedSamplesForDeceleration||0,removedSamplesForAcceleration:V.removedSamplesForAcceleration||0,silentConcealedSamples:V.silentConcealedSamples||0,playoutId:V.playoutId,...De};k.score=Vp({concealmentEvents:(k.concealmentEvents||0)-(((H=this.audioConsumerToStatsMap.get(P))==null?void 0:H.concealmentEvents)||0),packetsLost:(k.packetsLost||0)-(((ie=this.audioConsumerToStatsMap.get(P))==null?void 0:ie.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((ut=this.audioConsumerToStatsMap.get(P))==null?void 0:ut.packetsReceived)||0),jitter:k.jitter||0}),y.set(P,{score:+(k.score*10).toFixed(),packetsLostPercentage:Kc({packetsLost:(k.packetsLost||0)-(((Us=this.audioConsumerToStatsMap.get(P))==null?void 0:Us.packetsLost)||0),packetsReceived:(k.packetsReceived||0)-(((Ps=this.audioConsumerToStatsMap.get(P))==null?void 0:Ps.packetsReceived)||0)}),jitter:k.jitter||0,isScreenShare:this.screenShareConsumers.has(P),bitrate:((k.bytesReceived||0)-(((un=this.audioConsumerToStatsMap.get(P))==null?void 0:un.bytesReceived)||0))*8/7}),this.audioConsumerToStatsMap.set(P,k),d.inboundAudioRtp.set(I.id,k),d.consumerStreamMap.get(P).inboundAudioRtpId.push(I.id),this.processInboundConsumerAudioStats(P,be,k)}}else this.callStatsInstance.logger.error(`Callstats: Unknown Inbound-rtp. mediatype: ${T.mediaType} kind: ${T.kind}`);break}}}if(d.producerStreamMap.forEach((I,T)=>{var P,B,be,De,V,k,Be,hn,bc,Pc,_c,Cc,kc,Rc,Ic,Ac,Mc,Oc,Dc,Nc,Vc,Lc,xc;if(I.outboundVideoRtpId.length>0){const le=[];I.outboundVideoRtpId.forEach(Uh=>{le.push(d.outboundVideoRtp.get(Uh))});const X=this.getWorkingSimulcastVideoStats(le);X.score=Dp({frameWidth:X.frameWidth||0,framesPerSecond:X.framesPerSecond||0,jitter:((P=X.remoteData)==null?void 0:P.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsSent:(X.packetsSent||0)-(((B=this.videoProducerToStatsMap.get(T))==null?void 0:B.packetsSent)||0),packetsLost:(((be=X.remoteData)==null?void 0:be.packetsLost)||0)-(((V=(De=this.videoProducerToStatsMap.get(T))==null?void 0:De.remoteData)==null?void 0:V.packetsLost)||0),framesEncoded:(X.framesEncoded||0)-(((k=this.videoProducerToStatsMap.get(T))==null?void 0:k.framesEncoded)||0)}),S.set(T,{score:+(X.score*10).toFixed(),frameWidth:X.frameWidth||0,frameHeight:X.frameHeight||0,framesPerSecond:X.framesPerSecond||0,jitter:((Be=X.remoteData)==null?void 0:Be.jitter)||0,isScreenShare:this.screenShareProducers.has(T),packetsLostPercentage:Jc({packetsSent:(X.packetsSent||0)-(((hn=this.videoProducerToStatsMap.get(T))==null?void 0:hn.packetsSent)||0),packetsLost:(((bc=X.remoteData)==null?void 0:bc.packetsLost)||0)-(((_c=(Pc=this.videoProducerToStatsMap.get(T))==null?void 0:Pc.remoteData)==null?void 0:_c.packetsLost)||0)}),bitrate:((X.bytesSent||0)-(((Cc=this.videoProducerToStatsMap.get(T))==null?void 0:Cc.bytesSent)||0))*8/7,cpuLimitations:X.qualityLimitationReason==="cpu",bandwidthLimitations:X.qualityLimitationReason==="bandwidth"}),this.videoProducerToStatsMap.set(T,X)}else if(I.outboundAudioRtpId.length>0){const le=d.outboundAudioRtp.get(I.outboundAudioRtpId[0]);le.score=Op({packetsSent:(le.packetsSent||0)-(((kc=this.audioProducerToStatsMap.get(T))==null?void 0:kc.packetsSent)||0),packetsLost:(((Rc=le.remoteData)==null?void 0:Rc.packetsLost)||0)-(((Ac=(Ic=this.audioProducerToStatsMap.get(T))==null?void 0:Ic.remoteData)==null?void 0:Ac.packetsLost)||0),jitter:((Mc=le.remoteData)==null?void 0:Mc.jitter)||0}),S.set(T,{score:+(le.score*10).toFixed(),bitrate:((le.bytesSent||0)-(((Oc=this.audioProducerToStatsMap.get(T))==null?void 0:Oc.bytesSent)||0))*8/7,packetsLostPercentage:Jc({packetsSent:(le.packetsSent||0)-(((Dc=this.audioProducerToStatsMap.get(T))==null?void 0:Dc.packetsSent)||0),packetsLost:(((Nc=le.remoteData)==null?void 0:Nc.packetsLost)||0)-(((Lc=(Vc=this.audioProducerToStatsMap.get(T))==null?void 0:Vc.remoteData)==null?void 0:Lc.packetsLost)||0)}),jitter:((xc=le.remoteData)==null?void 0:xc.jitter)||0,isScreenShare:this.screenShareProducers.has(T)}),this.audioProducerToStatsMap.set(T,le)}}),m.forEach(I=>{const T=u.find(B=>B.id===I.localCandidateId?(I.localCandidateId=B.id,B):null),P=h.find(B=>B.id===I.remoteCandidateId?(I.remoteCandidateId=B.id,B):null);T&&(I.localCandidateType=T.type,I.localCandidateAddress=wr(T.address),I.localCandidatePort=T.port,I.localCandidateProtocol=T.protocol,I.localCandidateUrl=T.url,I.localCandidateNetworkType=T.networkType,I.localCandidateRelatedAddress=wr(T.relatedAddress),I.localCandidateRelatedPort=T.relatedPort),P&&(I.remoteCandidateType=P.type,I.remoteCandidateAddress=wr(P.address),I.remoteCandidatePort=P.port,I.remoteCandidateProtocol=P.protocol,I.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 I=0,T=0;d.remoteInboundRtp.forEach((P,B)=>{P.roundTripTime&&P.roundTripTime>I&&(I=P.roundTripTime,T=P.totalRoundTripTime)}),d.transport.roundTripTime=I,d.transport.totalRoundTripTime=T}if(y.size>0)try{this.observer.emit("consumer_score",y)}catch(I){}if(S.size>0)try{this.observer.emit("producer_score",S)}catch(I){}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 aT extends qp{}function Xc(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 jp(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=>{Xc(this,t,e,o)}):n}catch(n){Xc(this,t,e,n)}return null},s}const Y=(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=>{Xc(this,s,t,d)}):c}catch(c){Xc(this,s,t,c)}return null},i},oT=(s,t)=>(e,r,i)=>{if(i)return jp(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,jp(o,s,t))}};var K=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 z=console;let W=class extends it{constructor(e="https://api.testingv3.dyte.in",r="Blink",i=Pp.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 Gv({logger:o,peerId:c,apiHostnames:d,authToken:l}),this.logger.debug("callStats::engineName: ",{engineName:r}),r){case"Blink":this.measurements=new nT;break;case"Gecko":this.measurements=new qp;break;case"WebKit":this.measurements=new aT;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 it,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}})}};K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerIceServers",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerConsumer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerProducer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendConsumerSharedMediaStateEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerProducingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"registerConsumingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"deRegisterConsumer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"deRegisterProducer",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"disconnectConsumingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"disconnectProducingTransport",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPreCallTestBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendScreenShareToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendScreenShareRequestedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendActiveSpeakerEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"devices",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"selectedDevice",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaPermission",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaPlaybackFailed",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"mediaTrackMuted",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"tabChanged",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"browserBackgrounded",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"browserForegrounded",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"legacySwitch",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"getPreCallTestResults",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendCallJoinBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendNetworkQualityTestBeginEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendWebSocketConnectedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendTransportConnectedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendAudioToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendVideoToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendParticipantRoleToggleEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"startPingStats",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"stopPingStats",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPingStatsEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerRebufferEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerAudioBlockEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerPlaybackBlockedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerNetworkUnavailableEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerInitializedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerWorkerErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerRecoverableErrorEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerAnalyticsEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerPlaybackRateChangedEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendIVSPlayerQualityChanged",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendPlayerLiveLatency",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendDisconnectEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"sendReconnectEvent",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"expectedVideoResolution",null),K([Y(TypeError,(s,t)=>z.error(t,s))],W.prototype,"expectedScreenshareResolution",null),W=K([oT(TypeError,(s,t)=>z.error(t,s))],W);const cT=W;class Gp extends it{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=Pp.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 Up.getIPDetails({peerId:e,apiHostnames:l,logger:d}),this.backend=new cT(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 Gp().setMaxListeners(30);class dT{constructor(){g(this,vo,void 0)}get telemetry(){var t;return(t=a(this,vo))==null?void 0:t.getValue("telemetry")}init(t){f(this,vo,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)}}vo=new WeakMap;class lT extends it.EventEmitter{constructor(e){super();g(this,rr,void 0);g(this,ir,void 0);p(this,"asyncPromiseTimeout");p(this,"logger");this.logger=e,f(this,rr,new Map),f(this,ir,new Map),this.asyncPromiseTimeout=8e3}async emitAsync(e,...r){a(this,rr).set(e,[]);const i=a(this,ir).get(e).map(()=>new Promise(n=>{a(this,rr).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,rr).delete(e)}onAsync(e,r){const i=a(this,rr),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,ir).get(e)||a(this,ir).set(e,[]),a(this,ir).get(e).push(n),super.on(e,n)}reset(){f(this,rr,new Map),f(this,ir,new Map),super.removeAllListeners()}}rr=new WeakMap,ir=new WeakMap;var uT=typeof global=="object"&&global&&global.Object===Object&&global;const Wp=uT;var hT=typeof self=="object"&&self&&self.Object===Object&&self,pT=Wp||hT||Function("return this")();const os=pT;var mT=os.Symbol;const Cs=mT;var Jp=Object.prototype,gT=Jp.hasOwnProperty,fT=Jp.toString,$a=Cs?Cs.toStringTag:void 0;function ST(s){var t=gT.call(s,$a),e=s[$a];try{s[$a]=void 0;var r=!0}catch(n){}var i=fT.call(s);return r&&(t?s[$a]=e:delete s[$a]),i}var vT=Object.prototype,TT=vT.toString;function yT(s){return TT.call(s)}var ET="[object Null]",wT="[object Undefined]",Kp=Cs?Cs.toStringTag:void 0;function ni(s){return s==null?s===void 0?wT:ET:Kp&&Kp in Object(s)?ST(s):yT(s)}function ks(s){return s!=null&&typeof s=="object"}var bT="[object Symbol]";function Zc(s){return typeof s=="symbol"||ks(s)&&ni(s)==bT}function PT(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 _T=Array.isArray;const Ot=_T;var CT=1/0,zp=Cs?Cs.prototype:void 0,Yp=zp?zp.toString:void 0;function Qp(s){if(typeof s=="string")return s;if(Ot(s))return PT(s,Qp)+"";if(Zc(s))return Yp?Yp.call(s):"";var t=s+"";return t=="0"&&1/s==-CT?"-0":t}var kT=/\s/;function RT(s){for(var t=s.length;t--&&kT.test(s.charAt(t)););return t}var IT=/^\s+/;function AT(s){return s&&s.slice(0,RT(s)+1).replace(IT,"")}function Kt(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var Xp=0/0,MT=/^[-+]0x[0-9a-f]+$/i,OT=/^0b[01]+$/i,DT=/^0o[0-7]+$/i,NT=parseInt;function Zp(s){if(typeof s=="number")return s;if(Zc(s))return Xp;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=AT(s);var e=OT.test(s);return e||DT.test(s)?NT(s.slice(2),e?2:8):MT.test(s)?Xp:+s}function au(s){return s}var VT="[object AsyncFunction]",LT="[object Function]",xT="[object GeneratorFunction]",UT="[object Proxy]";function ou(s){if(!Kt(s))return!1;var t=ni(s);return t==LT||t==xT||t==VT||t==UT}var $T=os["__core-js_shared__"];const cu=$T;var em=function(){var s=/[^.]+$/.exec(cu&&cu.keys&&cu.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function BT(s){return!!em&&em in s}var FT=Function.prototype,HT=FT.toString;function ai(s){if(s!=null){try{return HT.call(s)}catch(t){}try{return s+""}catch(t){}}return""}var qT=/[\\^$.*+?()[\]{}|]/g,jT=/^\[object .+?Constructor\]$/,GT=Function.prototype,WT=Object.prototype,JT=GT.toString,KT=WT.hasOwnProperty,zT=RegExp("^"+JT.call(KT).replace(qT,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function YT(s){if(!Kt(s)||BT(s))return!1;var t=ou(s)?zT:jT;return t.test(ai(s))}function QT(s,t){return s==null?void 0:s[t]}function oi(s,t){var e=QT(s,t);return YT(e)?e:void 0}var XT=oi(os,"WeakMap");const du=XT;var tm=Object.create,ZT=function(){function s(){}return function(t){if(!Kt(t))return{};if(tm)return tm(t);s.prototype=t;var e=new s;return s.prototype=void 0,e}}();const ey=ZT;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 sy(){}function sm(s,t){var e=-1,r=s.length;for(t||(t=Array(r));++e<r;)t[e]=s[e];return t}var ry=800,iy=16,ny=Date.now;function ay(s){var t=0,e=0;return function(){var r=ny(),i=iy-(r-e);if(e=r,i>0){if(++t>=ry)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}function oy(s){return function(){return s}}var cy=function(){try{var s=oi(Object,"defineProperty");return s({},"",{}),s}catch(t){}}();const ed=cy;var dy=ed?function(s,t){return ed(s,"toString",{configurable:!0,enumerable:!1,value:oy(t),writable:!0})}:au,ly=ay(dy);const uy=ly;function hy(s,t){for(var e=-1,r=s==null?0:s.length;++e<r&&t(s[e],e,s)!==!1;);return s}function py(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 gy(s,t,e){for(var r=e-1,i=s.length;++r<i;)if(s[r]===t)return r;return-1}function fy(s,t,e){return t===t?gy(s,t,e):py(s,my,e)}function Sy(s,t){var e=s==null?0:s.length;return!!e&&fy(s,t,0)>-1}var vy=9007199254740991,Ty=/^(?:0|[1-9]\d*)$/;function lu(s,t){var e=typeof s;return t=t==null?vy:t,!!t&&(e=="number"||e!="symbol"&&Ty.test(s))&&s>-1&&s%1==0&&s<t}function uu(s,t,e){t=="__proto__"&&ed?ed(s,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):s[t]=e}function Ba(s,t){return s===t||s!==s&&t!==t}var yy=Object.prototype,Ey=yy.hasOwnProperty;function rm(s,t,e){var r=s[t];(!(Ey.call(s,t)&&Ba(r,e))||e===void 0&&!(t in s))&&uu(s,t,e)}function Fa(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?uu(e,c,d):rm(e,c,d)}return e}var im=Math.max;function wy(s,t,e){return t=im(t===void 0?s.length-1:t,0),function(){for(var r=arguments,i=-1,n=im(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 by(s,t){return uy(wy(s,t,au),s+"")}var Py=9007199254740991;function hu(s){return typeof s=="number"&&s>-1&&s%1==0&&s<=Py}function Ha(s){return s!=null&&hu(s.length)&&!ou(s)}function _y(s,t,e){if(!Kt(e))return!1;var r=typeof t;return(r=="number"?Ha(e)&&lu(t,e.length):r=="string"&&t in e)?Ba(e[t],s):!1}function Cy(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&&_y(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 ky=Object.prototype;function td(s){var t=s&&s.constructor,e=typeof t=="function"&&t.prototype||ky;return s===e}function Ry(s,t){for(var e=-1,r=Array(s);++e<s;)r[e]=t(e);return r}var Iy="[object Arguments]";function nm(s){return ks(s)&&ni(s)==Iy}var am=Object.prototype,Ay=am.hasOwnProperty,My=am.propertyIsEnumerable,Oy=nm(function(){return arguments}())?nm:function(s){return ks(s)&&Ay.call(s,"callee")&&!My.call(s,"callee")};const qa=Oy;function Dy(){return!1}var om=typeof exports=="object"&&exports&&!exports.nodeType&&exports,cm=om&&typeof module=="object"&&module&&!module.nodeType&&module,Ny=cm&&cm.exports===om,dm=Ny?os.Buffer:void 0,Vy=dm?dm.isBuffer:void 0,Ly=Vy||Dy;const fn=Ly;var xy="[object Arguments]",Uy="[object Array]",$y="[object Boolean]",By="[object Date]",Fy="[object Error]",Hy="[object Function]",qy="[object Map]",jy="[object Number]",Gy="[object Object]",Wy="[object RegExp]",Jy="[object Set]",Ky="[object String]",zy="[object WeakMap]",Yy="[object ArrayBuffer]",Qy="[object DataView]",Xy="[object Float32Array]",Zy="[object Float64Array]",eE="[object Int8Array]",tE="[object Int16Array]",sE="[object Int32Array]",rE="[object Uint8Array]",iE="[object Uint8ClampedArray]",nE="[object Uint16Array]",aE="[object Uint32Array]",fe={};fe[Xy]=fe[Zy]=fe[eE]=fe[tE]=fe[sE]=fe[rE]=fe[iE]=fe[nE]=fe[aE]=!0,fe[xy]=fe[Uy]=fe[Yy]=fe[$y]=fe[Qy]=fe[By]=fe[Fy]=fe[Hy]=fe[qy]=fe[jy]=fe[Gy]=fe[Wy]=fe[Jy]=fe[Ky]=fe[zy]=!1;function oE(s){return ks(s)&&hu(s.length)&&!!fe[ni(s)]}function pu(s){return function(t){return s(t)}}var lm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ja=lm&&typeof module=="object"&&module&&!module.nodeType&&module,cE=ja&&ja.exports===lm,mu=cE&&Wp.process,dE=function(){try{var s=ja&&ja.require&&ja.require("util").types;return s||mu&&mu.binding&&mu.binding("util")}catch(t){}}();const Sn=dE;var um=Sn&&Sn.isTypedArray,lE=um?pu(um):oE;const sd=lE;var uE=Object.prototype,hE=uE.hasOwnProperty;function hm(s,t){var e=Ot(s),r=!e&&qa(s),i=!e&&!r&&fn(s),n=!e&&!r&&!i&&sd(s),o=e||r||i||n,c=o?Ry(s.length,String):[],d=c.length;for(var l in s)(t||hE.call(s,l))&&!(o&&(l=="length"||i&&(l=="offset"||l=="parent")||n&&(l=="buffer"||l=="byteLength"||l=="byteOffset")||lu(l,d)))&&c.push(l);return c}function pm(s,t){return function(e){return s(t(e))}}var pE=pm(Object.keys,Object);const mE=pE;var gE=Object.prototype,fE=gE.hasOwnProperty;function mm(s){if(!td(s))return mE(s);var t=[];for(var e in Object(s))fE.call(s,e)&&e!="constructor"&&t.push(e);return t}function rd(s){return Ha(s)?hm(s):mm(s)}function SE(s){var t=[];if(s!=null)for(var e in Object(s))t.push(e);return t}var vE=Object.prototype,TE=vE.hasOwnProperty;function yE(s){if(!Kt(s))return SE(s);var t=td(s),e=[];for(var r in s)r=="constructor"&&(t||!TE.call(s,r))||e.push(r);return e}function Ga(s){return Ha(s)?hm(s,!0):yE(s)}var EE=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,wE=/^\w*$/;function gu(s,t){if(Ot(s))return!1;var e=typeof s;return e=="number"||e=="symbol"||e=="boolean"||s==null||Zc(s)?!0:wE.test(s)||!EE.test(s)||t!=null&&s in Object(t)}var bE=oi(Object,"create");const Wa=bE;function PE(){this.__data__=Wa?Wa(null):{},this.size=0}function _E(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var CE="__lodash_hash_undefined__",kE=Object.prototype,RE=kE.hasOwnProperty;function IE(s){var t=this.__data__;if(Wa){var e=t[s];return e===CE?void 0:e}return RE.call(t,s)?t[s]:void 0}var AE=Object.prototype,ME=AE.hasOwnProperty;function OE(s){var t=this.__data__;return Wa?t[s]!==void 0:ME.call(t,s)}var DE="__lodash_hash_undefined__";function NE(s,t){var e=this.__data__;return this.size+=this.has(s)?0:1,e[s]=Wa&&t===void 0?DE:t,this}function ci(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])}}ci.prototype.clear=PE,ci.prototype.delete=_E,ci.prototype.get=IE,ci.prototype.has=OE,ci.prototype.set=NE;function VE(){this.__data__=[],this.size=0}function id(s,t){for(var e=s.length;e--;)if(Ba(s[e][0],t))return e;return-1}var LE=Array.prototype,xE=LE.splice;function UE(s){var t=this.__data__,e=id(t,s);if(e<0)return!1;var r=t.length-1;return e==r?t.pop():xE.call(t,e,1),--this.size,!0}function $E(s){var t=this.__data__,e=id(t,s);return e<0?void 0:t[e][1]}function BE(s){return id(this.__data__,s)>-1}function FE(s,t){var e=this.__data__,r=id(e,s);return r<0?(++this.size,e.push([s,t])):e[r][1]=t,this}function Fs(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])}}Fs.prototype.clear=VE,Fs.prototype.delete=UE,Fs.prototype.get=$E,Fs.prototype.has=BE,Fs.prototype.set=FE;var HE=oi(os,"Map");const Ja=HE;function qE(){this.size=0,this.__data__={hash:new ci,map:new(Ja||Fs),string:new ci}}function jE(s){var t=typeof s;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?s!=="__proto__":s===null}function nd(s,t){var e=s.__data__;return jE(t)?e[typeof t=="string"?"string":"hash"]:e.map}function GE(s){var t=nd(this,s).delete(s);return this.size-=t?1:0,t}function WE(s){return nd(this,s).get(s)}function JE(s){return nd(this,s).has(s)}function KE(s,t){var e=nd(this,s),r=e.size;return e.set(s,t),this.size+=e.size==r?0:1,this}function Hs(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])}}Hs.prototype.clear=qE,Hs.prototype.delete=GE,Hs.prototype.get=WE,Hs.prototype.has=JE,Hs.prototype.set=KE;var zE="Expected a function";function fu(s,t){if(typeof s!="function"||t!=null&&typeof t!="function")throw new TypeError(zE);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(fu.Cache||Hs),e}fu.Cache=Hs;var YE=500;function QE(s){var t=fu(s,function(r){return e.size===YE&&e.clear(),r}),e=t.cache;return t}var XE=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ZE=/\\(\\)?/g,ew=QE(function(s){var t=[];return s.charCodeAt(0)===46&&t.push(""),s.replace(XE,function(e,r,i,n){t.push(i?n.replace(ZE,"$1"):r||e)}),t});const tw=ew;function sw(s){return s==null?"":Qp(s)}function gm(s,t){return Ot(s)?s:gu(s,t)?[s]:tw(sw(s))}var rw=1/0;function ad(s){if(typeof s=="string"||Zc(s))return s;var t=s+"";return t=="0"&&1/s==-rw?"-0":t}function fm(s,t){t=gm(t,s);for(var e=0,r=t.length;s!=null&&e<r;)s=s[ad(t[e++])];return e&&e==r?s:void 0}function iw(s,t,e){var r=s==null?void 0:fm(s,t);return r===void 0?e:r}function Sm(s,t){for(var e=-1,r=t.length,i=s.length;++e<r;)s[i+e]=t[e];return s}var nw=pm(Object.getPrototypeOf,Object);const Su=nw;var aw="[object Object]",ow=Function.prototype,cw=Object.prototype,vm=ow.toString,dw=cw.hasOwnProperty,lw=vm.call(Object);function uw(s){if(!ks(s)||ni(s)!=aw)return!1;var t=Su(s);if(t===null)return!0;var e=dw.call(t,"constructor")&&t.constructor;return typeof e=="function"&&e instanceof e&&vm.call(e)==lw}function hw(){this.__data__=new Fs,this.size=0}function pw(s){var t=this.__data__,e=t.delete(s);return this.size=t.size,e}function mw(s){return this.__data__.get(s)}function gw(s){return this.__data__.has(s)}var fw=200;function Sw(s,t){var e=this.__data__;if(e instanceof Fs){var r=e.__data__;if(!Ja||r.length<fw-1)return r.push([s,t]),this.size=++e.size,this;e=this.__data__=new Hs(r)}return e.set(s,t),this.size=e.size,this}function cs(s){var t=this.__data__=new Fs(s);this.size=t.size}cs.prototype.clear=hw,cs.prototype.delete=pw,cs.prototype.get=mw,cs.prototype.has=gw,cs.prototype.set=Sw;function vw(s,t){return s&&Fa(t,rd(t),s)}function Tw(s,t){return s&&Fa(t,Ga(t),s)}var Tm=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ym=Tm&&typeof module=="object"&&module&&!module.nodeType&&module,yw=ym&&ym.exports===Tm,Em=yw?os.Buffer:void 0,wm=Em?Em.allocUnsafe:void 0;function bm(s,t){if(t)return s.slice();var e=s.length,r=wm?wm(e):new s.constructor(e);return s.copy(r),r}function Ew(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 Pm(){return[]}var ww=Object.prototype,bw=ww.propertyIsEnumerable,_m=Object.getOwnPropertySymbols,Pw=_m?function(s){return s==null?[]:(s=Object(s),Ew(_m(s),function(t){return bw.call(s,t)}))}:Pm;const vu=Pw;function _w(s,t){return Fa(s,vu(s),t)}var Cw=Object.getOwnPropertySymbols,kw=Cw?function(s){for(var t=[];s;)Sm(t,vu(s)),s=Su(s);return t}:Pm;const Cm=kw;function Rw(s,t){return Fa(s,Cm(s),t)}function km(s,t,e){var r=t(s);return Ot(s)?r:Sm(r,e(s))}function Tu(s){return km(s,rd,vu)}function Iw(s){return km(s,Ga,Cm)}var Aw=oi(os,"DataView");const yu=Aw;var Mw=oi(os,"Promise");const Eu=Mw;var Ow=oi(os,"Set");const vn=Ow;var Rm="[object Map]",Dw="[object Object]",Im="[object Promise]",Am="[object Set]",Mm="[object WeakMap]",Om="[object DataView]",Nw=ai(yu),Vw=ai(Ja),Lw=ai(Eu),xw=ai(vn),Uw=ai(du),di=ni;(yu&&di(new yu(new ArrayBuffer(1)))!=Om||Ja&&di(new Ja)!=Rm||Eu&&di(Eu.resolve())!=Im||vn&&di(new vn)!=Am||du&&di(new du)!=Mm)&&(di=function(s){var t=ni(s),e=t==Dw?s.constructor:void 0,r=e?ai(e):"";if(r)switch(r){case Nw:return Om;case Vw:return Rm;case Lw:return Im;case xw:return Am;case Uw:return Mm}return t});const Tn=di;var $w=Object.prototype,Bw=$w.hasOwnProperty;function Fw(s){var t=s.length,e=new s.constructor(t);return t&&typeof s[0]=="string"&&Bw.call(s,"index")&&(e.index=s.index,e.input=s.input),e}var Hw=os.Uint8Array;const od=Hw;function wu(s){var t=new s.constructor(s.byteLength);return new od(t).set(new od(s)),t}function qw(s,t){var e=t?wu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.byteLength)}var jw=/\w*$/;function Gw(s){var t=new s.constructor(s.source,jw.exec(s));return t.lastIndex=s.lastIndex,t}var Dm=Cs?Cs.prototype:void 0,Nm=Dm?Dm.valueOf:void 0;function Ww(s){return Nm?Object(Nm.call(s)):{}}function Vm(s,t){var e=t?wu(s.buffer):s.buffer;return new s.constructor(e,s.byteOffset,s.length)}var Jw="[object Boolean]",Kw="[object Date]",zw="[object Map]",Yw="[object Number]",Qw="[object RegExp]",Xw="[object Set]",Zw="[object String]",eb="[object Symbol]",tb="[object ArrayBuffer]",sb="[object DataView]",rb="[object Float32Array]",ib="[object Float64Array]",nb="[object Int8Array]",ab="[object Int16Array]",ob="[object Int32Array]",cb="[object Uint8Array]",db="[object Uint8ClampedArray]",lb="[object Uint16Array]",ub="[object Uint32Array]";function hb(s,t,e){var r=s.constructor;switch(t){case tb:return wu(s);case Jw:case Kw:return new r(+s);case sb:return qw(s,e);case rb:case ib:case nb:case ab:case ob:case cb:case db:case lb:case ub:return Vm(s,e);case zw:return new r;case Yw:case Zw:return new r(s);case Qw:return Gw(s);case Xw:return new r;case eb:return Ww(s)}}function Lm(s){return typeof s.constructor=="function"&&!td(s)?ey(Su(s)):{}}var pb="[object Map]";function mb(s){return ks(s)&&Tn(s)==pb}var xm=Sn&&Sn.isMap,gb=xm?pu(xm):mb;const fb=gb;var Sb="[object Set]";function vb(s){return ks(s)&&Tn(s)==Sb}var Um=Sn&&Sn.isSet,Tb=Um?pu(Um):vb;const yb=Tb;var Eb=1,wb=2,bb=4,$m="[object Arguments]",Pb="[object Array]",_b="[object Boolean]",Cb="[object Date]",kb="[object Error]",Bm="[object Function]",Rb="[object GeneratorFunction]",Ib="[object Map]",Ab="[object Number]",Fm="[object Object]",Mb="[object RegExp]",Ob="[object Set]",Db="[object String]",Nb="[object Symbol]",Vb="[object WeakMap]",Lb="[object ArrayBuffer]",xb="[object DataView]",Ub="[object Float32Array]",$b="[object Float64Array]",Bb="[object Int8Array]",Fb="[object Int16Array]",Hb="[object Int32Array]",qb="[object Uint8Array]",jb="[object Uint8ClampedArray]",Gb="[object Uint16Array]",Wb="[object Uint32Array]",ue={};ue[$m]=ue[Pb]=ue[Lb]=ue[xb]=ue[_b]=ue[Cb]=ue[Ub]=ue[$b]=ue[Bb]=ue[Fb]=ue[Hb]=ue[Ib]=ue[Ab]=ue[Fm]=ue[Mb]=ue[Ob]=ue[Db]=ue[Nb]=ue[qb]=ue[jb]=ue[Gb]=ue[Wb]=!0,ue[kb]=ue[Bm]=ue[Vb]=!1;function Ka(s,t,e,r,i,n){var o,c=t&Eb,d=t&wb,l=t&bb;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=Fw(s),!c)return sm(s,o)}else{var h=Tn(s),m=h==Bm||h==Rb;if(fn(s))return bm(s,c);if(h==Fm||h==$m||m&&!i){if(o=d||m?{}:Lm(s),!c)return d?Rw(s,Tw(o,s)):_w(s,vw(o,s))}else{if(!ue[h])return i?s:{};o=hb(s,h,c)}}n||(n=new cs);var S=n.get(s);if(S)return S;n.set(s,o),yb(s)?s.forEach(function(b){o.add(Ka(b,t,e,b,s,n))}):fb(s)&&s.forEach(function(b,R){o.set(R,Ka(b,t,e,R,s,n))});var y=l?d?Iw:Tu:d?Ga:rd,w=u?void 0:y(s);return hy(w||s,function(b,R){w&&(R=b,b=s[R]),rm(o,R,Ka(b,t,e,R,s,n))}),o}var Jb=4;function Kb(s){return Ka(s,Jb)}var zb=1,Yb=4;function bu(s){return Ka(s,zb|Yb)}var Qb="__lodash_hash_undefined__";function Xb(s){return this.__data__.set(s,Qb),this}function Zb(s){return this.__data__.has(s)}function za(s){var t=-1,e=s==null?0:s.length;for(this.__data__=new Hs;++t<e;)this.add(s[t])}za.prototype.add=za.prototype.push=Xb,za.prototype.has=Zb;function eP(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 Hm(s,t){return s.has(t)}var tP=1,sP=2;function qm(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&sP?new za:void 0;for(n.set(s,t),n.set(t,s);++h<c;){var y=s[h],w=t[h];if(r)var b=o?r(w,y,h,t,s,n):r(y,w,h,s,t,n);if(b!==void 0){if(b)continue;m=!1;break}if(S){if(!eP(t,function(R,N){if(!Hm(S,N)&&(y===R||i(y,R,e,r,n)))return S.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 rP(s){var t=-1,e=Array(s.size);return s.forEach(function(r,i){e[++t]=[i,r]}),e}function Pu(s){var t=-1,e=Array(s.size);return s.forEach(function(r){e[++t]=r}),e}var iP=1,nP=2,aP="[object Boolean]",oP="[object Date]",cP="[object Error]",dP="[object Map]",lP="[object Number]",uP="[object RegExp]",hP="[object Set]",pP="[object String]",mP="[object Symbol]",gP="[object ArrayBuffer]",fP="[object DataView]",jm=Cs?Cs.prototype:void 0,_u=jm?jm.valueOf:void 0;function SP(s,t,e,r,i,n,o){switch(e){case fP:if(s.byteLength!=t.byteLength||s.byteOffset!=t.byteOffset)return!1;s=s.buffer,t=t.buffer;case gP:return!(s.byteLength!=t.byteLength||!n(new od(s),new od(t)));case aP:case oP:case lP:return Ba(+s,+t);case cP:return s.name==t.name&&s.message==t.message;case uP:case pP:return s==t+"";case dP:var c=rP;case hP:var d=r&iP;if(c||(c=Pu),s.size!=t.size&&!d)return!1;var l=o.get(s);if(l)return l==t;r|=nP,o.set(s,t);var u=qm(c(s),c(t),r,i,n,o);return o.delete(s),u;case mP:if(_u)return _u.call(s)==_u.call(t)}return!1}var vP=1,TP=Object.prototype,yP=TP.hasOwnProperty;function EP(s,t,e,r,i,n){var o=e&vP,c=Tu(s),d=c.length,l=Tu(t),u=l.length;if(d!=u&&!o)return!1;for(var h=d;h--;){var m=c[h];if(!(o?m in t:yP.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 b=o;++h<d;){m=c[h];var R=s[m],N=t[m];if(r)var U=o?r(N,R,m,t,s,n):r(R,N,m,s,t,n);if(!(U===void 0?R===N||i(R,N,e,r,n):U)){w=!1;break}b||(b=m=="constructor")}if(w&&!b){var L=s.constructor,F=t.constructor;L!=F&&"constructor"in s&&"constructor"in t&&!(typeof L=="function"&&L instanceof L&&typeof F=="function"&&F instanceof F)&&(w=!1)}return n.delete(s),n.delete(t),w}var wP=1,Gm="[object Arguments]",Wm="[object Array]",cd="[object Object]",bP=Object.prototype,Jm=bP.hasOwnProperty;function PP(s,t,e,r,i,n){var o=Ot(s),c=Ot(t),d=o?Wm:Tn(s),l=c?Wm:Tn(t);d=d==Gm?cd:d,l=l==Gm?cd:l;var u=d==cd,h=l==cd,m=d==l;if(m&&fn(s)){if(!fn(t))return!1;o=!0,u=!1}if(m&&!u)return n||(n=new cs),o||sd(s)?qm(s,t,e,r,i,n):SP(s,t,d,e,r,i,n);if(!(e&wP)){var S=u&&Jm.call(s,"__wrapped__"),y=h&&Jm.call(t,"__wrapped__");if(S||y){var w=S?s.value():s,b=y?t.value():t;return n||(n=new cs),i(w,b,e,r,n)}}return m?(n||(n=new cs),EP(s,t,e,r,i,n)):!1}function dd(s,t,e,r,i){return s===t?!0:s==null||t==null||!ks(s)&&!ks(t)?s!==s&&t!==t:PP(s,t,e,r,dd,i)}var _P=1,CP=2;function kP(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 cs;if(r)var m=r(l,u,d,s,t,h);if(!(m===void 0?dd(u,l,_P|CP,r,h):m))return!1}}return!0}function Km(s){return s===s&&!Kt(s)}function RP(s){for(var t=rd(s),e=t.length;e--;){var r=t[e],i=s[r];t[e]=[r,i,Km(i)]}return t}function zm(s,t){return function(e){return e==null?!1:e[s]===t&&(t!==void 0||s in Object(e))}}function IP(s){var t=RP(s);return t.length==1&&t[0][2]?zm(t[0][0],t[0][1]):function(e){return e===s||kP(e,s,t)}}function AP(s,t){return s!=null&&t in Object(s)}function MP(s,t,e){t=gm(t,s);for(var r=-1,i=t.length,n=!1;++r<i;){var o=ad(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&&hu(i)&&lu(o,i)&&(Ot(s)||qa(s)))}function OP(s,t){return s!=null&&MP(s,t,AP)}var DP=1,NP=2;function VP(s,t){return gu(s)&&Km(t)?zm(ad(s),t):function(e){var r=iw(e,s);return r===void 0&&r===t?OP(e,s):dd(t,r,DP|NP)}}function LP(s){return function(t){return t==null?void 0:t[s]}}function xP(s){return function(t){return fm(t,s)}}function UP(s){return gu(s)?LP(ad(s)):xP(s)}function $P(s){return typeof s=="function"?s:s==null?au:typeof s=="object"?Ot(s)?VP(s[0],s[1]):IP(s):UP(s)}function BP(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 FP=BP();const HP=FP;var qP=function(){return os.Date.now()};const Cu=qP;var jP="Expected a function",GP=Math.max,WP=Math.min;function ku(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(jP);t=Zp(t)||0,Kt(e)&&(u=!!e.leading,h="maxWait"in e,n=h?GP(Zp(e.maxWait)||0,t):n,m="trailing"in e?!!e.trailing:m);function S(H){var ie=r,ut=i;return r=i=void 0,l=H,o=s.apply(ut,ie),o}function y(H){return l=H,c=setTimeout(R,t),u?S(H):o}function w(H){var ie=H-d,ut=H-l,Us=t-ie;return h?WP(Us,n-ut):Us}function b(H){var ie=H-d,ut=H-l;return d===void 0||ie>=t||ie<0||h&&ut>=n}function R(){var H=Cu();if(b(H))return N(H);c=setTimeout(R,w(H))}function N(H){return c=void 0,m&&r?S(H):(r=i=void 0,o)}function U(){c!==void 0&&clearTimeout(c),l=0,r=d=i=c=void 0}function L(){return c===void 0?o:N(Cu())}function F(){var H=Cu(),ie=b(H);if(r=arguments,i=this,d=H,ie){if(c===void 0)return y(d);if(h)return clearTimeout(c),c=setTimeout(R,t),S(d)}return c===void 0&&(c=setTimeout(R,t)),o}return F.cancel=U,F.flush=L,F}function Ru(s,t,e){(e!==void 0&&!Ba(s[t],e)||e===void 0&&!(t in s))&&uu(s,t,e)}function JP(s){return ks(s)&&Ha(s)}function Iu(s,t){if(!(t==="constructor"&&typeof s[t]=="function")&&t!="__proto__")return s[t]}function KP(s){return Fa(s,Ga(s))}function zP(s,t,e,r,i,n,o){var c=Iu(s,e),d=Iu(t,e),l=o.get(d);if(l){Ru(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&&fn(d),y=!m&&!S&&sd(d);u=d,m||S||y?Ot(c)?u=c:JP(c)?u=sm(c):S?(h=!1,u=bm(d,!0)):y?(h=!1,u=Vm(d,!0)):u=[]:uw(d)||qa(d)?(u=c,qa(c)?u=KP(c):(!Kt(c)||ou(c))&&(u=Lm(d))):h=!1}h&&(o.set(d,u),i(u,d,r,n,o),o.delete(d)),Ru(s,e,u)}function Ym(s,t,e,r,i){s!==t&&HP(t,function(n,o){if(i||(i=new cs),Kt(n))zP(s,t,o,e,Ym,r,i);else{var c=r?r(Iu(s,o),n,o+"",s,t,i):void 0;c===void 0&&(c=n),Ru(s,o,c)}},Ga)}function YP(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 QP="[object Map]",XP="[object Set]",ZP=Object.prototype,e_=ZP.hasOwnProperty;function t_(s){if(s==null)return!0;if(Ha(s)&&(Ot(s)||typeof s=="string"||typeof s.splice=="function"||fn(s)||sd(s)||qa(s)))return!s.length;var t=Tn(s);if(t==QP||t==XP)return!s.size;if(td(s))return!mm(s).length;for(var e in s)if(e_.call(s,e))return!1;return!0}function s_(s,t){return dd(s,t)}var r_=Cy(function(s,t,e){Ym(s,t,e)});const br=r_;var i_=1/0,n_=vn&&1/Pu(new vn([,-0]))[1]==i_?function(s){return new vn(s)}:sy;const a_=n_;var o_=200;function Qm(s,t,e){var r=-1,i=Sy,n=s.length,o=!0,c=[],d=c;if(e)o=!1,i=YP;else if(n>=o_){var l=t?null:a_(s);if(l)return Pu(l);o=!1,i=Hm,d=new za}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 c_(s){return s&&s.length?Qm(s):[]}function d_(s,t){return s&&s.length?Qm(s,$P(t)):[]}function ld(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 l_={audio:!0,video:!0,screenshareAudio:!0,screenshareVideo:!0},Xm={STAGING:"staging",PROD:"prod"},u_={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 yn(s,t){const e=s.getValue("overrides");return e&&e[t]?e[t]:!1}function h_({baseURI:s}){return s.includes("staging.realtime")?Xm.STAGING:Xm.PROD}function En({servicePrefix:s,baseURI:t}){return`${s}.${t}`}function p_(s){const t=s.getValue("baseURI");return{location:En({servicePrefix:"location",baseURI:t}),locationLegacy:En({servicePrefix:"location-legacy",baseURI:t}),daCollector:En({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>',g_='<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>',ud=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})},li={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"}},f_=/\b(?:1[7-9](?:\.\d+)?|[2-9]\d(?:\.\d+)?|[1-9]\d{2,}(?:\.\d+)?)\b/,Zm="__rtk_plugins__",S_=[Zm];function eg(s){var r,i,n;const t=typeof navigator!="undefined"&&!navigator.isReactNative&&typeof window!="undefined"&&((r=window.location.host)==null?void 0:r.includes(li.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 tg(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"?tg(s[r],i,e):["number","string","boolean"].includes(typeof s[r])&&(e[i]=s[r])}),e}function sg(s,t,e={},r=""){const i={};try{const n=JSON.stringify(e),o=JSON.parse(n),c=tg(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 eg(s)&&console.error(u,{log:e,flattened:d}),new Error(u)}return JSON.parse(d)}catch(n){const o=ld(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=Pr.getContext(this.meetingMetadata.peerId);return`https://${En({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():ge.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=mn().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:ld(r.error)});const n=Pr.getContext(this.meetingMetadata.peerId);if(eg(n)&&(t_(r)?console[t]("InternalLogs:: ",t,e):console[t]("InternalLogs:: ",t,e,r)),!!v_(n,t))try{const c=sg(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:ld(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=Pr.getContext(this.meetingMetadata.peerId),o=JSON.stringify({meetingMetadata:sg(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:ld(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 T_(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 y_{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 dT;this.contexts.set(t,T_(e)),this.contexts.get(t).setValue("peerSessionStore",new lT(i));const n=new Gp;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 Pr=new y_,E_={"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"},hd={"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","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(hd).forEach(s=>{hd[s]=`{${E_[s.slice(0,2)]}} ${hd[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?hd[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=Pr.getContext(Pr.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 pd(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 rg(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){pd(this,t,e,o)}}),n&&(s.set=function(o){try{return n.apply(this,[o])}catch(c){pd(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=>{pd(this,t,e,o)}):n}catch(n){pd(this,t,e,n)}},s}function w_(s,t){return(e,r,i)=>{if(i)return rg(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,rg(o,s,t))}}}const nt=s=>w_(Error,s);var qs=(s=>(s.GroupCall="GROUP_CALL",s.Webinar="WEBINAR",s.AudioRoom="AUDIO_ROOM",s.Livestream="LIVESTREAM",s.Chat="CHAT",s))(qs||{}),q=(s=>(s.Allowed="ALLOWED",s.NotAllowed="NOT_ALLOWED",s.CanRequest="CAN_REQUEST",s))(q||{});typeof process!="undefined"&&(vS=process==null?void 0:process.env)!=null&&vS.FLAGSMITH_ENVIRONMENT_KEY&&process.env.FLAGSMITH_ENVIRONMENT_KEY;var ig=[-2,-1,0,1,2],b_=[0,1,2,3,4];function P_(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 __=(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)]},C_=(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]},k_=(s,t,e)=>{const r=i=>i.toString(16).padStart(2,"0");return`#${r(s)}${r(t)}${r(e)}`},ng=(s,t=ig,e=.4)=>{const r=[],[i,n,o]=P_(s),[c,d,l]=C_(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(b=>b===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 b of t){let R;b<0?R=u+b*w*e:b>0?R=u+b*y*e:R=u;const[N,U,L]=__(c,d,R/100);r.push(k_(N,U,L))}return r},ag={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"}},R_=s=>{const[t,e,r,i,n]=ng(s,ig);return{300:t,400:e,500:r,600:i,700:n}},I_=s=>{if(s==="#FFFFFF")return ag.light.background;if(s==="#000000")return ag.dark.background;const[t,e,r,i,n]=ng(s,b_);return{1e3:t,900:e,800:r,700:i,600:n}},A_={border_radius:"rounded",border_width:"thin",spacing_base:4,theme:"dark",colors:{brand:R_("#2160FD"),background:I_("#141414"),danger:"#FF2D2D",text:"#EEEEEE",text_on_brand:"#EEEEEE",success:"#62A504",video_bg:"#191919",warning:"#FFCD07"}};function og(){return bu(A_)}var M_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED",can_consume:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED",can_consume:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1},channel:{can_create:"ALL",can_delete:"ALL",can_update:"ALL",can_read_all:!1},message:{can_delete:"ALL",can_edit:"ALL",delete_cutoff_time_seconds:0,edit_cutoff_time_seconds:0}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{oldTheme:{setup_screen:{is_enabled:!1},alone_here:{is_enabled:!1},waiting_room:{is_enabled:!1,enable_preview:!0},control_bar:{is_enabled:!0,elements:{plugins:!0,screenshare:!0,invite:!1,participants:!0,chat:!0,reactions:!1,polls:!0,fullscreen:!0,layout:!0}},header:{is_enabled:!0,elements:{timer:!0,title:!0,participant_count:!0,change_layout:!0}},pip_mode:!0,auto_tune:!0,colors:{primary:"#2160FD",secondary:"#1A1A1A",text:"#EEEEEE",background:"#1A1A1A",textPrimary:"#EEEEEE",videoBackground:"#1A1A1A"},dimensions:{mode:"fillParent"},grid:{multi:{maxVideoCount:6,videoFit:"cover"},single:{maxVideoCount:6,videoFit:"cover"},defaultView:"MULTI"},controls:{pip_toggle:!1},plugins:[]},design_tokens:og(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate: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 O_(){return bu(M_)}var D_={permissions:{can_accept_production_requests:!1,can_edit_display_name:!0,accept_waiting_requests:!1,disable_participant_audio:!1,disable_participant_screensharing:!1,disable_participant_video:!1,can_spotlight:!1,kick_participant:!1,pin_participant:!1,can_record:!1,can_livestream:!1,waiting_room_type:"SKIP",plugins:{can_close:!0,can_start:!0,can_edit_config:!1,config:{}},polls:{can_create:!0,can_vote:!0,can_view:!0},media:{video:{can_produce:"ALLOWED"},audio:{can_produce:"ALLOWED"},screenshare:{can_produce:"ALLOWED"}},chat:{public:{can_send:!0,text:!0,files:!0},private:{can_send:!1,can_receive:!1,text:!1,files:!1}},hidden_participant:!1,is_recorder:!1,recorder_type:"NONE",show_participant_list:!0,transcription_enabled:!1,can_change_participant_permissions:!1,connected_meetings:{can_alter_connected_meetings:!1,can_switch_connected_meetings:!1,can_switch_to_parent_meeting:!1},stage_enabled:!1,stage_access:void 0,accept_stage_requests:!1},ui:{design_tokens:og(),config_diff:{}},config:{view_type:"GROUP_CALL",media:{audio:{enable_stereo:!1,enable_high_bitrate:!1},video:{quality:"vga",frame_rate: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 Au(){return bu(D_)}function N_(){ge.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 _=(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))(_||{});class wn extends it.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 it.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 V_(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 cg=1080,dg=1920,L_=(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,b,R=1;return h<e&&(R=e/h),Math.abs(R-1)<1e-14&&m<r&&(R=r/m),h*=R,m*=R,w=d/(h/e),b=l/(m/r),S=(d-w)*o,y=(l-b)*c,S<0&&(S=0),y<0&&(y=0),w>d&&(w=d),b>l&&(b=l),[S,y,w,b,s,t,e,r]},xh=class extends Dt{constructor(e,r,i,n){const o=e.getValue("logger");super(o);g(this,Yt,void 0);g(this,bi,void 0);g(this,ot,void 0);g(this,Qt,void 0);g(this,Me,{height:cg,width:dg});g(this,gs,{brand:"#2160FD",background:"#141414",text:"#000000",videoBackground:"#191919",textOnBrand:"#EEEEEE"});g(this,nr,void 0);g(this,ft,{});g(this,xe,void 0);g(this,Vn,void 0);g(this,Ln,void 0);g(this,ar,void 0);g(this,xn,!1);p(this,"cleanupEventListeners",()=>{a(this,bi).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,bi).getValue("peerSessionStore").emit(_.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,ar)==="active"){this.disable(!0);return}a(this,ft)!==void 0&&this.paintCanvas(),a(this,nr)!==void 0&&f(this,nr,requestAnimationFrame(()=>this.animate()))});p(this,"disable",(e=!1)=>{f(this,ar,"idle"),this.cleanupEventListeners(),cancelAnimationFrame(a(this,nr)),e!==!0&&document.body.removeChild(a(this,ot)),f(this,nr,void 0),document.pictureInPictureElement&&document.exitPictureInPicture()});f(this,bi,e),f(this,ar,"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 ud(m_),n=await ud(g_)}catch(o){}return new xh(e,r,i,n)}async setupIcon(e,r){switch(e){case"handRaise":f(this,Ln,r);break;case"pin":f(this,Vn,r);break}}async overrideIcon(e,r){switch(e){case"handRaise":f(this,Ln,await ud(r));break;case"pin":f(this,Vn,await ud(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,ot,document.createElement("div")),a(this,ot).style.width="0.1px",a(this,ot).style.height="0.1px",a(this,ot).style.overflow="hidden",a(this,ot).style.position="absolute",a(this,ot).style.bottom="0",a(this,ot).style.right="0",a(this,ot).style.opacity="0",a(this,ot).appendChild(a(this,Qt))}setupEventListeners(){a(this,bi).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,Me).height,e.width=a(this,Me).width,f(this,Yt,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,Yt)===void 0)return;const o=a(this,Yt).getContext("2d"),c=a(this,Yt).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,b=S*(h+d)+d,{displayText:R,image:N}=n!=null?n:{};o.fillStyle=R||N?a(this,gs).videoBackground:a(this,gs).background,o.strokeStyle=a(this,gs).brand,o.beginPath(),o.moveTo(w+l,b),o.arcTo(w+u,b,w+u,b+l,l),o.arcTo(w+u,b+h,w+u-l,b+h,l),o.arcTo(w,b+h,w,b+h-l,l),o.arcTo(w,b,w+l,b,l),o.closePath(),o.fill(),o.stroke();const U=u/6,L=u/2+w,F=h/2+b;o.save(),(R||N)&&(o.beginPath(),o.arc(L,F,U,0,Math.PI*2),o.fillStyle=a(this,gs).brand,o.fill(),N?(o.clip(),o.drawImage(N,L-U,F-U,U*2,U*2),o.restore()):R&&(o.fillStyle=a(this,gs).textOnBrand,o.font=`${U/2}px sans-serif`,o.textAlign="center",o.textBaseline="middle",o.fillText(R,L,F)),this.drawIcons(n,w,b,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,Yt).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,Vn)),e.handRaised&&h(a(this,Ln)),e.reaction&&h(e.reaction)}drawTile(e,r,i){var l,u;if(a(this,Yt)===void 0)return;const n=a(this,Yt).getContext("2d"),o=this.getSources();let c=0,d=0;for(;c<a(this,Me).height-5;){let h=0;for(;h<a(this,Me).width-5&&d<i;){if((l=o[d])!=null&&l.enabled){const m=o[d].element,[S,y,w,b,R,N,U,L]=L_(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,b,-1*R,N,-1*U,L),n.restore()):n.drawImage(m,S,y,w,b,R,N,U,L),this.drawIcons(o[d],R,N,Math.max(U,L))}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,Me).width,a(this,Me).height];case 2:return[Math.floor(a(this,Me).width/2),a(this,Me).height];case 3:case 4:return[Math.floor(a(this,Me).width/2),Math.floor(a(this,Me).height/2)];case 5:case 6:return[Math.floor(a(this,Me).width/3),Math.floor(a(this,Me).height/2)];case 7:case 8:case 9:return[Math.floor(a(this,Me).width/3),Math.floor(a(this,Me).height/3)];default:return[Math.floor(a(this,Me).width/3),Math.floor(a(this,Me).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,xn,!1),this.isSupported()&&document.exitPictureInPicture!==void 0&&document.pictureInPictureElement!==null&&document.exitPictureInPicture(),a(this,ot))try{document.body.removeChild(a(this,ot))}catch(e){}this.removeAllSources(),f(this,Yt,void 0),f(this,Qt,void 0),f(this,nr,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,xn))return;f(this,xn,!0),this.createCanvas(),this.setupMediaSessionEvents();const i=document.createElement("video");f(this,Me,{height:e!=null?e:cg,width:r!=null?r:dg}),i.height=a(this,Me).height,i.width=a(this,Me).width,i.autoplay=!0,i.muted=!0,i.srcObject=a(this,Yt).captureStream(24),f(this,Qt,i),a(this,Qt).onloadedmetadata=()=>{try{this.emit("pipStarted"),a(this,Qt).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?V_(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,ar,"activating"),this.setupEventListeners(),this.updateMediaSession("CAMERA",a(this,xe).videoEnabled),this.updateMediaSession("MIC",a(this,xe).audioEnabled),document.body.appendChild(a(this,ot)),f(this,nr,requestAnimationFrame(()=>this.animate())),a(this,Qt).onloadedmetadata=()=>{a(this,Qt).requestPictureInPicture().then(()=>{f(this,ar,"active")})},a(this,Qt).readyState===4&&a(this,Qt).requestPictureInPicture().then(()=>{f(this,ar,"active")})}};let Mu=xh;Yt=new WeakMap,bi=new WeakMap,ot=new WeakMap,Qt=new WeakMap,Me=new WeakMap,gs=new WeakMap,nr=new WeakMap,ft=new WeakMap,xe=new WeakMap,Vn=new WeakMap,Ln=new WeakMap,ar=new WeakMap,xn=new WeakMap;function Ou(s){let t=typeof s;if(t=="object"){if(Array.isArray(s))return"array";if(s===null)return"null"}return t}function x_(s){return s!==null&&typeof s=="object"&&!Array.isArray(s)}let js="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),md=[];for(let s=0;s<js.length;s++)md[js[s].charCodeAt(0)]=s;md["-".charCodeAt(0)]=js.indexOf("+"),md["_".charCodeAt(0)]=js.indexOf("/");function U_(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=md[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 $_(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 gd;(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])})(gd||(gd={}));var Ve;(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"})(Ve||(Ve={}));function B_(){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 Du(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 fd=(1<<16)*(1<<16);function lg(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>=fd&&(i=i+(r/fd|0),r=r%fd)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function Nu(s,t){if(t>>>0<=2097151)return""+(fd*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 ug(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 F_(){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 de;function H_(){const s=new DataView(new ArrayBuffer(8));de=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}H_();function hg(s){if(!s)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}const pg=/^-?[0-9]+$/,Sd=4294967296,vd=2147483648;class mg{constructor(t,e){this.lo=t|0,this.hi=e|0}isZero(){return this.lo==0&&this.hi==0}toNumber(){let t=this.hi*Sd+(this.lo>>>0);if(!Number.isSafeInteger(t))throw new Error("cannot convert to safe number");return t}}class at extends mg{static from(t){if(de)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=de.C(t);case"number":if(t===0)return this.ZERO;t=de.C(t);case"bigint":if(!t)return this.ZERO;if(t<de.UMIN)throw new Error("signed value for ulong");if(t>de.UMAX)throw new Error("ulong too large");return de.V.setBigUint64(0,t,!0),new at(de.V.getInt32(0,!0),de.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!pg.test(t))throw new Error("string is no integer");let[e,r,i]=lg(t);if(e)throw new Error("signed value for ulong");return new at(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 at(t,t/Sd)}throw new Error("unknown value "+typeof t)}toString(){return de?this.toBigInt().toString():Nu(this.lo,this.hi)}toBigInt(){return hg(de),de.V.setInt32(0,this.lo,!0),de.V.setInt32(4,this.hi,!0),de.V.getBigUint64(0,!0)}}at.ZERO=new at(0,0);class he extends mg{static from(t){if(de)switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=="")throw new Error("string is no integer");t=de.C(t);case"number":if(t===0)return this.ZERO;t=de.C(t);case"bigint":if(!t)return this.ZERO;if(t<de.MIN)throw new Error("signed long too small");if(t>de.MAX)throw new Error("signed long too large");return de.V.setBigInt64(0,t,!0),new he(de.V.getInt32(0,!0),de.V.getInt32(4,!0))}else switch(typeof t){case"string":if(t=="0")return this.ZERO;if(t=t.trim(),!pg.test(t))throw new Error("string is no integer");let[e,r,i]=lg(t);if(e){if(i>vd||i==vd&&r!=0)throw new Error("signed long too small")}else if(i>=vd)throw new Error("signed long too large");let n=new he(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 he(t,t/Sd):new he(-t,-t/Sd).negate()}throw new Error("unknown value "+typeof t)}isNegative(){return(this.hi&vd)!==0}negate(){let t=~this.hi,e=this.lo;return e?e=~e+1:t+=1,new he(e,t)}toString(){if(de)return this.toBigInt().toString();if(this.isNegative()){let t=this.negate();return"-"+Nu(t.lo,t.hi)}return Nu(this.lo,this.hi)}toBigInt(){return hg(de),de.V.setInt32(0,this.lo,!0),de.V.setInt32(4,this.hi,!0),de.V.getBigInt64(0,!0)}}he.ZERO=new he(0,0);const gg={readUnknownField:!0,readerFactory:s=>new j_(s)};function q_(s){return s?Object.assign(Object.assign({},gg),s):gg}class j_{constructor(t,e){this.varint64=B_,this.uint32=F_,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 Ve.Varint:for(;this.buf[this.pos++]&128;);break;case Ve.Bit64:this.pos+=4;case Ve.Bit32:this.pos+=4;break;case Ve.LengthDelimited:let r=this.uint32();this.pos+=r;break;case Ve.StartGroup:let i;for(;(i=this.tag()[1])!==Ve.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 he(...this.varint64())}uint64(){return new at(...this.varint64())}sint64(){let[t,e]=this.varint64(),r=-(t&1);return t=(t>>>1|(e&1)<<31)^r,e=e>>>1^r,new he(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 at(this.sfixed32(),this.sfixed32())}sfixed64(){return new he(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 ee(s,t){if(!s)throw new Error(t)}const G_=34028234663852886e22,W_=-34028234663852886e22,J_=4294967295,K_=2147483647,z_=-2147483648;function Ya(s){if(typeof s!="number")throw new Error("invalid int 32: "+typeof s);if(!Number.isInteger(s)||s>K_||s<z_)throw new Error("invalid int 32: "+s)}function Td(s){if(typeof s!="number")throw new Error("invalid uint 32: "+typeof s);if(!Number.isInteger(s)||s>J_||s<0)throw new Error("invalid uint 32: "+s)}function Vu(s){if(typeof s!="number")throw new Error("invalid float 32: "+typeof s);if(Number.isFinite(s)&&(s>G_||s<W_))throw new Error("invalid float 32: "+s)}const fg={writeUnknownFields:!0,writerFactory:()=>new Q_};function Y_(s){return s?Object.assign(Object.assign({},fg),s):fg}class Q_{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(Td(t);t>127;)this.buf.push(t&127|128),t=t>>>7;return this.buf.push(t),this}int32(t){return Ya(t),ug(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){Vu(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){Td(t);let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!0),this.raw(e)}sfixed32(t){Ya(t);let e=new Uint8Array(4);return new DataView(e.buffer).setInt32(0,t,!0),this.raw(e)}sint32(t){return Ya(t),t=(t<<1^t>>31)>>>0,ug(t,this.buf),this}sfixed64(t){let e=new Uint8Array(8),r=new DataView(e.buffer),i=he.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=at.from(t);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(e)}int64(t){let e=he.from(t);return Du(e.lo,e.hi,this.buf),this}sint64(t){let e=he.from(t),r=e.hi>>31,i=e.lo<<1^r,n=(e.hi<<1|e.lo>>>31)^r;return Du(i,n,this.buf),this}uint64(t){let e=at.from(t);return Du(e.lo,e.hi,this.buf),this}}const Sg={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},vg={ignoreUnknownFields:!1};function X_(s){return s?Object.assign(Object.assign({},vg),s):vg}function Z_(s){return s?Object.assign(Object.assign({},Sg),s):Sg}const Tg=Symbol.for("protobuf-ts/message-type");function yg(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 A;(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"})(A||(A={}));var Rs;(function(s){s[s.BIGINT=0]="BIGINT",s[s.STRING=1]="STRING",s[s.NUMBER=2]="NUMBER"})(Rs||(Rs={}));var yd;(function(s){s[s.NO=0]="NO",s[s.PACKED=1]="PACKED",s[s.UNPACKED=2]="UNPACKED"})(yd||(yd={}));function eC(s){var t,e,r,i;return s.localName=(t=s.localName)!==null&&t!==void 0?t:yg(s.name),s.jsonName=(e=s.jsonName)!==null&&e!==void 0?e:yg(s.name),s.repeat=(r=s.repeat)!==null&&r!==void 0?r:yd.NO,s.opt=(i=s.opt)!==null&&i!==void 0?i:s.repeat||s.oneof?!1:s.kind=="message",s}function tC(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 sC{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(!tC(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,A.INT32,i):this.scalar(t,A.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),A.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 A.UINT64:case A.FIXED64:case A.INT64:case A.SFIXED64:case A.SINT64:switch(r){case Rs.BIGINT:return i=="bigint";case Rs.NUMBER:return i=="number"&&!isNaN(t);default:return i=="string"}case A.BOOL:return i=="boolean";case A.STRING:return i=="string";case A.BYTES:return t instanceof Uint8Array;case A.DOUBLE:case A.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 A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.UINT32:return this.scalars(i.slice(0,r).map(n=>parseInt(n)),e,r);case A.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 ds(s,t){switch(t){case Rs.BIGINT:return s.toBigInt();case Rs.NUMBER:return s.toNumber();default:return s.toString()}}class rC{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=Ou(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(x_(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==A.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"&&ee(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 ee(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:(ee(typeof o=="number",`Unable to parse field ${this.info.typeName}#${r}, enum ${t[0]} has no value for "${e}".`),o)}ee(!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 A.DOUBLE:case A.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==A.FLOAT&&Vu(o),o;case A.INT32:case A.FIXED32:case A.SFIXED32:case A.SINT32:case A.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==A.UINT32?Td(c):Ya(c),c;case A.INT64:case A.SFIXED64:case A.SINT64:if(t===null)return ds(he.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ds(he.from(t),r);case A.FIXED64:case A.UINT64:if(t===null)return ds(at.ZERO,r);if(typeof t!="number"&&typeof t!="string")break;return ds(at.from(t),r);case A.BOOL:if(t===null)return!1;if(typeof t!="boolean")break;return t;case A.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 A.BYTES:if(t===null||t==="")return new Uint8Array(0);if(typeof t!="string")break;return U_(t)}}catch(o){n=o.message}this.assert(!1,i+(n?" - "+n:""),t)}}class iC{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);ee(d!==void 0),r[e.useProtoFieldName?n.name:n.jsonName]=d}return r}field(t,e,r){let i;if(t.kind=="map"){ee(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);ee(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);ee(u!==void 0),n[d.toString()]=u}break;case"enum":const c=t.V.T();for(const[d,l]of Object.entries(e)){ee(l===void 0||typeof l=="number");const u=this.enum(c,l,t.name,!1,!0,r.enumAsInteger);ee(u!==void 0),n[d.toString()]=u}break}(r.emitDefaultValues||Object.keys(n).length>0)&&(i=n)}else if(t.repeat){ee(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);ee(l!==void 0),n.push(l)}break;case"enum":const o=t.T();for(let d=0;d<e.length;d++){ee(e[d]===void 0||typeof e[d]=="number");const l=this.enum(o,e[d],t.name,t.opt,!0,r.enumAsInteger);ee(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);ee(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){ee(i);return}if(!(e===0&&!n&&!i))return ee(typeof e=="number"),ee(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){ee(i);return}const o=n||i;switch(t){case A.INT32:case A.SFIXED32:case A.SINT32:return e===0?o?0:void 0:(Ya(e),e);case A.FIXED32:case A.UINT32:return e===0?o?0:void 0:(Td(e),e);case A.FLOAT:Vu(e);case A.DOUBLE:return e===0?o?0:void 0:(ee(typeof e=="number"),Number.isNaN(e)?"NaN":e===Number.POSITIVE_INFINITY?"Infinity":e===Number.NEGATIVE_INFINITY?"-Infinity":e);case A.STRING:return e===""?o?"":void 0:(ee(typeof e=="string"),e);case A.BOOL:return e===!1?o?!1:void 0:(ee(typeof e=="boolean"),e);case A.UINT64:case A.FIXED64:ee(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let c=at.from(e);return c.isZero()&&!o?void 0:c.toString();case A.INT64:case A.SFIXED64:case A.SINT64:ee(typeof e=="number"||typeof e=="string"||typeof e=="bigint");let d=he.from(e);return d.isZero()&&!o?void 0:d.toString();case A.BYTES:return ee(e instanceof Uint8Array),e.byteLength?$_(e):o?"":void 0}}}function Lu(s,t=Rs.STRING){switch(s){case A.BOOL:return!1;case A.UINT64:case A.FIXED64:return ds(at.ZERO,t);case A.INT64:case A.SFIXED64:case A.SINT64:return ds(he.ZERO,t);case A.DOUBLE:case A.FLOAT:return 0;case A.BYTES:return new Uint8Array(0);case A.STRING:return"";default:return 0}}class nC{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?gd.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"?A.INT32:d.T,S=d.kind=="scalar"?d.L:void 0;if(u){let b=l[h];if(c==Ve.LengthDelimited&&m!=A.STRING&&m!=A.BYTES){let R=t.uint32()+t.pos;for(;t.pos<R;)b.push(this.scalar(t,m,S))}else b.push(this.scalar(t,m,S))}else l[h]=this.scalar(t,m,S);break;case"message":if(u){let b=l[h],R=d.T().internalBinaryRead(t,t.uint32(),r);b.push(R)}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==A.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=Lu(t.K);o=t.K==A.BOOL?d.toString():d}if(c===void 0)switch(t.V.kind){case"scalar":c=Lu(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 A.INT32:return t.int32();case A.STRING:return t.string();case A.BOOL:return t.bool();case A.DOUBLE:return t.double();case A.FLOAT:return t.float();case A.INT64:return ds(t.int64(),r);case A.UINT64:return ds(t.uint64(),r);case A.FIXED64:return ds(t.fixed64(),r);case A.FIXED32:return t.fixed32();case A.BYTES:return t.bytes();case A.UINT32:return t.uint32();case A.SFIXED32:return t.sfixed32();case A.SFIXED64:return ds(t.sfixed64(),r);case A.SINT32:return t.sint32();case A.SINT64:return ds(t.sint64(),r)}}}class aC{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"?A.INT32:n.T;if(d)if(ee(Array.isArray(o)),d==yd.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?ee(n.opt):this.scalar(e,u,n.no,o,c||n.opt);break;case"message":if(d){ee(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":ee(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?gd.onWrite:i)(this.info.typeName,t,e)}mapEntry(t,e,r,i,n){t.tag(r.no,Ve.LengthDelimited),t.fork();let o=i;switch(r.K){case A.INT32:case A.FIXED32:case A.UINT32:case A.SFIXED32:case A.SINT32:o=Number.parseInt(i);break;case A.BOOL:ee(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,A.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,Ve.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;ee(e!==A.BYTES&&e!==A.STRING),t.tag(r,Ve.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=Ve.Varint,i,n=e===void 0,o=e===0;switch(t){case A.INT32:i="int32";break;case A.STRING:o=n||!e.length,r=Ve.LengthDelimited,i="string";break;case A.BOOL:o=e===!1,i="bool";break;case A.UINT32:i="uint32";break;case A.DOUBLE:r=Ve.Bit64,i="double";break;case A.FLOAT:r=Ve.Bit32,i="float";break;case A.INT64:o=n||he.from(e).isZero(),i="int64";break;case A.UINT64:o=n||at.from(e).isZero(),i="uint64";break;case A.FIXED64:o=n||at.from(e).isZero(),r=Ve.Bit64,i="fixed64";break;case A.BYTES:o=n||!e.byteLength,r=Ve.LengthDelimited,i="bytes";break;case A.FIXED32:r=Ve.Bit32,i="fixed32";break;case A.SFIXED32:r=Ve.Bit32,i="sfixed32";break;case A.SFIXED64:o=n||he.from(e).isZero(),r=Ve.Bit64,i="sfixed64";break;case A.SINT32:i="sint32";break;case A.SINT64:o=n||he.from(e).isZero(),i="sint64";break}return[r,i,n||o]}}function oC(s){const t=s.messagePrototype?Object.create(s.messagePrototype):Object.defineProperty({},Tg,{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]=Lu(e.T,e.L);break;case"enum":t[r]=0;break;case"map":t[r]={};break}}return t}function xu(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 cC(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"?A.INT32:r.T;if(!(r.repeat?wg(c,n,o):Eg(c,n,o)))return!1;break;case"map":if(!(r.V.kind=="message"?bg(r.V.T(),Ed(n),Ed(o)):wg(r.V.kind=="enum"?A.INT32:r.V.T,Ed(n),Ed(o))))return!1;break;case"message":let d=r.T();if(!(r.repeat?bg(d,n,o):d.equals(n,o)))return!1;break}}return!0}const Ed=Object.values;function Eg(s,t,e){if(t===e)return!0;if(s!==A.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 wg(s,t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(!Eg(s,t[r],e[r]))return!1;return!0}function bg(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 dC=Object.getOwnPropertyDescriptors(Object.getPrototypeOf({}));class v{constructor(t,e,r){this.defaultCheckDepth=16,this.typeName=t,this.fields=e.map(eC),this.options=r!=null?r:{},this.messagePrototype=Object.create(null,Object.assign(Object.assign({},dC),{[Tg]:{value:this}})),this.refTypeCheck=new sC(this),this.refJsonReader=new rC(this),this.refJsonWriter=new iC(this),this.refBinReader=new nC(this),this.refBinWriter=new aC(this)}create(t){let e=oC(this);return t!==void 0&&xu(this,e,t),e}clone(t){let e=this.create();return xu(this,e,t),e}equals(t,e){return cC(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){xu(this,t,e)}fromBinary(t,e){let r=q_(e);return this.internalBinaryRead(r.readerFactory(t),t.byteLength,r)}fromJson(t,e){return this.internalJsonRead(t,X_(e))}fromJsonString(t,e){let r=JSON.parse(t);return this.fromJson(r,e)}toJson(t,e){return this.internalJsonWrite(t,Z_(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=Y_(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 ${Ou(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 Gs;(function(s){s[s.PUBLISHER=0]="PUBLISHER",s[s.SUBSCRIBER=1]="SUBSCRIBER"})(Gs||(Gs={}));var Ws;(function(s){s[s.AUDIO=0]="AUDIO",s[s.VIDEO=1]="VIDEO"})(Ws||(Ws={}));class lC 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 Pg=new lC;class uC 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 hC=new uC;class pC extends v{constructor(){super("media.Fingerprint",[{no:1,name:"algorithm",kind:"scalar",T:9},{no:2,name:"value",kind:"scalar",T:9}])}}new pC;class mC extends v{constructor(){super("media.SessionDescription",[{no:1,name:"target",kind:"enum",T:()=>["media.Target",Gs]},{no:2,name:"type",kind:"scalar",T:9},{no:3,name:"sdp",kind:"scalar",T:9}])}}const ls=new mC;class gC 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 fC=new gC;class SC 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:()=>ls},{no:4,name:"private_ice",kind:"scalar",opt:!0,T:8},{no:5,name:"producers",kind:"message",repeat:1,T:()=>fC}])}}const vC=new SC;class TC 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 yC=new TC;class EC extends v{constructor(){super("media.CreateTransportResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls},{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 EC;class wC extends v{constructor(){super("media.RenegotiateRequest",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls}])}}const bC=new wC;class PC extends v{constructor(){super("media.RenegotiateResponse",[{no:1,name:"transport_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls}])}}new PC;class _C 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 CC=new _C;class kC 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 RC=new kC;class IC 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 IC;class AC 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 AC;class MC extends v{constructor(){super("media.ProducerState",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"kind",kind:"enum",T:()=>["media.ProducerKind",Ws]},{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:()=>Pg}])}}const Qa=new MC;class OC extends v{constructor(){super("media.ConsumerState",[{no:1,name:"consumer_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Qa},{no:3,name:"producer_track",kind:"message",T:()=>RC},{no:4,name:"error_code",kind:"scalar",opt:!0,T:9}])}}const DC=new OC;class NC extends v{constructor(){super("media.ProducerIdToConsumerMap",[{no:1,name:"map",kind:"map",K:9,V:{kind:"message",T:()=>DC}}])}}const Cg=new NC;class VC extends v{constructor(){super("media.PeerRtpCapabilitites",[{no:1,name:"sender",kind:"message",T:()=>Ig},{no:2,name:"receiver",kind:"message",T:()=>Ig}])}}const kg=new VC;class LC extends v{constructor(){super("media.RtpCapability",[{no:1,name:"codecs",kind:"message",repeat:1,T:()=>Pg},{no:2,name:"header_extensions",kind:"message",repeat:1,T:()=>hC}])}}const Rg=new LC;class xC extends v{constructor(){super("media.RtpCapabilitites",[{no:1,name:"audio",kind:"message",T:()=>Rg},{no:2,name:"video",kind:"message",T:()=>Rg}])}}const Ig=new xC;class UC 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 $C=new UC;class BC 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 Ag=new BC;class FC 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 HC=new FC;class qC 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:()=>HC},{no:9,name:"capabilities",kind:"message",T:()=>kg}])}}const jC=new qC;class GC extends v{constructor(){super("media.edge.PeerJoinCompleteRequest",[])}}const WC=new GC;class JC extends v{constructor(){super("media.edge.PeerLeaveRequest",[{no:1,name:"close_room",kind:"scalar",T:8}])}}const KC=new JC;class zC 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 zC;class YC 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:()=>$C},{no:5,name:"producing_transport_id",kind:"scalar",opt:!0,T:9},{no:6,name:"simulcast",kind:"message",T:()=>Ag}])}}const QC=new YC;class XC extends v{constructor(){super("media.edge.ConsumePeersRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>QC},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const ZC=new XC;class ek extends v{constructor(){super("media.edge.UpdateConsumerSimulcastConfigRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"simulcast",kind:"message",T:()=>Ag},{no:3,name:"producing_transport_id",kind:"scalar",T:9},{no:4,name:"mid",kind:"scalar",T:9}])}}const tk=new ek;class sk extends v{constructor(){super("media.edge.UpdateConsumersSimulcastConfigRequest",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>tk},{no:2,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const rk=new sk;class ik 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:()=>ls},{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 nk=new ik;class ak extends v{constructor(){super("media.edge.SelectedPeersRequest",[])}}new ak;class ok extends v{constructor(){super("media.edge.GlobalPeerPinningRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const ck=new ok;class dk 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 wd=new dk;class lk 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 lk;class uk extends v{constructor(){super("media.edge.ProducerCloseRequest",[{no:1,name:"producer_id",kind:"scalar",T:9},{no:2,name:"description",kind:"message",T:()=>ls},{no:3,name:"producing_transport_id",kind:"scalar",opt:!0,T:9}])}}const hk=new uk;class pk 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:()=>ls},{no:3,name:"consuming_transport_id",kind:"scalar",opt:!0,T:9}])}}const mk=new pk;class gk extends v{constructor(){super("media.edge.KickPeerRequest",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new gk;class fk extends v{constructor(){super("media.edge.KickAllPeersRequest",[{no:1,name:"propagate_kick_across_rooms",kind:"scalar",T:8}])}}const Mg=new fk;class Sk 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 vk=new Sk;class Tk 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 yk=new Tk;class Ek 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 wk=new Ek;class bk 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 Pk=new bk;class _k 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 Ck=new _k;class kk extends v{constructor(){super("media.edge.EmptyResponse",[])}}new kk;class Rk 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:()=>Qa},{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:()=>kg}])}}const Og=new Rk;class Ik 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 Uu=new Ik;class Ak 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 Mk=new Ak;class Ok extends v{constructor(){super("media.edge.SelectedPeersDiffResponse",[{no:1,name:"entries",kind:"message",repeat:1,T:()=>Mk}])}}const Dg=new Ok;class Dk extends v{constructor(){super("media.edge.PeerJoinResponse",[])}}new Dk;class Nk extends v{constructor(){super("media.edge.PeerJoinCompleteResponse",[{no:1,name:"room_state",kind:"message",T:()=>Pk},{no:2,name:"participants",kind:"message",repeat:1,T:()=>Og},{no:3,name:"selected_peers",kind:"message",T:()=>Uu},{no:4,name:"max_preferred_streams",kind:"scalar",T:5}])}}const $u=new Nk;class Vk extends v{constructor(){super("media.edge.PeerLeaveResponse",[{no:1,name:"closed",kind:"scalar",T:8}])}}const Lk=new Vk;class xk extends v{constructor(){super("media.edge.ConsumeMultipleProducerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Cg}])}}new xk;class Uk extends v{constructor(){super("media.edge.ConsumePeerResponse",[{no:1,name:"status",kind:"scalar",T:8},{no:2,name:"consumer_ids_map",kind:"message",T:()=>Cg},{no:3,name:"description",kind:"message",T:()=>ls}])}}const $k=new Uk;class Bk 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:()=>ls}])}}const Fk=new Bk;class Hk extends v{constructor(){super("media.edge.ProducerScoreResponse",[{no:1,name:"responseid",kind:"scalar",T:9},{no:2,name:"score",kind:"message",T:()=>CC}])}}new Hk;class qk 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 qk;class jk extends v{constructor(){super("media.edge.NoActiveSpeakerResponse",[])}}new jk;class Gk extends v{constructor(){super("media.edge.ProducerToggleResponse",[])}}new Gk;class Wk extends v{constructor(){super("media.edge.ConsumerToggleResponse",[])}}new Wk;class Jk extends v{constructor(){super("media.edge.ProducerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ls}])}}const Kk=new Jk;class zk extends v{constructor(){super("media.edge.ConsumerClosingResponse",[{no:1,name:"description",kind:"message",T:()=>ls}])}}const Yk=new zk;class Qk extends v{constructor(){super("media.edge.GlobalPeerPinningResponse",[])}}new Qk;class Xk extends v{constructor(){super("media.edge.KickPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Xk;class Zk extends v{constructor(){super("media.edge.KickAllPeersResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}new Zk;class eR extends v{constructor(){super("media.edge.HostMediaControlForPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const tR=new eR;class sR extends v{constructor(){super("media.edge.HostMediaControlForAllPeerResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const rR=new sR;class iR extends v{constructor(){super("media.edge.PeerDisplayNameEditResponse",[{no:1,name:"status",kind:"scalar",T:9}])}}const nR=new iR;class aR extends v{constructor(){super("media.edge.PeerJoinBroadcastResponse",[{no:1,name:"participant",kind:"message",T:()=>Og}])}}const Ng=new aR;class oR extends v{constructor(){super("media.edge.TrackSubscriptionKind",[{no:1,name:"audio",kind:"scalar",T:8},{no:2,name:"video",kind:"scalar",T:8}])}}const Vg=new oR;class cR extends v{constructor(){super("media.edge.TrackSubscription",[{no:1,name:"label",kind:"scalar",T:9},{no:2,name:"webcam",kind:"message",T:()=>Vg},{no:3,name:"screenshare",kind:"message",T:()=>Vg}])}}const dR=new cR;class lR 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:()=>dR}])}}new lR;class uR extends v{constructor(){super("media.edge.PeerProducerCreateBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Qa}])}}const hR=new uR;class pR extends v{constructor(){super("media.edge.PeerProducerToggleBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Qa},{no:3,name:"initiator_participant_id",kind:"scalar",opt:!0,T:9}])}}const Lg=new pR;class mR extends v{constructor(){super("media.edge.PeerProducerCloseBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9},{no:2,name:"producer_state",kind:"message",T:()=>Qa}])}}const gR=new mR;class fR extends v{constructor(){super("media.edge.PeerLeaveBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const Bu=new fR;class SR extends v{constructor(){super("media.edge.GlobalPeerPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}const xg=new SR;class vR extends v{constructor(){super("media.edge.GlobalPeerUnPinningBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new vR;class TR extends v{constructor(){super("media.edge.RecordingStartedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new TR;class yR extends v{constructor(){super("media.edge.RecordingStoppedBroadcastResponse",[{no:1,name:"participant_id",kind:"scalar",T:9}])}}new yR;class ER 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 ER;class wR extends v{constructor(){super("media.edge.PeerPingRequestBroadcastResponse",[{no:1,name:"password",kind:"scalar",T:9}])}}new wR;class bR extends v{constructor(){super("media.edge.MediaRoomTerminationBroadcastResponse",[{no:1,name:"reason",kind:"scalar",T:9}])}}new bR;class PR 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 Fu=new PR;class _R 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 _R;class CR 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 kR=new CR;var ui;(function(s){s[s.BROWSER=0]="BROWSER",s[s.TRACK=1]="TRACK",s[s.COMPOSITE=2]="COMPOSITE"})(ui||(ui={}));var Js;(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"})(Js||(Js={}));var Hu;(function(s){s[s.NONE=0]="NONE",s[s.RECORDER=1]="RECORDER",s[s.LIVESTREAMER=2]="LIVESTREAMER"})(Hu||(Hu={}));var qu;(function(s){s[s.PEERS=0]="PEERS",s[s.ROOMS=1]="ROOMS"})(qu||(qu={}));var bd;(function(s){s[s.HIVE=0]="HIVE",s[s.CHAT=1]="CHAT",s[s.PING=2]="PING"})(bd||(bd={}));class RR 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 IR=new RR;class AR 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",Js,"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:()=>IR}])}}const Pd=new AR;class MR extends v{constructor(){super("socket.room.PeerInfoResponse",[{no:1,name:"peer",kind:"message",T:()=>Pd}])}}const bn=new MR;class OR 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",Js,"STAGE_TYPE_"]}])}}const Ug=new OR;class DR 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 NR=new DR;class VR extends v{constructor(){super("socket.room.RoomPeersInfoResponse",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>Pd}])}}const ju=new VR;class LR extends v{constructor(){super("socket.room.RoomPeerCountResponse",[{no:1,name:"count",kind:"scalar",T:4,L:2}])}}const $g=new LR;class xR 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:()=>$R},{no:6,name:"room_uuid",kind:"scalar",opt:!0,T:9}])}}const Bg=new xR;class UR 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",ui]},{no:3,name:"recording_status",kind:"scalar",T:9}])}}const $R=new UR;class BR extends v{constructor(){super("socket.room.RoomInfoResponse",[{no:1,name:"room",kind:"message",T:()=>Bg}])}}const Fg=new BR;class FR extends v{constructor(){super("socket.room.GetPeerInfoRequest",[{no:1,name:"peer_id",kind:"scalar",T:9}])}}const Hg=new FR;class HR 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 HR;class qR extends v{constructor(){super("socket.room.JoinRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Pd},{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",bd,"CAPABILITIES_"]},{no:8,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const jR=new qR;class GR extends v{constructor(){super("socket.room.LeaveRoomRequest",[{no:1,name:"peer",kind:"message",T:()=>Pd},{no:2,name:"timestamp",kind:"scalar",opt:!0,T:4,L:2}])}}const WR=new GR;class JR extends v{constructor(){super("socket.room.UpdateRoomInfoRequest",[{no:1,name:"room",kind:"message",T:()=>Bg}])}}new JR;class KR extends v{constructor(){super("socket.room.GetConnectedRoomsDumpRequest",[])}}new KR;class zR 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 Gu=new zR;class YR 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 QR=new YR;class XR 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:()=>QR}])}}const qg=new XR;class ZR extends v{constructor(){super("socket.room.GetConnectedRoomsDumpResponse",[{no:1,name:"parent_meeting",kind:"message",T:()=>qg},{no:2,name:"meetings",kind:"message",repeat:1,T:()=>qg}])}}const e0=new ZR;class t0 extends v{constructor(){super("socket.room.CreateRoomRequestPayload",[{no:1,name:"title",kind:"scalar",opt:!0,T:9}])}}const s0=new t0;class r0 extends v{constructor(){super("socket.room.CreateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>s0}])}}const i0=new r0;class n0 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:()=>Gu}])}}const a0=new n0;class o0 extends v{constructor(){super("socket.room.CreateConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>a0}])}}const jg=new o0;class c0 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 d0=new c0;class l0 extends v{constructor(){super("socket.room.UpdateConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>d0}])}}new l0;class u0 extends v{constructor(){super("socket.room.DisableRoomPayload",[{no:1,name:"id",kind:"scalar",opt:!0,T:9}])}}const h0=new u0;class p0 extends v{constructor(){super("socket.room.DisableConnectedRoomsRequest",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>h0}])}}const m0=new p0;class g0 extends v{constructor(){super("socket.room.DisableConnectedRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>v0}])}}const f0=new g0;class S0 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:()=>Gu}])}}const v0=new S0;class T0 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 y0=new T0;class E0 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:()=>y0}])}}const w0=new E0;class b0 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:()=>Gu}])}}const Gg=new b0;class P0 extends v{constructor(){super("socket.room.MovePeersBetweenRoomsResponse",[{no:1,name:"payloads",kind:"message",repeat:1,T:()=>Gg}])}}new P0;class _0 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 C0=new _0;class k0 extends v{constructor(){super("socket.room.GetAllAddedParticipantsResponse",[{no:1,name:"participants",kind:"message",repeat:1,T:()=>A0}])}}const R0=new k0;class I0 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 A0=new I0;class M0 extends v{constructor(){super("socket.room.RemoveParticipantsRequest",[{no:1,name:"peer_ids",kind:"scalar",repeat:2,T:9}])}}const Wg=new M0;class O0 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",qu,"BROADCAST_TYPE_"]}])}}const Xa=new O0;class D0 extends v{constructor(){super("socket.room.AcceptWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const N0=new D0;class V0 extends v{constructor(){super("socket.room.DenyWaitingRoomRequests",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const L0=new V0;class x0 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 U0=new x0;class $0 extends v{constructor(){super("socket.room.GetWaitingRoomRequests",[{no:1,name:"requests",kind:"message",repeat:1,T:()=>U0}])}}const Jg=new $0;class B0 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 Kg=new B0;var Wu;(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"})(Wu||(Wu={}));var _r;(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"})(_r||(_r={}));class F0 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 H0=new F0;class q0 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 j0=new q0;class G0 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 W0=new G0;class J0 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 K0=new J0;class z0 extends v{constructor(){super("socket.preset.ChatPermissionUpdate",[{no:1,name:"public",kind:"message",T:()=>W0},{no:2,name:"private",kind:"message",T:()=>K0}])}}const Y0=new z0;class Q0 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 X0=new Q0;class Z0 extends v{constructor(){super("socket.preset.StreamPermission",[{no:1,name:"can_produce",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",_r,"STREAM_PERMISSION_TYPE_"]},{no:2,name:"can_consume",kind:"enum",opt:!0,T:()=>["socket.preset.StreamPermissionType",_r,"STREAM_PERMISSION_TYPE_"]}])}}const Ju=new Z0;class eI extends v{constructor(){super("socket.preset.MediaPermissionUpdate",[{no:1,name:"video",kind:"message",T:()=>Ju},{no:2,name:"audio",kind:"message",T:()=>Ju},{no:3,name:"screenshare",kind:"message",T:()=>Ju}])}}const tI=new eI;class sI extends v{constructor(){super("socket.preset.PresetUpdates",[{no:1,name:"polls",kind:"message",T:()=>H0},{no:2,name:"plugins",kind:"message",T:()=>j0},{no:3,name:"chat",kind:"message",T:()=>Y0},{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",Wu,"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",Hu,"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:()=>X0},{no:23,name:"media",kind:"message",T:()=>tI}])}}const Ku=new sI;class rI extends v{constructor(){super("socket.preset.ReadPeersPresetRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const iI=new rI;class nI 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 aI=new nI;class oI extends v{constructor(){super("socket.preset.ReadPeersPresetResponse",[{no:1,name:"peer_presets",kind:"message",repeat:1,T:()=>aI}])}}const cI=new oI;class dI extends v{constructor(){super("socket.preset.UpdatePeerPreset",[{no:1,name:"user_ids",kind:"scalar",T:9},{no:2,name:"patch",kind:"message",T:()=>Ku}])}}const zg=new dI;class lI extends v{constructor(){super("socket.preset.UpdatePeersPresetRequest",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>zg}])}}const uI=new lI;class hI extends v{constructor(){super("socket.preset.UpdatePeersPresetResponse",[{no:1,name:"update_peers_presets",kind:"message",repeat:1,T:()=>zg}])}}const Yg=new hI;class pI 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 mI=new pI;class gI extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetRequest",[{no:1,name:"peers",kind:"message",repeat:1,T:()=>mI},{no:2,name:"patch",kind:"message",T:()=>Ku}])}}new gI;class fI extends v{constructor(){super("socket.preset.BulkUpdatePeerPresetResponse",[{no:2,name:"patch",kind:"message",T:()=>Ku}])}}new fI;class SI 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 Cr=new SI;class vI 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 TI=new vI;class yI 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:()=>TI}])}}const EI=new yI;class wI extends v{constructor(){super("socket.chat.GetPaginatedChatMessageRoomResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Cr},{no:2,name:"next",kind:"scalar",T:8}])}}const bI=new wI;class PI extends v{constructor(){super("socket.chat.GetChatMessagesResponse",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>Cr}])}}const Qg=new PI;class _I 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 CI=new _I;class kI extends v{constructor(){super("socket.chat.SendChatMessageToRoomResponse",[{no:1,name:"message",kind:"message",T:()=>Cr}])}}const zu=new kI;class RI 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 II=new RI;class AI extends v{constructor(){super("socket.chat.SendChatMessageToPeersResponse",[{no:1,name:"message",kind:"message",T:()=>Cr}])}}const Yu=new AI;class MI 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 MI;class OI extends v{constructor(){super("socket.chat.SendChatMessageToChannelResponse",[{no:1,name:"message",kind:"message",T:()=>Cr}])}}new OI;class DI 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 NI=new DI;class VI 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 LI=new VI;class xI 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:()=>Cr}])}}const _d=new xI;class UI extends v{constructor(){super("socket.chat.EditChatMessageResponse",[{no:1,name:"message",kind:"message",T:()=>Cr}])}}const Cd=new UI;class $I 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 BI=new $I;class FI 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 kd=new FI;class HI 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 qI=new HI;class jI 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 jI;class GI extends v{constructor(){super("socket.chat.MarkChannelIndexAsReadResponse",[{no:1,name:"channel_index",kind:"scalar",T:9}])}}new GI;class WI 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 WI;class JI 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 JI;class KI extends v{constructor(){super("socket.chat.CreateChatChannelResponse",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new KI;class zI extends v{constructor(){super("socket.chat.GetChatChannelRequest",[{no:1,name:"chat_channel_id",kind:"scalar",T:9}])}}new zI;class YI extends v{constructor(){super("socket.chat.LatestMessageAndUnreadCount",[{no:1,name:"message",kind:"message",T:()=>Cr},{no:2,name:"unread_count",kind:"scalar",T:4,L:2}])}}const QI=new YI;class XI 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:()=>QI},{no:7,name:"target_user_ids",kind:"scalar",repeat:2,T:9}])}}const ZI=new XI;class eA extends v{constructor(){super("socket.chat.GetChatChannelResponse",[{no:1,name:"chat_channels",kind:"message",repeat:1,T:()=>ZI}])}}new eA;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 sA=new tA;class rA extends v{constructor(){super("socket.chat.GetChatChannelMembersResponse",[{no:1,name:"channel_members",kind:"message",repeat:1,T:()=>sA}])}}new rA;class iA 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 iA;class nA 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 nA;class aA extends v{constructor(){super("socket.plugin.EnablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new aA;class oA extends v{constructor(){super("socket.plugin.DisablePluginForRoomRequest",[{no:1,name:"plugin_id",kind:"scalar",T:9}])}}new oA;class cA 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 cA;class dA 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 dA;class lA 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 lA;class uA 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 uA;class hA 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 Qu=new hA;class pA 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:()=>Qu}])}}const mA=new pA;class gA 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:()=>Qu}])}}const fA=new gA;class SA 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:()=>Qu}])}}const vA=new SA;class TA 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 TA;class yA 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 EA=new yA;class wA extends v{constructor(){super("socket.plugin.EnablePluginsResponse",[{no:1,name:"plugins",kind:"message",repeat:1,T:()=>EA}])}}new wA;class bA 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 bA;class PA 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 _A=new PA;class CA 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:()=>_A}])}}const Xg=new CA;class kA 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 kA;class RA 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 Zg=new RA;class IA extends v{constructor(){super("socket.livestreaming.GetStagePeersResponse",[{no:1,name:"stage_peers",kind:"scalar",repeat:2,T:9}])}}const ef=new IA;class AA 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 MA=new AA;class OA extends v{constructor(){super("socket.livestreaming.GetStageRequestsResponse",[{no:1,name:"stage_requests",kind:"message",repeat:1,T:()=>MA}])}}const Xu=new OA;class DA extends v{constructor(){super("socket.livestreaming.GrantStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const NA=new DA;class VA extends v{constructor(){super("socket.livestreaming.DenyStageAccessRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const LA=new VA;class xA extends v{constructor(){super("socket.livestreaming.LeaveStageRequest",[{no:1,name:"user_ids",kind:"scalar",repeat:2,T:9}])}}const tf=new xA;class UA 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:()=>BA},{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 UA;class $A 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:()=>HA}])}}const BA=new $A;class FA 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 HA=new FA;class qA 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 jA=new qA;class GA 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 WA=new GA;class JA extends v{constructor(){super("socket.polls.UpdatePollResponse",[{no:1,name:"poll",kind:"message",T:()=>sf}])}}const Zu=new JA;class KA extends v{constructor(){super("socket.polls.GetPollsResponse",[{no:1,name:"polls",kind:"message",repeat:1,T:()=>sf}])}}const zA=new KA;class YA 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",ui]}])}}const rf=new YA;class QA 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=he.from(Math.floor(e/1e3)).toBigInt(),t.nanos=e%1e3*1e6,t}toDate(t){return new Date(he.from(t.seconds).toNumber()*1e3+Math.ceil(t.nanos/1e6))}fromDate(t){const e=this.create(),r=t.getTime();return e.seconds=he.from(Math.floor(r/1e3)).toBigInt(),e.nanos=r%1e3*1e6,e}internalJsonWrite(t,e){let r=he.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 "+Ou(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=he.from(n/1e3).toBigInt(),r.nanos=0,i[7]&&(r.nanos=parseInt("1"+i[7]+"0".repeat(9-i[7].length))-1e9),r}}new QA;class XA 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 eh=new XA;class ZA extends v{constructor(){super("common.BulkedHubMessage",[{no:1,name:"messages",kind:"message",repeat:1,T:()=>eh}])}}new ZA;class eM extends v{constructor(){super("common.CFWorkersResponse",[{no:1,name:"responses",kind:"message",repeat:1,T:()=>eh},{no:2,name:"broadcast_responses",kind:"message",repeat:1,T:()=>eh}])}}new eM;const tM=0,sM=1,rM=2,iM=3,nM=5,aM={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},oM={getMessages:0,sendMessageToRoom:1,sendMessageToPeers:2,editMessage:3,deleteMessage:4,getPaginatedMessages:5,searchChannelMessages:7,pinMessage:10},cM={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},dM={createPoll:0,getPolls:1,votePoll:2,updatePoll:3},nf={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},lM={getUserPresets:0,updateUserPreset:1};function Za(s,t){return Object.keys(t).reduce((e,r)=>(e[r]=(s<<16)+t[r],e),{})}function af(s,t){return Object.keys(s).reduce((e,r)=>(e[r]=t|s[r],e),{})}const x=Za(tM,aM),Ge=Za(sM,oM),Ks=Za(rM,cM),zs=Za(iM,dM),kr=af(nf,16777216),us=af(nf,50331648),Rd=Za(nM,lM);var uM=Object.defineProperty,hM=Object.getOwnPropertyDescriptor,Rr=(s,t,e,r)=>{for(var i=r>1?void 0:r?hM(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&&uM(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 Ys{constructor(t,e){g(this,$t,void 0);g(this,Un,void 0);f(this,$t,e),f(this,Un,t)}get telemetry(){return a(this,Un).getValue("telemetry")}get logger(){return a(this,Un).getValue("logger")}getChatMessages(){return a(this,$t).sendMessagePromise(Ge.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,$t).sendMessagePromise(Ge.getPaginatedMessages,EI.toBinary(n));return o.payload?bI.fromBinary(o.payload):{messages:[],next:!1}}sendMessageToRoom(t,e){const r={payloadType:e,payload:t};a(this,$t).sendMessage(Ge.sendMessageToRoom,CI.toBinary(r))}sendMessageToPeers(t,e,r){const i={payloadType:e,peerIds:r,payload:t};a(this,$t).sendMessage(Ge.sendMessageToPeers,II.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,$t).sendMessagePromise(Ge.editMessage,NI.toBinary(n));return Cd.fromBinary(o.payload).message}async deleteMessage(t){const e={chatId:t},r=await a(this,$t).sendMessagePromise(Ge.deleteMessage,BI.toBinary(e));return{id:kd.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,$t).sendMessagePromise(Ge.searchChannelMessages,qI.toBinary(r));return Qg.fromBinary(d.payload).messages}catch(d){return[]}}async setPinState(t,e){const r={chatId:t,pinned:e},i=await a(this,$t).sendMessagePromise(Ge.pinMessage,LI.toBinary(r));return _d.fromBinary(i.payload)}on(t,e){let r,i;switch(t){case Ge.sendMessageToRoom:{r=zu.fromBinary.bind(zu),i=zu.create();break}case Ge.sendMessageToPeers:{r=Yu.fromBinary.bind(Yu),i=Yu.create();break}case Ge.editMessage:{r=Cd.fromBinary.bind(Cd),i=Cd.create();break}case Ge.pinMessage:{r=_d.fromBinary.bind(_d),i=_d.create();break}case Ge.deleteMessage:{r=kd.fromBinary.bind(kd),i=kd.create();break}}if(!r){this.logger.warn(`ChatSocketHandler::Event ${t} is not recognized`);return}a(this,$t).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)})}}$t=new WeakMap,Un=new WeakMap,Rr([E.trace("SocketService.getChatMessages")],Ys.prototype,"getChatMessages",1),Rr([E.trace("SocketService.getChatMessagesPaginated")],Ys.prototype,"getChatMessagesPaginated",1),Rr([E.trace("SocketService.sendMessageToRoom")],Ys.prototype,"sendMessageToRoom",1),Rr([E.trace("SocketService.sendMessageToPeers")],Ys.prototype,"sendMessageToPeers",1),Rr([E.trace("SocketService.sendMessage")],Ys.prototype,"sendMessage",1),Rr([E.trace("SocketService.editMessage")],Ys.prototype,"editMessage",1),Rr([E.trace("SocketService.deleteMessage")],Ys.prototype,"deleteMessage",1),Rr([E.trace("SocketService.searchMessages")],Ys.prototype,"searchMessages",1);function pM(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=su(e)?e:pM(e);t[r]=Is(s[e])}),t}function mM(s){return s.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function of(s){if(!s||typeof s!="object")return s;if(Array.isArray(s))return s.map(e=>of(e));const t={};return Object.keys(s).forEach(e=>{const r=su(e)?e:mM(e);t[r]=s[e]}),t}class th extends Error{constructor(e){var t=(...gN)=>{super(...gN);p(this,"status");p(this,"response");p(this,"isTimeout")};e instanceof Error?(t(e.message),this.stack=e.stack,this.isTimeout=e.name==="AbortError"):(t(`Request failed with status ${e.status}`),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 cf{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 b=y.headers.get("content-type");b&&b.includes("application/json")?w=await y.json():w=await y.text();const R={};y.headers.forEach((U,L)=>{R[L]=U});const N={data:w,status:y.status,statusText:y.statusText,headers:R,config:t};if(!y.ok)throw N;return N}catch(m){if(m instanceof Error&&l>0)return await new Promise(S=>setTimeout(S,u)),this.defaults.baseURL===li.apiBase.prod?this.defaults.baseURL=li.apiBase.prodAlternate:this.defaults.baseURL===li.apiBase.prodAlternate&&(this.defaults.baseURL=li.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 gM=3,fM=30,SM=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=SM,retry:i=gM,retryDelay:n=fM,baseURL:o=li.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 cf({baseURL:o,timeout:r,retry:i,retryDelay:n,responseType:"json"}),this.fetchClient=new cf({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,b;const h=t.getValue("telemetry");try{h.injectContext(this.requests.defaults.headers.common);const R=await l(u);return u.url!==h.logsEndpoint&&this.logger.debug("xhr::fetch",{networkCall:{status:R.status,statusText:R.statusText,baseURL:u.baseURL||this.requests.defaults.baseURL,url:u.url,method:u.method}}),R}catch(R){if(!R)throw new C("Unknown network error occurred","0011");if(R instanceof C||R instanceof th)throw R;((m=R.config)==null?void 0:m.url)!==h.logsEndpoint&&this.logger.error("xhr::fetch",{error:R,networkCall:{status:R.status,statusText:R.statusText,baseURL:((S=R.config)==null?void 0:S.baseURL)||this.requests.defaults.baseURL,url:(y=R.config)==null?void 0:y.url,retries:(w=R.config)==null?void 0:w.retry,method:(b=R.config)==null?void 0:b.method,isOnline:navigator.onLine?"online":"offline"}});const N=R instanceof Error&&R.message||"Network request failed";throw new C(N,"0011"),new th(R)}}}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 TM=Object.defineProperty,yM=Object.getOwnPropertyDescriptor,Qs=(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&&TM(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=yn(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",{...of(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")}}}Qs([E.trace("APIClient.getICEServers")],As.prototype,"getICEServers",1),Qs([E.trace("APIClient.startLivestreaming")],As.prototype,"startLivestreaming",1),Qs([E.trace("APIClient.stopLivestreaming")],As.prototype,"stopLivestreaming",1),Qs([E.trace("APIClient.getActiveLivestream")],As.prototype,"getActiveLivestream",1),Qs([E.trace("APIClient.getUserDetails")],As.prototype,"getUserDetails",1),Qs([E.trace("APIClient.startRecording")],As.prototype,"startRecording",1),Qs([E.trace("APIClient.stopRecording")],As.prototype,"updateRecording",1),Qs([E.trace("APIClient.getActiveRecording")],As.prototype,"getActiveRecording",1),Qs([E.trace("APIClient.getActiveTranscript")],As.prototype,"getActiveTranscript",1);let sh;function EM(s,t){return sh=new As(s,t),sh}function Pt(){return sh}const Pn={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 C(`Method rate limit ${u.maxInvocations} invocations/${u.period}sec exceeded`,"0013");return o+=1,n.apply(this,d)},i}}var wM=Object.defineProperty,bM=Object.getOwnPropertyDescriptor,hs=(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&&wM(t,e,i),i};const PM=["text","image","file","custom","poll"],Id={maxInvocations:180,period:60};let Vt=(TS=class extends Dt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,il);g(this,To);p(this,"messages");g(this,Z,void 0);g(this,Pi,void 0);g(this,Ke,void 0);g(this,$n,void 0);p(this,"maxTextLimit",2e3);f(this,$n,t),f(this,Ke,e),f(this,Z,r),f(this,Pi,i),this.messages=[]}get telemetry(){return a(this,$n).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,Z).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,Z).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,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,Z).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,Z).id),r=a(this,Pi).joined.toArray().filter(u=>e.includes(u.id)).map(u=>u.userId),r.push(a(this,Z).userId)),a(this,Ke).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,Z).permissions)!=null&&i.chatPrivate.canSend)||!((n=a(this,Z).permissions)!=null&&n.chatPrivate.files)){this.logger.error("sendImageMessage::private_chat_permission_denied");return}}else if(!((c=(o=a(this,Z).permissions)==null?void 0:o.chatPublic)!=null&&c.canSend)||!((l=(d=a(this,Z).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,Z).id),S=a(this,Pi).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),S.push(a(this,Z).userId)),a(this,Ke).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,Z).permissions)!=null&&r.chatPrivate.canSend)||!((i=a(this,Z).permissions)!=null&&i.chatPrivate.files)){this.logger.error("sendFileMessage::private_chat_permission_denied");return}}else if(!((o=(n=a(this,Z).permissions)==null?void 0:n.chatPublic)!=null&&o.canSend)||!((d=(c=a(this,Z).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,Z).id),m=a(this,Pi).joined.toArray().filter(y=>e.includes(y.id)).map(y=>y.userId),m.push(a(this,Z).userId));const S=JSON.stringify({link:u,name:t.name,size:"size"in t?t.size:0});a(this,Ke).sendMessage(S,zt.FILE,e)}catch(l){throw new C("Error sending file message.","0500",this.logger)}}get rateLimits(){return Id}updateRateLimits(t,e){Id.maxInvocations=t,Id.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,b,R,N,U;if(e&&e.length>0){if(!((n=a(this,Z).permissions)!=null&&n.chatPrivate.canSend)||!((o=a(this,Z).permissions)!=null&&o.chatPrivate.files)||!((c=a(this,Z).permissions)!=null&&c.chatPrivate.text)){this.logger.error("sendCustomMessage::private_chat_permission_denied");return}}else if(!((l=(d=a(this,Z).permissions)==null?void 0:d.chatPublic)!=null&&l.canSend)||!((h=(u=a(this,Z).permissions)==null?void 0:u.chatPublic)!=null&&h.files)||!((S=(m=a(this,Z).permissions)==null?void 0:m.chatPublic)!=null&&S.text)){this.logger.error("sendCustomMessage::permission_denied");return}const r=async L=>{try{if(typeof L=="string")return{link:L};const F=Pt(),{getLocation:H,putLocation:ie}=await F.getPresignedUrls(L.name);return await F.uploadFile(L,ie),{link:H,type:L.type,name:L.name,size:L.size}}catch(F){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 L=>r(L))),images:await Promise.all((R=(b=t.images)!=null?b:[])==null?void 0:R.map(async L=>r(L))),videos:await Promise.all((U=(N=t.videos)!=null?N:[])==null?void 0:U.map(async L=>r(L)))};a(this,Ke).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,Z).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,Z).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,Ke).editMessage(t,e,zt.TEXT)}async editImageMessage(t,e){var i,n,o,c;if(!((n=(i=a(this,Z).permissions)==null?void 0:i.chatPublic)!=null&&n.canSend)||!((c=(o=a(this,Z).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,Ke).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,Z).permissions)==null?void 0:r.chatPublic)!=null&&i.canSend)||!((o=(n=a(this,Z).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,Ke).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,Ke).deleteMessage(t)}getMessagesByUser(t){return this.messages.filter(e=>e.userId===t)}getMessagesByType(t){return this.messages.filter(e=>e.type===t)}async pin(t){if(!a(this,To,Bh))throw new C("Can`t pin message without joining room","0505");try{await a(this,Ke).setPinState(t,!0)}catch(e){throw new C(`No message found with id: ${t}`,"0504")}}async unpin(t){if(!a(this,To,Bh))throw new C("Can`t unpin message without joining room","0505");try{await a(this,Ke).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,Ke).getChatMessagesPaginated(t,e,r==="before")).messages.map(o=>_n.formatSocketPeerMessage(o))}async fetchPrivateMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after",userId:i}){return(await a(this,Ke).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"userId",userId:i})).messages.map(c=>_n.formatSocketPeerMessage(c))}async fetchPinnedMessages({timestamp:t=new Date().getTime(),limit:e,direction:r="after"}){return(await a(this,Ke).getChatMessagesPaginated(t,e,r==="before",{oneofKind:"pinned",pinned:!0})).messages.map(o=>_n.formatSocketPeerMessage(o))}async getMessages(t,e,r,i=0){const n=await a(this,Ke).getChatMessagesPaginated(t,e,r);return{messages:n.messages.map(o=>_n.formatSocketPeerMessage(o)),next:n.next}}async searchMessages(t,e){throw new C("searchMessages is disabled! Please use `fetchPublicMessages` method instead.","0506")}get pinned(){return this.messages.filter(t=>t.pinned)}},Z=new WeakMap,Pi=new WeakMap,Ke=new WeakMap,$n=new WeakMap,il=new WeakSet,US=function(){return a(this,$n).getValue("connectionHandler")},To=new WeakSet,Bh=function(){return a(this,il,US).socketJoined===!0},TS);hs([E.trace("Chat.sendTextMessage"),Nt(Id)],Vt.prototype,"sendTextMessage",1),hs([E.trace("Chat.sendImageMessage"),Nt({maxInvocations:20,period:60})],Vt.prototype,"sendImageMessage",1),hs([E.trace("Chat.sendFileMessage"),Nt({maxInvocations:20,period:60})],Vt.prototype,"sendFileMessage",1),hs([E.trace("Chat.sendMessage"),Nt({maxInvocations:180,period:60})],Vt.prototype,"sendMessage",1),hs([E.trace("Chat.editTextMessage")],Vt.prototype,"editTextMessage",1),hs([E.trace("Chat.editImageMessage")],Vt.prototype,"editImageMessage",1),hs([E.trace("Chat.editFileMessage")],Vt.prototype,"editFileMessage",1),hs([E.trace("Chat.editMessage")],Vt.prototype,"editMessage",1),hs([E.trace("Chat.deleteMessage")],Vt.prototype,"deleteMessage",1),hs([E.trace("Chat.searchMessages")],Vt.prototype,"searchMessages",1),Vt=hs([nt("0500")],Vt);var _M=Object.defineProperty,CM=Object.getOwnPropertyDescriptor,kM=(s,t,e,r)=>{for(var i=r>1?void 0:r?CM(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 Ir=(yS=class{constructor(s,t,e,r){p(this,"chat");p(this,"chatSocketHandler");p(this,"self");g(this,_i,void 0);f(this,_i,s),this.chatSocketHandler=t,this.chat=new Vt(s,t,e,r),this.self=e,this.setupEvents()}get telemetry(){return a(this,_i).getValue("telemetry")}get logger(){return a(this,_i).getValue("logger")}static async init(s,t,e,r){return new Ir(s,t,e,r)}static formatMessage(s){return{...s,time:new Date(s.time),type:PM[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 Ir.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=Qg.fromBinary(s.payload).messages;this.chat.messages=t.map(e=>Ir.formatSocketPeerMessage(e))}setupEvents(){a(this,_i).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{this.getChatMessages()}),this.chatSocketHandler.on(Ge.sendMessageToRoom,s=>{if(!s.message)return;const t=Ir.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(Ge.sendMessageToPeers,s=>{const t=Ir.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(Ge.editMessage,s=>{if(!s.message)return;const t=Ir.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(Ge.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(Ge.pinMessage,s=>{const t=this.chat.messages.findIndex(r=>r.id===s.chatId),e=Ir.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})})}},_i=new WeakMap,yS);let _n=Ir;kM([E.trace("ChatController.setupEvents")],_n.prototype,"setupEvents",1);var RM=Object.defineProperty,IM=Object.getOwnPropertyDescriptor,AM=(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};let rh=(ES=class extends Dt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,nl);g(this,al);p(this,"items");g(this,Bn,void 0);g(this,Fn,void 0);g(this,yo,void 0);f(this,yo,t),f(this,Bn,e),f(this,Fn,r),this.items=[]}async create(t,e,r=!1,i=!1){if(!a(this,al,BS))throw new C("Can't create polls without joining room","0705");if(!a(this,Bn).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,Fn).createPoll(t,e,r,i)}async vote(t,e){if(!a(this,Bn).permissions.polls.canVote){this.logger.error("Polls::vote::permission_denied");return}await a(this,Fn).votePoll(t,e)}},nl=new WeakSet,$S=function(){return a(this,yo).getValue("connectionHandler")},al=new WeakSet,BS=function(){var t;return((t=a(this,nl,$S))==null?void 0:t.socketJoined)===!0},Bn=new WeakMap,Fn=new WeakMap,yo=new WeakMap,ES);rh=AM([nt("0700")],rh);var MM=Object.defineProperty,OM=Object.getOwnPropertyDescriptor,DM=(s,t,e,r)=>{for(var i=r>1?void 0:r?OM(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&&MM(t,e,i),i};const Cn=(wS=class{constructor(s,t,e){p(this,"polls");g(this,$r,void 0);g(this,Hn,void 0);g(this,Ci,void 0);this.polls=new rh(s,t,e),f(this,Hn,t),f(this,$r,s),f(this,Ci,e),this.setupEvents()}get telemetry(){return a(this,$r).getValue("telemetry")}get logger(){return a(this,$r).getValue("logger")}static async init(s,t,e){return new Cn(s,t,e)}canViewPolls(){return a(this,Hn).permissions.polls.canView}setupEvents(){const s={[zs.createPoll]:r=>{r.poll&&this.updatePoll(Cn.formatSocketServicePoll(r.poll))},[zs.updatePoll]:r=>{r.poll&&this.updatePoll(Cn.formatSocketServicePoll(r.poll))},[zs.votePoll]:r=>{r.poll&&this.updatePoll(Cn.formatSocketServicePoll(r.poll))}},t=()=>{a(this,$r).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Ci).on(r,s[r])})},e=()=>{a(this,$r).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,()=>{this.getPolls()}),Object.keys(s).map(Number).forEach(r=>{a(this,Ci).removeListeners(r)})};a(this,Hn).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,Ci).getPolls();if(!(s!=null&&s.payload))return;const{polls:t}=zA.fromBinary(s.payload);this.polls.items=t.map(e=>Cn.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}}},$r=new WeakMap,Hn=new WeakMap,Ci=new WeakMap,wS);let df=Cn;DM([E.trace("PollController.setupEvents")],df.prototype,"setupEvents",1);var NM=Object.defineProperty,VM=Object.getOwnPropertyDescriptor,LM=(s,t,e,r)=>{for(var i=r>1?void 0:r?VM(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&&NM(t,e,i),i},lf=(s=>(s[s.User=0]="User",s[s.Meeting=1]="Meeting",s))(lf||{});let ih=(bS=class extends Dt{constructor(t,e,r,i,n){const o=t.getValue("logger");super(o);g(this,Eo);p(this,"selfActiveTab");p(this,"broadcastTabChanges");g(this,qn,void 0);g(this,ki,void 0);g(this,wo,void 0);p(this,"viewType");p(this,"meetingStartedTimestamp");p(this,"meetingTitle");p(this,"sessionId");f(this,qn,t),f(this,ki,e),this.viewType=r,f(this,wo,i),this.meetingTitle=n,this.broadcastTabChanges=e.permissions.canSpotlight}get socketState(){return a(this,Eo,Fh).socketState}get mediaState(){return a(this,Eo,Fh).mediaState}get meetingId(){return a(this,qn).getValue("meetingId")}setBroadcastTabChanges(t){if(!a(this,ki).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,ki).permissions)!=null&&r.canSpotlight&&this.broadcastTabChanges&&e===0&&this.assertActiveTabToRoom()}assertActiveTabToRoom(){a(this,wo).broadcastMessage("spotlight",{userId:a(this,ki).userId,currentTab:this.selfActiveTab})}},qn=new WeakMap,Eo=new WeakSet,Fh=function(){return a(this,qn).getValue("connectionHandler")},ki=new WeakMap,wo=new WeakMap,bS);ih=LM([nt("0800")],ih);function xM(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 UM=Object.defineProperty,$M=Object.getOwnPropertyDescriptor,uf=(s,t,e,r)=>{for(var i=r>1?void 0:r?$M(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&&UM(t,e,i),i};let Ar=(PS=class extends Dt{constructor(t){const e=t.getValue("logger");super(e);p(this,"transcripts");g(this,bo,void 0);f(this,bo,t),this.transcripts=[]}get telemetry(){return a(this,bo).getValue("telemetry")}static async init(t,e){const r=new Ar(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]]=xM(t);return{id:mn(),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=>Ar.parseTranscript(e,!1)).filter(Boolean):[]}async getActiveTranscript(){try{const t=Pt(),{transcript:e}=await t.getActiveTranscript();this.transcripts=Ar.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)}},bo=new WeakMap,PS);uf([E.trace("Ai.getActiveTranscript")],Ar.prototype,"getActiveTranscript",1),Ar=uf([nt("0000")],Ar);var BM=Object.defineProperty,FM=Object.getOwnPropertyDescriptor,HM=(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 hf=(_S=class{constructor(s,t,e,r,i,n){p(this,"meta");p(this,"ai");g(this,Br,void 0);g(this,jn,void 0);p(this,"aiSocketHandler");g(this,Bt,void 0);f(this,Bt,s),this.meta=new ih(s,t,t.config.viewType,e,n),this.ai=r,f(this,Br,t),f(this,jn,e),this.aiSocketHandler=i,this.setupEvents()}get telemetry(){return a(this,Bt).getValue("telemetry")}get logger(){return a(this,Bt).getValue("logger")}static async init(s,t,e,r,i){const n=await Ar.init(s,t.permissions.transcriptionEnabled);return new hf(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,lf.Meeting),this.meta.emit("activeTabUpdate",s.currentTab))}setupEvents(){a(this,Bt).getValue("peerSessionStore").on(_.TRANSPORT_STATE_UPDATE,s=>{this.meta.emit("mediaConnectionUpdate",s)}),a(this,Bt).getValue("peerSessionStore").on(_.SOCKET_STATE_UPDATE,s=>{this.meta.emit("socketConnectionUpdate",s)}),a(this,Bt).getValue("peerSessionStore").on(_.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,Bt).getValue("peerSessionStore").on(_.PRODUCER_SCORE_UPDATE,({score:s})=>{s<5&&this.meta.emit("poorConnection",{score:s})}),a(this,Br).permissions.canSpotlight&&(this.logger.info("MetaController::Asserting Spotlight"),this.meta.selfActiveTab&&a(this,jn).broadcastMessage("spotlight",{userId:a(this,Br).userId,currentTab:this.meta.selfActiveTab})),a(this,Bt).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async s=>{a(this,Br).permissions.canSpotlight&&this.meta.selfActiveTab&&a(this,jn).broadcastToPeers("spotlight",[s.id],{userId:a(this,Br).userId,currentTab:this.meta.selfActiveTab})}),a(this,Bt).getValue("peerSessionStore").on(_.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,Bt).getValue("peerSessionStore").on(_.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(x.transcript,s=>{const{meetingId:t,transcript:e,isPartial:r}=s;let i;try{i=Ar.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),this.meta.emit("transcript",i);const{peerId:n,name:o,transcript:c}=i;this.logger.debug(`${t} Received transcript for peer ${n} - ${o}: ${c}`)})}},Br=new WeakMap,jn=new WeakMap,Bt=new WeakMap,_S);let pf=hf;HM([E.trace("MetaController.setupEvents")],pf.prototype,"setupEvents",1);const eo={},Xs={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(eo[u]){const b=new Error(`Unsupported concurrent calls on method: ${s}.`);throw b.name="UnsupportedConcurrentMethodExecution",h==null||h.error("Locker::UnsupportedConcurrentMethodExecution",{error:{stack:b.stack},locker:{methodName:s,lockName:u}}),b}eo[u]=!0;const m=setTimeout(()=>delete eo[u],e),S=o.apply(this,d);return Promise.resolve(S).then(()=>{delete eo[u],clearTimeout(m)}).catch(()=>{delete eo[u],clearTimeout(m)}),S},n}}};var qM=Object.defineProperty,jM=Object.getOwnPropertyDescriptor,hi=(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};class Mr extends Dt{constructor(e,r,i,n,o){const c=e.getValue("logger");super(c);g(this,_o);g(this,Gn);g(this,Xt,void 0);g(this,ol,void 0);g(this,re,void 0);g(this,Po,void 0);g(this,Ms,void 0);g(this,ze,void 0);f(this,ze,e),f(this,Xt,n),f(this,ol,o),f(this,re,r),f(this,Po,i),f(this,Ms,[]),this.setupEvents()}get telemetry(){return a(this,ze).getValue("telemetry")}get status(){return a(this,ze).getValue("stageStatus")}setupEvents(){const e={[_.GET_STAGE_REQUESTS]:async n=>{f(this,Ms,n)},[_.UPDATE_STAGE_REQUESTS]:async({add:n})=>{const o=a(this,Ms).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,re).permissions.on("permissionsUpdate",n=>{const{canAcceptProductionRequests:o}=n;o!==void 0&&(a(this,re).permissions.acceptStageRequests?(r(),a(this,Xt).getStageRequests()):(i(),f(this,Ms,[]),this.emit("stageAccessRequestUpdate",a(this,Ms))))}),a(this,re).permissions.acceptStageRequests&&r()}getAccessRequests(){if(!a(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,re).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,Po).joined.toArray().filter(r=>r.stageStatus==="REQUESTED_TO_JOIN_STAGE").map(r=>({displayName:r.name,userId:r.userId,peerId:r.id}));return f(this,Ms,e),{stageRequests:a(this,Ms)}}async requestAccess(){if(!a(this,re).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,re).permissions.stageAccess===q.Allowed){$(this,Gn,Ql).call(this,"ACCEPTED_TO_JOIN_STAGE");return}a(this,Xt).requestAccess(),$(this,Gn,Ql).call(this,"REQUESTED_TO_JOIN_STAGE")}async cancelRequestAccess(){if(!a(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");a(this,Xt).cancelRequestAccess(),$(this,Gn,Ql).call(this,"OFF_STAGE")}grantAccess(e){if(!a(this,re).roomJoined)throw new C("Can`t grant for participant without joining room");if(!a(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,re).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,Xt).grantAccess(e)}denyAccess(e){if(!a(this,re).roomJoined)throw new C("Can`t rejectRequestToJoinStage for participant without joining room","2005");if(!a(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,re).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,Xt).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,re).permissions.stageAccess===q.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,Xt).joinStage(),e===qs.Livestream){await a(this,ze).getValue("selfController").joinRoom();return}a(this,ze).notify("stageStatus"),a(this,re).audioEnabled&&a(this,_o,Hh).shareMic(a(this,re).audioTrack),a(this,re).videoEnabled&&a(this,_o,Hh).shareWebcam(a(this,re).videoTrack)}async leave(){if(!a(this,re).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,re).setIsPinned(!1),a(this,ze).setValue("stageStatus","OFF_STAGE",!1),await a(this,Xt).leaveStage(a(this,re).userId);try{await a(this,ze).getValue("peerSessionStore").emitAsync(_.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,re).roomJoined)throw new C("Can`t kick participant without joining room","2005");if(!a(this,re).permissions.stageEnabled)throw this.logger.error("Stage::stage_disabled"),new C("Stage is disabled","2003");if(!a(this,re).permissions.acceptStageRequests)throw this.logger.error("Stage::kick::permission_denied"),new C("You do not have permissions for kick","2001");return a(this,Xt).kick(e)}}Xt=new WeakMap,ol=new WeakMap,re=new WeakMap,Po=new WeakMap,Ms=new WeakMap,ze=new WeakMap,_o=new WeakSet,Hh=function(){return a(this,ze).getValue("roomNodeClient")},Gn=new WeakSet,Ql=async function(e){this.status!==e&&a(this,ze).setValue("stageStatus",e)},hi([E.trace("Stage.getStageRequests")],Mr.prototype,"getAccessRequests",1),hi([E.trace("Stage.requestAccess")],Mr.prototype,"requestAccess",1),hi([E.trace("Stage.cancelRequestAccess")],Mr.prototype,"cancelRequestAccess",1),hi([E.trace("Stage.grantAccess")],Mr.prototype,"grantAccess",1),hi([E.trace("Stage.denyAccess")],Mr.prototype,"denyAccess",1),hi([Xs.executeWithLock({methodName:"joinStage",lockName:"Stage.join",timeout:5e3}),E.trace("Stage.joinStage")],Mr.prototype,"join",1),hi([E.trace("Stage.leaveStage")],Mr.prototype,"leave",1);function GM(s){return!(s.viewType==="LIVESTREAM"||s.viewType==="CHAT")}function nh(s){switch(s){case Js.UNSPECIFIED:return"OFF_STAGE";case Js.REQUESTED_STAGE:return"REQUESTED_TO_JOIN_STAGE";case Js.APPROVED_STAGE:return"ACCEPTED_TO_JOIN_STAGE";case Js.OFF_STAGE:return"OFF_STAGE";case Js.ON_STAGE:return"ON_STAGE";default:return"OFF_STAGE"}}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};class mf{constructor(t,e,r,i,n){p(this,"stage");g(this,Fr,void 0);g(this,fs,void 0);g(this,Hr,void 0);g(this,Co,0);g(this,St,void 0);f(this,St,t),this.stage=new Mr(t,i,n,e,r),f(this,Hr,e),f(this,Fr,i),f(this,fs,n),this.setupEvents()}get telemetry(){return a(this,St).getValue("telemetry")}get logger(){return a(this,St).getValue("logger")}setupEvents(){a(this,St).subscribe("stageStatus",t=>{this.stage.emit("stageStatusUpdate",t)}),a(this,Hr).on(x.grantStageAccess,()=>{a(this,Fr).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestApproved"),this.setStageStatus("ACCEPTED_TO_JOIN_STAGE"))}),a(this,Hr).on(x.peerStageStatusUpdate,t=>{t!==void 0&&(t.peerId===a(this,Fr).id?this.selfStageStatusHandler(t):this.peerStageStatusHandler(t))}),a(this,Hr).on(x.denyStageAccess,()=>{a(this,Fr).permissions.stageAccess!==q.Allowed&&(this.stage.emit("stageRequestRejected"),this.setStageStatus("OFF_STAGE"))}),a(this,Hr).on(x.getStageRequests,async t=>{var r;if(a(this,Fr).permissions.stageAccess!==q.Allowed)return;const e=(r=t==null?void 0:t.stageRequests)!=null?r:[];await a(this,St).getValue("peerSessionStore").emitAsync(_.GET_STAGE_REQUESTS,e),a(this,Co)<e.length&&e.length>0&&this.stage.emit("newStageRequest",{count:e.length}),f(this,Co,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,St).setValue("stageStatus",t)}selfStageStatusHandler(t){const e=nh(t.stageType),r=a(this,St).getValue("stageStatus");if(r!==e)switch(t.stageType){case 1:a(this,St).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,St).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,St).getValue("peerSessionStore").emit(_.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,St).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:a(this,fs).viewMode,page:a(this,fs).currentPage});break}a(this,St).getValue("peerSessionStore").emit(_.UPDATE_PEER_STAGE_STATUS,{id:e.id,status:e.stageStatus})}}Fr=new WeakMap,fs=new WeakMap,Hr=new WeakMap,Co=new WeakMap,St=new WeakMap,KM([E.trace("Stage.setupEvents")],mf.prototype,"setupEvents",1);var zM=Object.defineProperty,YM=Object.getOwnPropertyDescriptor,ah=(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};let to=(CS=class extends wn{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,Ri,void 0);g(this,Wn,void 0);g(this,ko,void 0);g(this,Ro,void 0);g(this,Ii,void 0);p(this,"active");p(this,"enabledBy");f(this,ko,t);const o=t.getValue("meetingId");this.id=`${o}:${e.id}`,this.name=e.name,this.icon=e.icon,f(this,Ro,e.component),this.permissions=e.permissions,f(this,Ri,i),f(this,Wn,r),this.active=!1,this.enabledBy=""}get component(){return a(this,Ro)}get telemetry(){return a(this,ko).getValue("telemetry")}activateForSelf(){f(this,Ii,new Date),this.active=!0,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("enabled")}deactivateForSelf(){f(this,Ii,void 0),this.active=!1,this.emit("stateUpdate",{active:this.active,pluginId:this.id}),this.emit("closed")}async activate(){var t;this.active||(t=this.permissions)!=null&&t.canActivate&&(await a(this,Wn).set(this.id,{name:this.name,icon:this.icon,id:this.id,enabledBy:a(this,Ri).id}),this.enabledBy=a(this,Ri).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,Ri).id)return;const t=a(this,Ii)?new Date().getTime()-a(this,Ii).getTime():0;await a(this,Wn).set(this.id,null),this.deactivateForSelf(),this.logger.info("plugin::deactivated",{plugin:{id:this.id,name:this.name,duration:t}})}},Ri=new WeakMap,Wn=new WeakMap,ko=new WeakMap,Ro=new WeakMap,Ii=new WeakMap,CS);ah([E.trace("Plugin.activatePlugin")],to.prototype,"activate",1),ah([E.trace("Plugin.deactivatePlugin")],to.prototype,"deactivate",1),to=ah([nt("0600")],to);class gf extends Map{constructor(e,r=void 0){const{onAddEvent:i,onDeleteEvent:n,onClearEvent:o}=e;super();g(this,Ue,void 0);g(this,Ai,void 0);p(this,"onAddEvent");p(this,"onDeleteEvent");p(this,"onClearEvent");f(this,Ue,new wn(r)),this.onAddEvent=i,this.onDeleteEvent=n,this.onClearEvent=o,f(this,Ai,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,Ai).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,Ai).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,Ai).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,Ai=new WeakMap;class ff extends gf{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 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};let oh=class{constructor(s){p(this,"all");p(this,"active");this.all=new ff(s),this.active=new ff(s)}};oh=ZM([nt("0600")],oh);var eO=Object.defineProperty,tO=Object.getOwnPropertyDescriptor,sO=(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&&eO(t,e,i),i};const Sf=(kS=class{constructor(s,t,e,r){p(this,"plugins");g(this,Mi,void 0);g(this,Io,void 0);g(this,Oi,void 0);f(this,Oi,s),this.plugins=t,f(this,Mi,e),f(this,Io,r),this.setupEvents()}get telemetry(){return a(this,Oi).getValue("telemetry")}get logger(){return a(this,Oi).getValue("logger")}static async init(s,t,e,r,i){const n=s.getValue("logger"),o=new oh(n);return t.forEach(c=>{const d=new to(s,c,e,r);o.all.add(d)}),new Sf(s,o,e,i)}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,Oi).getValue("peerSessionStore").onAsync(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{var e,r;((r=(e=this.plugins.active)==null?void 0:e.toArray())!=null?r:[]).forEach(i=>{i.deactivateForSelf()});try{await a(this,Io).refresh(a(this,Mi).name)}catch(i){this.logger.error("[PluginController] Failed to refresh active plugins store, syncing from stale data.",{error:i})}const t=a(this,Mi).getAll();Object.entries(t).forEach(([i,n])=>{if(!n)return;const o=this.plugins.all.get(i);if(!o){this.logger.warn(`[PluginController] Plugin '${i}' not found in plugins.all, ignoring store entry.`);return}o.active||(o.enabledBy=n.enabledBy,o.activateForSelf())}),this.logger.debug("[SOCKET_SERVICE_ROOM_JOINED] resolved request to sync active plugins.")}),a(this,Mi).subscribe("*",s=>{Object.entries(s).forEach(([t,e])=>{const r=this.plugins.all.get(t);if(!r){this.logger.warn(`[PluginController] 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())})})}},Mi=new WeakMap,Io=new WeakMap,Oi=new WeakMap,kS);let vf=Sf;sO([E.trace("PluginController.setupEvents")],vf.prototype,"setupEvents",1);class rO{constructor(t){p(this,"mediaJoined");p(this,"socketJoined");p(this,"socketJoinAttempted");p(this,"mediaJoinAttempted");p(this,"socketState");p(this,"mediaState");g(this,Ao,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,Ao,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,Ao).getValue("peerSessionStore").emit(_.SOCKET_STATE_UPDATE,r),this.socketState=r)}}Ao=new WeakMap;var iO=Object.defineProperty,nO=Object.getOwnPropertyDescriptor,so=(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};let pi=(RS=class extends Dt{constructor(t,e){const r=t.getValue("logger");super(r);g(this,zn);g(this,Jn,void 0);g(this,Kn,void 0);p(this,"recordingPeerIds",[]);p(this,"recordings",[]);f(this,Kn,t),f(this,Jn,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,Kn).getValue("telemetry")}updateRecordings(t){this.recordings=t,this.emit("recordingUpdate",this.recordingState)}async start(t){if(!a(this,Jn).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=Pt(),{recording:r={}}=a(this,Kn).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 $(this,zn,Xl).call(this,"stop",["RECORDING","PAUSED"],t)}async pause(t){await $(this,zn,Xl).call(this,"pause",["RECORDING"],t)}async resume(t){await $(this,zn,Xl).call(this,"resume",["PAUSED"],t)}},Jn=new WeakMap,Kn=new WeakMap,zn=new WeakSet,Xl=async function(t,e,r){if(!a(this,Jn).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 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 C("Error while stopping recording","1000",this.logger)}})},RS);so([E.trace("Recording.start")],pi.prototype,"start",1),so([E.trace("Recording.stop")],pi.prototype,"stop",1),so([E.trace("Recording.stop")],pi.prototype,"pause",1),so([E.trace("Recording.stop")],pi.prototype,"resume",1),pi=so([nt("1000")],pi);var aO=Object.defineProperty,oO=Object.getOwnPropertyDescriptor,cO=(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 Tf{constructor(t,e,r){p(this,"recording");p(this,"room");g(this,Di,void 0);f(this,Di,t),this.recording=new pi(t,e),this.room=r,this.setupEvents()}get telemetry(){return a(this,Di).getValue("telemetry")}get logger(){return a(this,Di).getValue("logger")}getRecordingTypeFromProtoType(t){let e;switch(t){case ui.BROWSER:e="BROWSER";break;case ui.COMPOSITE:e="COMPOSITE";break;case ui.TRACK:e="TRACK";break;default:e="BROWSER"}return e}setupEvents(){a(this,Di).getValue("peerSessionStore").on(_.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(x.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(x.recordingPaused,t=>{const e=[...this.recording.recordings];e.forEach(r=>{r.id===t.recordingId&&(r.state="PAUSED")}),this.recording.updateRecordings(e)}),this.room.on(x.recordingStopped,t=>{const e=[...this.recording.recordings.filter(r=>r.id!==t.recordingId)];this.recording.updateRecordings(e)})}}Di=new WeakMap,cO([E.trace("RecordingController.setupEvents")],Tf.prototype,"setupEvents",1);class dO{constructor(t){g(this,Ni,void 0);f(this,Ni,t)}hasFeature(t){return a(this,Ni).getValue("logger").warn("Unimplemented method: meeting.__internals__.hasFeature called"),!1}getFeatureValue(t){return a(this,Ni).getValue("logger").warn("Unimplemented method: meeting.__internals__.getFeatureValue called"),null}getAllFeatures(){return a(this,Ni).getValue("logger").warn("Unimplemented method: meeting.__internals__.getAllFeatures called"),{}}}Ni=new WeakMap;class ch{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=ge,this.callStats=i}static init(t){return new ch(t.getValue("authToken"),t.getValue("logger"),new dO(t),t.getValue("callstats"))}}class dh{constructor(t){p(this,"internals");this.internals=t}static async init(t){const e=ch.init(t);return new dh(e)}}var lO=Object.defineProperty,uO=Object.getOwnPropertyDescriptor,Lt=(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 _t extends wn{constructor(e,r,i=Md,n=!0){const o=e.getValue("logger");super(o);g(this,He,void 0);g(this,Te,void 0);g(this,pe,void 0);g(this,or,void 0);g(this,Zt,void 0);g(this,Mo,void 0);g(this,Oe,void 0);p(this,"audioUpdateInProgress");p(this,"videoUpdateInProgress");f(this,Oe,e),this.audioUpdateInProgress=!1,this.videoUpdateInProgress=!1,f(this,He,new kf(e,r)),f(this,Te,new BO(e,a(this,He),void 0,i)),f(this,pe,new JO(e,a(this,He),void 0,i)),f(this,Zt,new jO(a(this,Oe),a(this,He))),f(this,or,new HO(e,a(this,He))),f(this,Mo,n),a(this,Te).on("trackMuted",this.onAudioTrackMuted.bind(this)),a(this,Te).on("trackChanged",this.onAudioTrackChanged.bind(this)),a(this,pe).on("trackChanged",this.onVideoTrackChanged.bind(this)),a(this,pe).on("trackEnded",this.onVideoTrackEnded.bind(this)),a(this,Zt).on("trackEnded",this.onScreenShareEnded.bind(this)),this.onVisibilityChange=this.onVisibilityChange.bind(this),document.addEventListener("visibilitychange",this.onVisibilityChange)}get telemetry(){return a(this,Oe).getValue("telemetry")}set context(e){f(this,Oe,e)}async onVisibilityChange(){a(this,Oe).getValue("callstats").tabChanged(document.visibilityState==="visible"),document.visibilityState!=="visible"?a(this,Oe).getValue("callstats").browserBackgrounded():(a(this,Oe).getValue("callstats").browserForegrounded(),await this.setupSpeaker())}async repopulateAvailableDevices(){return!0}async setupStreams({audio:e,video:r}){var o;e?a(this,Oe).getValue("callstats").audioOn():a(this,Oe).getValue("callstats").audioOff(),r?a(this,Oe).getValue("callstats").videoOn():a(this,Oe).getValue("callstats").videoOff();let i,n;if(e&&r)try{const c=await a(this,He).getAudioAndVideoTrack(a(this,Te).userSelectedDevice,a(this,pe).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,He).getAudioTrack(!1,a(this,Te).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get audio track",{error:c})}if(!n&&r)try{n=await a(this,He).getVideoTrack(a(this,pe).userSelectedDevice)}catch(c){this.logger.error("LocalMediaHandler::init::Failed to get video track",{error:c})}e&&!i&&a(this,Oe).getValue("callstats").audioOff(),r&&!n&&a(this,Oe).getValue("callstats").videoOff(),await a(this,Te).setMediaTrack(i),await a(this,pe).setMediaTrack(n);try{await this.setupSpeaker()}catch(c){}if(n){const c=await this.getDeviceById(n.getSettings().deviceId);a(this,Oe).getValue("callstats").selectedDevice("VIDEO",c)}if(i){const c=await this.getDeviceById(i.getSettings().deviceId);a(this,Oe).getValue("callstats").selectedDevice("AUDIO",c)}(o=a(this,or).currentDevice)!=null&&o.deviceId&&a(this,Oe).getValue("callstats").selectedDevice("SPEAKER",a(this,or).currentDevice),a(this,He).onDeviceChange((c,d,l)=>{this.onDeviceChange(d,l)})}getCurrentDevices(){return{audio:a(this,Te).currentDevice,video:a(this,pe).currentDevice,speaker:a(this,or).currentDevice}}get permissions(){return a(this,He).permissions}getAllDevices(){return a(this,He).getAvailableDevices()}getDeviceById(e,r){return a(this,He).getDevice(e)}onAudioTrackMuted(){this.emit("AUDIO_TRACK_SILENT")}onAudioTrackChanged(){this.emit("AUDIO_TRACK_CHANGE")}get rawAudioTrack(){return a(this,Te).mediaTrack}get audioTrack(){return a(this,Te).transformedMediaTrack}get audioEnabled(){return a(this,Te).trackEnabled}async enableAudio(e){if(!this.audioUpdateInProgress){this.audioUpdateInProgress=!0;try{e?await a(this,Te).enableTrack(!1,e):await a(this,Te).unmuteTrack()}catch(r){}finally{this.audioUpdateInProgress=!1}}}disableAudio(){a(this,Te).mediaTrack&&!a(this,Te).isCustomTrack?a(this,Te).muteTrack():a(this,Te).disableTrack()}getAudioDevices(e){return a(this,He).getAudioInputDevices(e)}async setAudioDevice(e,{saveDevicePreference:r}){await a(this,Te).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Oe).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,or).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,or).setupSpeaker(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Oe).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,pe).mediaTrack}get videoTrack(){return a(this,pe).transformedMediaTrack}get videoEnabled(){return a(this,pe).trackEnabled}async enableVideo(e){if(!this.videoUpdateInProgress){this.videoUpdateInProgress=!0;try{e?await a(this,pe).enableTrack(!1,e):await a(this,pe).unmuteTrack()}catch(r){}finally{this.videoUpdateInProgress=!1}}}disableVideo(){a(this,pe).disableTrack()}getVideoDevices(e){return a(this,He).getVideoInputDevices(e)}async setVideoDevice(e,{saveDevicePreference:r}){await a(this,pe).setDevice(e,{saveDevicePreference:r}),e!=null&&e.deviceId&&a(this,Oe).getValue("callstats").selectedDevice("VIDEO",e),this.emit("VIDEO_TRACK_CHANGE"),this.emit("DEVICE_CHANGE",{device:e})}async updateVideoConstraints(e){await a(this,pe).updateConstraints(e)}onScreenShareEnded(){this.emit("SCREENSHARE_ENDED")}get screenShareTracks(){return{audio:a(this,Zt).audioMediaTrack,video:a(this,Zt).videoMediaTrack}}get screenShareEnabled(){return a(this,Zt).trackEnabled}async enableScreenShare(){await a(this,Zt).enableScreenShare()}async disableScreenShare(){a(this,Zt).disableScreenShare()}async updateScreenshareConstraints(e){await a(this,Zt).updateConstraints(e)}getSpeakerDevices(e){return a(this,He).getAudioOutputDevices(e)}addAudioMiddleware(e){return a(this,Te).addMiddleware(e)}removeAudioMiddleware(e){return a(this,Te).removeMiddleware(e)}removeAllAudioMiddlewares(){return a(this,Te).removeAllMiddlewares()}addVideoMiddleware(e){return a(this,pe).addMiddleware(e)}removeVideoMiddleware(e){return a(this,pe).removeMiddleware(e)}removeAllVideoMiddlewares(){return a(this,pe).removeAllMiddlewares()}setVideoMiddlewareGlobalConfig(e){return a(this,pe).setVideoMiddlewareGlobalConfig(e)}destruct(){a(this,Te).disableTrack(),a(this,pe).disableTrack(),a(this,pe).terminateMiddlewareWebWorker(),a(this,Zt).disableScreenShare(),a(this,He).destruct()}async onDeviceChange(e,r){var n,o;if(this.emit("DEVICE_LIST_UPDATED",e),r||!a(this,Mo))return;let i=!1;(n=e==null?void 0:e.added)==null||n.reverse().forEach(async c=>{var d;c&&!Md(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,Te).disableTrack()}removeVideoTrack(){a(this,pe).disableTrack(),a(this,pe).terminateMiddlewareWebWorker()}async removeDocumentEventListeners(){document.removeEventListener("visibilitychange",this.onVisibilityChange)}}He=new WeakMap,Te=new WeakMap,pe=new WeakMap,or=new WeakMap,Zt=new WeakMap,Mo=new WeakMap,Oe=new WeakMap,Lt([E.trace("MediaHandler.setupStreams")],_t.prototype,"setupStreams",1),Lt([E.trace("MediaHandler.enableAudio")],_t.prototype,"enableAudio",1),Lt([E.trace("MediaHandler.disableAudio")],_t.prototype,"disableAudio",1),Lt([E.trace("MediaHandler.setAudioDevice")],_t.prototype,"setAudioDevice",1),Lt([E.trace("MediaHandler.enableVideo")],_t.prototype,"enableVideo",1),Lt([E.trace("MediaHandler.disableVideo")],_t.prototype,"disableVideo",1),Lt([E.trace("MediaHandler.setVideoDevice")],_t.prototype,"setVideoDevice",1),Lt([E.trace("MediaHandler.updateVideoConstraints")],_t.prototype,"updateVideoConstraints",1),Lt([E.trace("MediaHandler.enableScreenShare")],_t.prototype,"enableScreenShare",1),Lt([E.trace("MediaHandler.disableScreenShare")],_t.prototype,"disableScreenShare",1),Lt([E.trace("MediaHandler.updateScreenshareConstraints")],_t.prototype,"updateScreenshareConstraints",1),Lt([E.trace("MediaHandler.destruct")],_t.prototype,"destruct",1),Lt([E.trace("MediaHandler.onDeviceChange")],_t.prototype,"onDeviceChange",1);function Ad(s,t,e){switch(!0){case ge.isChromiumBased():switch(t){case"NotAllowedError":return e.includes("by system")?"SYSTEM_DENIED":s==="screenshare"?"CANCELED":"DENIED";case"NotReadableError":default:return"COULD_NOT_START"}case ge.isSafari():switch(t){case"NotAllowedError":return"DENIED";default:return"COULD_NOT_START"}case ge.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 hO=["virtual","emulator","krisp","solstice conference","teams","loom","zoom","manycam","blackhole","displayport","xsplit","wirecast","vMix","elgato","epiphan","voice changer","voicemod","morphvoxx"];function Md(s){var e,r;const t=(e=s.label)==null?void 0:e.toLowerCase();return((r=ge._bowser)==null?void 0:r.getOSName())==="macOS"&&t.includes("iphone")?!0:hO.some(i=>t==null?void 0:t.includes(i))}async function pO(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),yf=Number.MAX_SAFE_INTEGER===void 0?9007199254740991:Number.MAX_SAFE_INTEGER,Ef=536870912,wf=Ef*2,gO=(s,t)=>e=>{const r=t.get(e);let i=r===void 0?e.size:r<wf?r+1:0;if(!e.has(i))return s(e,i);if(e.size<Ef){for(;e.has(i);)i=Math.floor(Math.random()*wf);return s(e,i)}if(e.size>yf)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()*yf);return s(e,i)},bf=new WeakMap,fO=mO(bf),Od=gO(fO,bf),SO=s=>s.method!==void 0&&s.method==="call",vO=s=>s.error===null&&typeof s.id=="number",Dd=((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(SO(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(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: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=Od(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=Od(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=Od(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=Od(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})}}))})();`),Pf=s=>Dd().clearInterval(s),TO=s=>Dd().clearTimeout(s),_f=(s,t)=>Dd().setInterval(s,t),Cf=Object.freeze(Object.defineProperty({__proto__:null,clearInterval:Pf,clearTimeout:TO,setInterval:_f,setTimeout:(s,t)=>Dd().setTimeout(s,t)},Symbol.toStringTag,{value:"Module"}));class yO{constructor(t){g(this,Vi,void 0);g(this,Oo,void 0);f(this,Oo,t)}get logger(){return a(this,Oo).getValue("logger")}terminateMiddlewareWebWorker(){if(a(this,Vi))try{Pf(a(this,Vi)),f(this,Vi,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:Cf})));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,Vi,_f(l,50))},!1);const h=i.captureStream().getVideoTracks()[0];return Object.defineProperty(h,"originalSettings",{value:e.getSettings()}),h}}Vi=new WeakMap,Oo=new WeakMap;const EO={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}}},wO=[[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=wO,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 PO=O_(),kn=Is(PO.config.media);function _O(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 CO{constructor(t,e){g(this,Li,void 0);g(this,cl,void 0);p(this,"getScreenShareConstraints",()=>{var l,u,h,m,S,y,w,b,R;const t=(l=a(this,Li))==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=(R=(b=t==null?void 0:t.frameRate)==null?void 0:b.ideal)!=null?R: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,Li))==null?void 0:n.audio,i=r!=null&&r.enableStereo?2:1;return ge.isFirefox()||ge.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,Li))==null?void 0:o.video,i=Kb(EO);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,cl,t),f(this,Li,e)}getUpdatedVideoConstraints(t){return t}}Li=new WeakMap,cl=new WeakMap;class lh extends Error{constructor(e,r,i){super(r);p(this,"constraints");p(this,"name");this.name=e,this.constraints=i}}class kO{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 RO=Object.defineProperty,IO=Object.getOwnPropertyDescriptor,ps=(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};let xt=(IS=class extends kO{constructor(t,e){super();g(this,Yn,void 0);g(this,es,void 0);g(this,Ye,void 0);f(this,Ye,t),f(this,es,new CO(t,e)),f(this,Yn,new AbortController)}get telemetry(){return a(this,Ye).getValue("telemetry")}get logger(){return a(this,Ye).getValue("logger")}get constraintsBuilder(){return a(this,es)}async destruct(){var t;(t=a(this,Yn))==null||t.abort()}handlePermissionErrors(t,e){const r=Ad(t,e.name,e.message);return this.permissions[t]=r,a(this,Ye).getValue("peerSessionStore").emit(_.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(R=>R.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(R=>R.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,es).getAudioConstraints(u).audio,video:a(this,es).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 b=y.getVideoTracks()[0];if(this.permissions.audio="ACCEPTED",this.permissions.video="ACCEPTED",b.label.includes("OBS Virtual")){const N=(await this.getVideoInputDevices()).find(U=>U.label.includes("OBS Virtual"));b=await this.getVideoTrack(N.deviceId)}return a(this,Ye).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.audio,kind:"audio"}),a(this,Ye).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,{message:this.permissions.video,kind:"video"}),{audioTrack:w,videoTrack:b}}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(_.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,es).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=Ad("audio",h.name,h.message),S=new lh(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,es).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,Ye).getValue("peerSessionStore").emit(_.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(_.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[S]=(await navigator.mediaDevices.getUserMedia(h)).getVideoTracks();if(e&&typeof m!="boolean"&&typeof m.width=="object"){const{width:y,height:w}=S.getSettings(),{ideal:b}=m.width;S.applyConstraints({width:{ideal:b},height:{ideal:Math.floor(w*b/y)},frameRate:m.frameRate})}return this.logger.info("getUserMediaWithoutTimeout::received_user_media",{constraints:JSON.stringify(h)}),S}catch(h){const m=Ad("video",h.name,h.message),S=new lh(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,es).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,es).getVideoConstraints(n),h=await o(u);return this.permissions.video!=="ACCEPTED"&&(this.permissions.video="ACCEPTED",a(this,Ye).getValue("peerSessionStore").emit(_.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=Ad("video",r.name,r.message),n=new lh(r.name,r.message,e),o={video:!0};if(s_(e,o))throw n;if(i==="COULD_NOT_START")return t(o);throw n}};try{const e=a(this,es).getScreenShareConstraints(),r=await t(e);return this.permissions.screenshare!=="ACCEPTED"&&(this.permissions.screenshare="ACCEPTED",a(this,Ye).getValue("peerSessionStore").emit(_.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 Md(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 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(ge.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,Yn).signal})}}},Yn=new WeakMap,es=new WeakMap,Ye=new WeakMap,IS);ps([E.trace("WebMediaInterface.destruct")],xt.prototype,"destruct",1),ps([E.trace("WebMediaInterface.handlePermissionErrors")],xt.prototype,"handlePermissionErrors",1),ps([E.trace("WebMediaInterface.getAudioAndVideoTrack")],xt.prototype,"getAudioAndVideoTrack",1),ps([E.trace("WebMediaInterface.getAudioTrack")],xt.prototype,"getAudioTrack",1),ps([E.trace("WebMediaInterface.getVideoTrack")],xt.prototype,"getVideoTrack",1),ps([E.trace("WebMediaInterface.getScreenShareTracks")],xt.prototype,"getScreenShareTracks",1),ps([E.trace("WebMediaInterface.getAvailableDevices")],xt.prototype,"getAvailableDevices",1),ps([E.trace("WebMediaInterface.getAvailableDevicesByKind")],xt.prototype,"getAvailableDevicesByKind",1),ps([E.trace("WebMediaInterface.getDevice")],xt.prototype,"getDevice",1),ps([E.trace("WebMediaInterface.onDeviceChange")],xt.prototype,"onDeviceChange",1),xt=ps([nt("1600")],xt);const kf=xt,mi={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}},AO=(s=0)=>new Promise(t=>setTimeout(t,s)),MO=(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):AO().then(d))}return d().then(l=>(i.disconnect(),l),l=>{throw i.disconnect(),l})},OO=typeof AudioContext!="undefined"?AudioContext:null;class uh{constructor(t){p(this,"_AudioContext");p(this,"audioContext");p(this,"_audioContextRefContainers");const e={AudioContext:OO,...t};Object.defineProperties(this,{_AudioContext:{value:e.AudioContext},audioContext:{value:null,writable:!0},_audioContextRefContainers:{value:new Set},AudioContextProvider:{enumerable:!0,value:uh}})}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 Rf=new uh,DO=3,NO=250;function VO(s){const t={},e=Rf.getOrCreate(t);let r=DO;function i(){return r-=1,MO(e,s.srcObject,NO).then(n=>n?r>0?i():!0:!1).catch(()=>!0)}return i().finally(()=>{Rf.release(t)})}async function If(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 VO(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 LO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,Af=(s,t,e,r)=>{for(var i=r>1?void 0:r?xO(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};let Nd=class extends wn{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=>mi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>mi.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(ge.isWebKitBased()&&!(ge.isSafari()&&f_.test(ge.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))}};Af([E.trace("BaseMediaHandler.unmuteTrack")],Nd.prototype,"unmuteTrack",1),Nd=Af([nt("1600")],Nd);const Mf=Nd;var UO=Object.defineProperty,$O=Object.getOwnPropertyDescriptor,hh=(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&&UO(t,e,i),i};const ph="[Realtimekit]nonSilentDeviceLabels";class Vd extends Mf{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 pO(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(mi.getItem(ph,this.logger));if(o!=null&&o.devices.some(l=>l.label===r.label))return r;if(!await If(this.logger,r)){const l=(d=o==null?void 0:o.devices.concat({label:r.label}))!=null?d:[{label:r.label}];return mi.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 If(this.logger,r)){const h=(u=o==null?void 0:o.devices.concat({label:r.label}))!=null?u:[{label:r.label}];return mi.setItem(ph,JSON.stringify({devices:h}),this.logger),this.logger.info("AudioMediaHandler.conditionallyChangeTrack.SuccesfullyChangedTrack"),!0}return this.logger.info("AudioMediaHandler.conditionallyChangeTrack.AnotherSilentTrackFound"),!1}),r}}hh([E.trace("AudioMediaHandler.setTransformedTrack")],Vd.prototype,"setTransformedTrack",1),hh([E.trace("AudioMediaHandler.onTrackEnded")],Vd.prototype,"onTrackEnded",1),hh([E.trace("AudioMediaHandler.conditionallyChangeTrack")],Vd.prototype,"conditionallyChangeTrack",1);const BO=Vd;class FO{constructor(t,e){g(this,xi,void 0);p(this,"currentDevice");p(this,"userPreferredDeviceKey","Realtimekit::speaker::UserDeviceID");p(this,"logger");p(this,"setUserPreferredDevice",t=>mi.setItem(this.userPreferredDeviceKey,t,this.logger));p(this,"getUserPreferredDevice",()=>mi.getItem(this.userPreferredDeviceKey,this.logger));f(this,xi,e),this.logger=t.getValue("logger")}async setPreferredSpeaker(){const t=this.getUserPreferredDevice(),e=await a(this,xi).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,xi)instanceof kf))return;let r=t;if(t||([r]=(await a(this,xi).getAvailableDevicesByKind("audiooutput")).filter(d=>!Md(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){}})}}xi=new WeakMap;const HO=FO;class qO extends wn{constructor(e,r){const i=e.getValue("logger");super(i);p(this,"mediaInterface");p(this,"audioMediaTrack");p(this,"videoMediaTrack");g(this,Do,void 0);f(this,Do,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,Do).getValue("peerSessionStore").emit(_.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)),ge.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")}}Do=new WeakMap;const jO=qO;var GO=Object.defineProperty,WO=Object.getOwnPropertyDescriptor,Ld=(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};class ro extends Mf{constructor(e,r,i,n){super(e,r,i,n);g(this,Qn,void 0);g(this,No,{disablePerFrameCanvasRendering:!1});f(this,Qn,new yO(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,Qn).getTransformedVideoTrack(this.middlewares,this.mediaTrack,a(this,No)),this.emit("trackChanged")}catch(i){this.logger.error("VideoMediaHandler.setTransformedTrack",{error:i}),this.transformedMediaTrack=this.mediaTrack}}async setVideoMiddlewareGlobalConfig(e){f(this,No,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,Qn).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}}Qn=new WeakMap,No=new WeakMap,Ld([E.trace("VideoMediaHandler.setTransformedTrack")],ro.prototype,"setTransformedTrack",1),Ld([E.trace("VideoMediaHandler.setVideoMiddlewareGlobalConfig")],ro.prototype,"setVideoMiddlewareGlobalConfig",1),Ld([E.trace("VideoMediaHandler.onTrackEnded")],ro.prototype,"onTrackEnded",1),Ld([E.trace("VideoMediaHandler.conditionallyChangeTrack")],ro.prototype,"conditionallyChangeTrack",1);const JO=ro,Of=Is(Au()),Zn=class{constructor(t){g(this,vt,void 0);g(this,Ui,void 0);g(this,Vo,void 0);g(this,Xn,void 0);if(!t)throw new C("Could not load preset.","0904");f(this,vt,t.config),f(this,Vo,t.name),f(this,Ui,t.ui||Is(Au().ui)),f(this,Xn,t.permissions.plugins.config)}static fromResponse(t){return new Zn(t)}static default(){return new Zn(Of)}static init(t,e=!0){return!t||e?new Zn(Of):new Zn(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,Ui).designTokens.logo,timer:!0,title:!0,participantCount:!0,changeLayout:!1}}}get pipMode(){return!0}get viewType(){return a(this,vt).viewType}get livestreamViewerQualities(){return a(this,vt).livestreamViewerQualities||[]}get maxVideoStreams(){return a(this,vt).maxVideoStreams}get maxScreenShareCount(){return a(this,vt).maxScreenshareCount}get plugins(){return[]}get disabledPlugins(){return Object.keys(a(this,Xn)).filter(t=>a(this,Xn)[t].disabled)}get designTokens(){return a(this,Ui).designTokens}get configDiff(){return a(this,Ui).configDiff}get isSimulcastEnabled(){var t,e,r,i;return(i=(r=(e=(t=a(this,vt))==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,b,R,N,U,L,F,H,ie,ut;return{audio:{enableStereo:(i=(r=(e=(t=a(this,vt))==null?void 0:t.media)==null?void 0:e.audio)==null?void 0:r.enableStereo)!=null?i:kn.audio.enableStereo,enableHighBitrate:(d=(c=(o=(n=a(this,vt))==null?void 0:n.media)==null?void 0:o.audio)==null?void 0:c.enableHighBitrate)!=null?d:kn.audio.enableHighBitrate},video:{quality:(m=(h=(u=(l=a(this,vt))==null?void 0:l.media)==null?void 0:u.video)==null?void 0:h.quality)!=null?m:kn.video.quality,frameRate:(b=(w=(y=(S=a(this,vt))==null?void 0:S.media)==null?void 0:y.video)==null?void 0:w.frameRate)!=null?b:kn.video.frameRate},screenshare:{quality:(L=(U=(N=(R=a(this,vt))==null?void 0:R.media)==null?void 0:N.screenshare)==null?void 0:U.quality)!=null?L:kn.screenshare.quality,frameRate:(ut=(ie=(H=(F=a(this,vt))==null?void 0:F.media)==null?void 0:H.screenshare)==null?void 0:ie.frameRate)!=null?ut:kn.screenshare.frameRate}}}get name(){return a(this,Vo)}};let mh=Zn;vt=new WeakMap,Ui=new WeakMap,Vo=new WeakMap,Xn=new WeakMap;var KO=Object.defineProperty,zO=Object.getOwnPropertyDescriptor,Df=(s,t,e,r)=>{for(var i=r>1?void 0:r?zO(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&&KO(t,e,i),i};class gh extends Dt{constructor(e,r){const i=e.getValue("logger");super(i);g(this,ea,void 0);p(this,"state","IDLE");p(this,"playbackUrl");p(this,"ingestionCredentials");p(this,"viewerCount");g(this,Lo,void 0);f(this,ea,r),f(this,Lo,e),this.viewerCount=0}get telemetry(){return a(this,Lo).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,ea).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=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 C("Error while starting livestream","1900",this.logger)}}async stop(){if(!a(this,ea).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 Pt().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)}}}ea=new WeakMap,Lo=new WeakMap,Df([E.trace("livestream.start")],gh.prototype,"start",1),Df([E.trace("livestream.stop")],gh.prototype,"stop",1);var YO=Object.defineProperty,QO=Object.getOwnPropertyDescriptor,XO=(s,t,e,r)=>{for(var i=r>1?void 0:r?QO(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&&YO(t,e,i),i};class Nf{constructor(t,e,r){p(this,"livestream");g(this,ta,void 0);g(this,sa,void 0);g(this,cr,void 0);g(this,Os,void 0);f(this,Os,t),f(this,sa,e),this.livestream=new gh(t,e),f(this,cr,r),this.setupEvents()}get logger(){return a(this,Os).getValue("logger")}get telemetry(){return a(this,Os).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,cr).on(x.startedLivestream,async t=>{this.livestream.playbackUrl=t.playbackUrl,this.livestream.setLivestreamState("LIVESTREAMING");try{a(this,sa).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during startedLivestream re-fetch")}}),a(this,cr).on(x.livestreamingInvoked,async t=>{if(t.manualIngest){this.livestream.setLivestreamState("WAITING_ON_MANUAL_INGESTION");try{a(this,sa).permissions.canLivestream&&await this.fetchInitialLivestreamingState()}catch(e){this.logger.error("Error: LivestreamController.fetchLivestream during livestreamingInvoked re-fetch")}}}),a(this,cr).on(x.stoppedLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0,this.livestream.ingestionCredentials=void 0}),a(this,cr).on(x.erroredLivestream,()=>{this.livestream.setLivestreamState("IDLE"),this.livestream.playbackUrl=void 0}),a(this,cr).on(x.roomPeerCount,t=>{this.livestream.viewerCount=t.count,this.livestream.emit("viewerCountUpdate",t.count)}),a(this,Os).getValue("peerSessionStore").on(_.PEER_JOINED_INTERNAL,async t=>{var e;((e=t.flags)==null?void 0:e.hiddenParticipant)===!0&&t.recorderType==="LIVESTREAMER"&&(f(this,ta,t.id),this.livestream.setLivestreamState("LIVESTREAMING"))}),a(this,Os).getValue("peerSessionStore").on(_.PEER_CLOSED,t=>{t.id===a(this,ta)&&(f(this,ta,void 0),this.livestream.setLivestreamState("IDLE"))}),a(this,Os).getValue("peerSessionStore").onAsync(_.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,Os).getValue("peerSessionStore").on(_.SOCKET_SERVICE_ROOM_JOINED,async()=>{try{await this.fetchInitialLivestreamingState()}catch(t){this.logger.error("Error: LivestreamController.fetchLivestream")}})}}ta=new WeakMap,sa=new WeakMap,cr=new WeakMap,Os=new WeakMap,XO([E.trace("LivestreamController.setupEvents")],Nf.prototype,"setupEvents",1);var ZO=Object.defineProperty,eD=Object.getOwnPropertyDescriptor,io=(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};class Rn{constructor({name:t,socketHandler:e,meetingId:r}){g(this,dl);p(this,"name","");g(this,st,{});g(this,qr,"");g(this,jr,void 0);p(this,"rateLimitConfig",{maxInvocations:5,period:1});p(this,"bulkRateLimitConfig",{maxInvocations:5,period:1});p(this,"listeners",{});this.name=t,f(this,jr,e),f(this,qr,r)}async set(t,e,r=!0,i=!1){a(this,st)[t]=e,r&&this.remoteSet(t,e),i&&(this.listeners[t]&&this.listeners[t].forEach(n=>n({[t]:a(this,st)[t]})),this.listeners["*"]&&this.listeners["*"].forEach(n=>n({[t]:a(this,st)[t]})))}remoteSet(t,e){a(this,jr).storeInsertKeys(a(this,qr),this.name,[{key:t,payload:e}])}async bulkSet(t){t.forEach(({key:e,payload:r})=>{a(this,st)[e]=r}),a(this,jr).storeInsertKeys(a(this,qr),this.name,t)}async update(t,e,r=!0){$(this,dl,FS).call(this,t,e,r)}async delete(t,e=!0,r=!1){if(a(this,st)[t]&&delete a(this,st)[t],e)return a(this,jr).storeDeleteKeys(a(this,qr),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,st)[e]&&delete a(this,st)[e]}),a(this,jr).storeDeleteKeys(a(this,qr),this.name,t)}get(t){if(a(this,st)[t])return a(this,st)[t]}getAll(){return a(this,st)}clear(){f(this,st,{})}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,st,t)}}st=new WeakMap,qr=new WeakMap,jr=new WeakMap,dl=new WeakSet,FS=function(t,e,r=!0){let i;const n=a(this,st)[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)},io([Nt(Pn,"rateLimitConfig")],Rn.prototype,"remoteSet",1),io([Nt(Pn,"bulkRateLimitConfig")],Rn.prototype,"bulkSet",1),io([Nt(Pn,"rateLimitConfig")],Rn.prototype,"update",1),io([Nt(Pn,"rateLimitConfig")],Rn.prototype,"delete",1),io([Nt(Pn,"bulkRateLimitConfig")],Rn.prototype,"bulkDelete",1);class tD{constructor(t,e){g(this,xo);g(this,ll);p(this,"stores",new Map);g(this,Gr,void 0);g(this,Wr,"");g(this,Uo,void 0);g(this,Ss,new Map);f(this,Gr,e),f(this,Wr,t.getValue("meetingId")),f(this,Uo,t),$(this,ll,HS).call(this)}create(t,e=!1){if(S_.includes(t)&&!e)throw new C(`'${t}' is a reserved store name.`,"0601");const r=new Rn({name:t,socketHandler:a(this,Gr),meetingId:a(this,Wr)});return a(this,Gr).storeGetKeys(a(this,Wr),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,Gr).storeGetKeys(a(this,Wr),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`))}}Gr=new WeakMap,Wr=new WeakMap,xo=new WeakSet,qh=function(){return a(this,Uo).getValue("peerId")},Uo=new WeakMap,Ss=new WeakMap,ll=new WeakSet,HS=function(){[Ks.storeInsertKeys,Ks.storeGetKeys,Ks.storeDeleteKeys].forEach(t=>{a(this,Gr).on(t,async e=>{var n,o;if(e.pluginId!==a(this,Wr))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===Ks.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===Ks.storeInsertKeys&&r.forEach(({key:c,peerId:d,payload:l})=>{d!==a(this,xo,qh)&&i.set(c,l,!1,!0)}),t===Ks.storeDeleteKeys&&r.forEach(({key:c,peerId:d})=>{d!==a(this,xo,qh)&&i.delete(c,!1,!0)}))})})};function gi(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 sD=Object.defineProperty,rD=Object.getOwnPropertyDescriptor,In=(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 iD=.8,nD=1.2;let Zs=(AS=class extends Dt{constructor(t,e,r,i){const n=t.getValue("logger");super(n);g(this,$i);g(this,Jr);g(this,Bi);g(this,ul);g(this,Fi);g(this,Bo);g(this,pl);g(this,ml);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,ra,void 0);p(this,"supportsRemoteControl",!1);g(this,ia,void 0);p(this,"presetName");g(this,Ft,void 0);g(this,dr,void 0);g(this,$o,void 0);g(this,Kr,new Map);g(this,lr,1);g(this,hl,ku(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>nD&&a(this,lr)===1?(f(this,lr,0),a(this,Ft).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,lr)})):d<iD&&a(this,lr)===0&&(f(this,lr,1),a(this,Ft).getValue("peerSessionStore").emit(_.MAX_SPATIAL_LAYER_CHANGE,{peerId:this.id,maxSpatialLayer:a(this,lr)}))},2e3));f(this,Ft,t);const{id:o,userId:c,displayName:d,device:l,picture:u,isHost:h,flags:m,clientSpecificId:S,stageStatus:y,customParticipantId:w,audioMuted:b,audioTrack:R,videoEnabled:N=!1,videoTrack:U,producers:L,metadata:F}=e;this.id=o,this.userId=c,this.name=d,this.device=l,this.picture=u,this.isHost=h,this.flags=m,this.manualProducerConfig=l_,f(this,ia,y!=null?y:"ON_STAGE"),this.customParticipantId=w!=null?w:S,this.audioEnabled=!b,this.audioTrack=R,this.videoEnabled=N,this.videoTrack=U,this.screenShareTracks={audio:void 0,video:void 0},this.producers=L!=null?L:[],this.presetName=F==null?void 0:F.preset_name,f(this,ra,!1),f(this,dr,r),f(this,$o,i),this.setupEvents(),this.updateVideo=this.updateVideo.bind(this),$(this,Bo,jh).call(this)}get clientSpecificId(){return this.customParticipantId}get stageStatus(){return a(this,ia)}get telemetry(){return a(this,Ft).getValue("telemetry")}setVideoEnabled(t,e=!0){this.videoEnabled=t,e&&(this.logger.info("Participant::setVideoEnabled::videoUpdate",{...gi(this)}),this.emit("videoUpdate",{videoEnabled:this.videoEnabled,videoTrack:this.videoTrack}))}setAudioEnabled(t,e=!0){this.audioEnabled=t,e&&(this.logger.info("Participant::setAudioEnabled::audioUpdate",{...gi(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",$(this,Bo,jh)),a(this,Jr,La)&&(this.on("audioUpdate",$(this,pl,jS)),this.on("screenShareUpdate",$(this,ml,GS)))}async pin(){if(!a(this,Bi,$c))throw new C("Can`t pin participant without joining room","1205");if(!a(this,dr).permissions.pinParticipant)throw new C("You do not have permission to pin participants.","1201");return a(this,$i,Uc).pinPeer(this.id)}async unpin(){if(!a(this,Bi,$c))throw new C("Can`t unpin participant without joining room","1205");if(!a(this,dr).permissions.pinParticipant)throw new C("You do not have permission to unpin participants.","1201");return a(this,$i,Uc).pinPeer(null)}setIsPinned(t,e=!0){var i;f(this,ra,t);const r=t?"pinned":"unpinned";(i=a(this,Fi,Bc))==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,Bi,$c))throw new C("Can`t disable participant audio without joining room","1205");if(a(this,dr).permissions.canDisableParticipantAudio)return a(this,$i,Uc).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,ul,qS))throw new C("Can`t kick participant without joining room","1205");if(a(this,dr).permissions.kickParticipant){await a(this,Ft).getValue("peerSessionStore").emitAsync(_.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,Bi,$c))throw new C("Can`t disable participant video without joining room","1205");if(a(this,dr).permissions.canDisableParticipantVideo)return a(this,$i,Uc).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,$o).getUserPermissions(this.userId)}setStageStatus(t){f(this,ia,t),this.emit("stageStatusUpdate",this)}get isPinned(){return a(this,ra)}registerVideoElement(t){var r,i,n,o;if(!t)return;let e;(i=(r=a(this,Kr).get(t))==null?void 0:r.observer)==null||i.disconnect(),"ResizeObserver"in window&&(e=new ResizeObserver(()=>a(this,hl).call(this,t)),e.observe(t)),a(this,Kr).set(t,{observer:e}),this.updateVideo(t),(o=a(this,Fi,Bc))==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,Fi,Bc))==null||e.removeSource(this.id);return}t.srcObject=void 0,(i=(r=a(this,Kr).get(t))==null?void 0:r.observer)==null||i.disconnect(),a(this,Kr).delete(t),(n=a(this,Fi,Bc))==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"}},ra=new WeakMap,ia=new WeakMap,Ft=new WeakMap,$i=new WeakSet,Uc=function(){return a(this,Ft).getValue("roomNodeClient")},Jr=new WeakSet,La=function(){return a(this,Ft).getValue("audioPlayback")},Bi=new WeakSet,$c=function(){return a(this,Ft).getValue("connectionHandler").mediaJoined},ul=new WeakSet,qS=function(){return a(this,Ft).getValue("connectionHandler").socketJoined},dr=new WeakMap,$o=new WeakMap,Kr=new WeakMap,Fi=new WeakSet,Bc=function(){return a(this,Ft).getValue("pip")},lr=new WeakMap,hl=new WeakMap,Bo=new WeakSet,jh=function(){Array.from(a(this,Kr).keys()).forEach(this.updateVideo)},pl=new WeakSet,jS=function(){var t,e;this.audioEnabled&&this.audioTrack?(t=a(this,Jr,La))==null||t.addParticipantTrack(this.id,this.audioTrack):(e=a(this,Jr,La))==null||e.removeParticipantTrack(this.id)},ml=new WeakSet,GS=function(){var t,e;this.screenShareEnabled&&this.screenShareTracks.audio?(t=a(this,Jr,La))==null||t.addParticipantTrack(`screenshare-${this.id}`,this.screenShareTracks.audio):(e=a(this,Jr,La))==null||e.removeParticipantTrack(`screenshare-${this.id}`)},AS);In([E.trace("Participant.disableAudio")],Zs.prototype,"disableAudio",1),In([E.trace("Participant.kick")],Zs.prototype,"kick",1),In([E.trace("Participant.disableVideo")],Zs.prototype,"disableVideo",1),In([E.trace("Participant.getPermissions")],Zs.prototype,"getPermissions",1),In([E.trace("Participant.setStageStatus")],Zs.prototype,"setStageStatus",1),Zs=In([nt("1200")],Zs);class no extends gf{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 aD extends wn{constructor(e){super(e);g(this,zr,void 0);f(this,zr,new Map)}__set(e,r){return a(this,zr).set(e,r)}__clear(){return a(this,zr).clear()}get(e){return a(this,zr).get(e)}toArray(){return Array.from(a(this,zr).values())}}zr=new WeakMap;class oD{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 cD{constructor(){p(this,"_activeSpeakerPeers");p(this,"_compulsoryPeers");this._activeSpeakerPeers=new oD,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 Vf=new cD;var dD=Object.defineProperty,lD=Object.getOwnPropertyDescriptor,Ut=(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};const uD=["ACTIVE_GRID","PAGINATED","MANUAL"];let mt=(MS=class extends Dt{constructor(t,e,r){const i=t.getValue("logger");super(i);g(this,Fo);g(this,Hi);g(this,na);p(this,"waitlisted");p(this,"joined");p(this,"active");p(this,"videoSubscribed");p(this,"audioSubscribed");p(this,"pinned");p(this,"all");g(this,Ce,void 0);g(this,qi,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",Vf);f(this,Ce,t),f(this,qi,e),f(this,kt,r),this.waitlisted=new no(i),this.joined=new no(i),this.videoSubscribed=new no(i),this.audioSubscribed=new no(i),this.active=this.videoSubscribed,this.pinned=new no(i),this.all=new aD(i),this.viewMode="ACTIVE_GRID",this.currentPage=0,this.setupEvents()}get pip(){return a(this,Ce).getValue("pip")}get rateLimits(){return this.rateLimitConfig}updateRateLimits(t,e){this.rateLimitConfig.maxInvocations=t,this.rateLimitConfig.period=e}get telemetry(){return a(this,Ce).getValue("telemetry")}setupEvents(){a(this,Ce).getValue("peerSessionStore").on(_.E2EE_ACTIVE_CONSUMER,({peerId:e})=>{var r;((r=a(this,Ce).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,Ce).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,Ce))==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,Ce).setValue("maxPreferredStreams",t),a(this,na,Zl)&&a(this,Ce).getValue("peerSessionStore").emit(_.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,Hi,Fc))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,Hi,Fc))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=>uD.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,Ce).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="ACTIVE_GRID"?(this.currentPage=0,a(this,Ce).getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{viewMode:t,page:this.currentPage})):t==="MANUAL"&&(this.currentPage=0,a(this,Ce).getValue("peerSessionStore").emit(_.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,Ce).getValue("peerSessionStore").emit(_.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,Ce).getValue("peerSessionStore").emit(_.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,Ce).getValue("peerSessionStore").emit(_.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,na,Zl))throw new C("Can`t disable all audio without joining room","1205");if(a(this,qi).permissions.canAllowParticipantAudio)return a(this,Fo,Gh).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,na,Zl))throw new C("Can`t disable all video without joining room","1205");if(a(this,qi).permissions.canAllowParticipantVideo)return a(this,Fo,Gh).muteAllVideo();throw this.logger.error("Participants::unauthorized_disable_all_video"),new C("Unauthorized: User does not have permission to disable peer video.","1201")}async disableAudio(t){this.joined.get(t).disableAudio()}async disableVideo(t){this.joined.get(t).disableVideo()}async kick(t){await a(this,Ce).getValue("peerSessionStore").emitAsync(_.KICK_PEER,{peerId:t})}async kickAll(){if(this.logger.info("Participants::kick_all"),a(this,Ce).getValue("viewType")!=="LIVESTREAM"&&!a(this,Hi,Fc))throw new C("Can`t kick all without joining room","1205");if(!a(this,qi).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,Hi,Fc))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(er.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()}},Ce=new WeakMap,Fo=new WeakSet,Gh=function(){return a(this,Ce).getValue("roomNodeClient")},Hi=new WeakSet,Fc=function(){var t;return((t=a(this,Ce).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0},na=new WeakSet,Zl=function(){var t;return((t=a(this,Ce).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},qi=new WeakMap,kt=new WeakMap,MS);Ut([E.trace("Participants.setViewMode")],mt.prototype,"setViewMode",1),Ut([E.trace("Participants.setPage")],mt.prototype,"setPage",1),Ut([E.trace("Participants.disableAllAudio")],mt.prototype,"disableAllAudio",1),Ut([E.trace("Participants.disableAllVideo")],mt.prototype,"disableAllVideo",1),Ut([E.trace("Participants.disablePeerAudio")],mt.prototype,"disableAudio",1),Ut([E.trace("Participants.disablePeerVideo")],mt.prototype,"disableVideo",1),Ut([E.trace("Participants.kickPeer")],mt.prototype,"kick",1),Ut([E.trace("Participants.kickAll")],mt.prototype,"kickAll",1),Ut([E.trace("Participants.broadcastMessage"),Nt(Pn,"rateLimitConfig")],mt.prototype,"broadcastMessage",1),Ut([E.trace("Participants.getAllJoinedPeers"),Nt({maxInvocations:10,period:60})],mt.prototype,"getAllJoinedPeers",1),Ut([E.trace("Participant.updatePermissions"),Nt({maxInvocations:1e3,period:60})],mt.prototype,"updatePermissions",1),Ut([E.trace("Participants.getParticipantsInMeetingPreJoin")],mt.prototype,"getParticipantsInMeetingPreJoin",1),mt=Ut([nt("1200")],mt);var hD=Object.defineProperty,pD=Object.getOwnPropertyDescriptor,fi=(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};const Lf=(OS=class{constructor(s,t,e){p(this,"participants");p(this,"self");p(this,"selectedPeers",Vf);p(this,"maxSpatialLayerUpdates",new Map);p(this,"consumerPeerMap");p(this,"events");p(this,"roomSocketHandler");p(this,"context");p(this,"videoPeerConsumerMap",new Map);g(this,ts,{mode:"ACTIVE_GRID",page:0});g(this,vs,!1);g(this,aa,!1);p(this,"updateConsumerSpatialLayers",ku(()=>{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,vs)}`);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 mt(s,t,this.roomSocketHandler),this.self=t,this.consumerPeerMap=new Map,this.events=us,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(x.getWaitingRoomRequests,this.waitingRoomRequestHandler.bind(this)),this.context.getValue("peerSessionStore").on(_.SOCKET_PEERS,async s=>{s==null||s.forEach(t=>{t.waitlisted||this.onParticipantSocketJoined(this.createParticipantObjFromSocketPeer(t))})}),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(_.UPDATE_ACTIVE,{createAllConsumers:!0})}),this.context.getValue("peerSessionStore").on(_.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(_.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,vs)}, 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(_.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(_.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(_.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,vs)}, 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 Zs(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,ts).mode!==s&&(a(this,ts).mode=s),e&&a(this,ts).page!==e&&(a(this,ts).page=e);const{mode:r,page:i}=a(this,ts);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,ts))==null?void 0:e.mode)==="PAGINATED"&&!a(this,vs)?200:0;this.logger.info(`scheduleSyncConsumers():: Source: ${s}, ViewMode: ${(r=a(this,ts))==null?void 0:r.mode}, ConsumersSyncing: ${a(this,vs)}, Delay: ${t}, Page: ${(i=a(this,ts))==null?void 0:i.page}`),setTimeout(()=>this.syncConsumers(),t)}async syncConsumers(){var o,c,d,l,u;if(((d=(c=(o=this.context.getValue("connectionHandler"))==null?void 0:o.mediaState)==null?void 0:c.recv)==null?void 0:d.state)!=="connected"){this.logger.info("syncConsumers: Connection not ready, exiting.");return}if(a(this,vs)){f(this,aa,!0),this.logger.info("syncConsumers: Sync in progress, marking resyncRequired=true and exiting.");return}this.logger.info("syncConsumers: Starting sync operation."),f(this,vs,!0),f(this,aa,!1);let s=[];this.participants.videoSubscribed.forEach(h=>{var y,w;const m=this.participants.joined.get(h.id),S=(w=(y=h.producers)==null?void 0:y.filter(b=>b.kind==="video"))!=null?w:[];m&&(S!=null&&S.length)&&S.forEach(b=>{var U,L,F,H;const R=((L=(U=m.manualProducerConfig)==null?void 0:U.video)!=null?L:!0)&&b.kind==="video"&&!b.screenShare,N=((H=(F=m.manualProducerConfig)==null?void 0:F.screenshareVideo)!=null?H:!0)&&b.kind==="video"&&b.screenShare;(R||N)&&(b.pause||s.push(b))})}),this.participants.audioSubscribed.forEach(h=>{var y,w;const m=this.participants.joined.get(h.id),S=(w=(y=h.producers)==null?void 0:y.filter(b=>b.kind==="audio"))!=null?w:[];m&&(S!=null&&S.length)&&S.forEach(b=>{var U,L,F,H;const R=((L=(U=m.manualProducerConfig)==null?void 0:U.audio)!=null?L:!0)&&b.kind==="audio"&&!b.screenShare,N=((H=(F=m.manualProducerConfig)==null?void 0:F.screenshareAudio)!=null?H:!0)&&b.kind==="audio"&&b.screenShare;(R||N)&&s.push(b)})}),s=d_(s,h=>h.producerId);const t=new Map;s.forEach(h=>{t.set(h.producerId,h)});const e=(l=this.roomNodeClient)==null?void 0:l.getConsumers(),r=s.filter(h=>!(e!=null&&e.has(h.producerId))),i=[];let n=Array.from((u=e==null?void 0:e.values())!=null?u:[]).map(h=>h.peerId);n=c_(n),n==null||n.forEach(h=>{var S;const m=this.participants.joined.get(h);if(!m){this.logger.warn(`Peer with ${h} doesn't exist in joined list but producers of it are being consumed.`);return}(S=m.producers)!=null&&S.length&&m.producers.forEach(y=>{const w=y.consumer&&e.has(y.consumer.id);!t.has(y.producerId)&&(e.has(y.producerId)||w)&&i.push(y)})}),this.logger.info(`syncConsumers: Computed changes - AddProducers: ${r.length} [${r.map(h=>h.producerId).join(", ")}], RemoveProducers: ${i.length} [${i.map(h=>h.producerId).join(", ")}]`.substring(0,5e3));try{r.length>0||i.length>0?(this.logger.info(`syncConsumers: Calling updateConsumers with changes. Adding ${r.length} and removing ${i.length}.`),await this.updateConsumers(r,i),this.logger.info("syncConsumers: updateConsumers completed successfully.")):this.logger.info("syncConsumers: No changes needed, skipping updateConsumers.")}catch(h){this.logger.error("syncConsumers: updateConsumers failed with error.",{error:h})}finally{this.logger.info("syncConsumers: Setting consumersSyncing=false and completing sync."),f(this,vs,!1)}a(this,aa)&&(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=Lf.formatSocketPeerMessage(s);return new Zs(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===Ws.AUDIO&&!r.screenShare?e.setAudioEnabled(!r.pause):r.kind===Ws.VIDEO&&!r.screenShare&&(e.setVideoEnabled(!r.pause),this.updatePipSource(e.id,!r.pause)),e.producers.push({...r,producingTransportId:r.producingTransportId,kind:r.kind===Ws.AUDIO?"audio":"video",producingPeerId:s,mimeType:r.mimeType})}),this.logger.info(`onParticipantMediaJoined: Emitting UPDATE_ACTIVE for peer ${s}`),this.context.getValue("peerSessionStore").emit(_.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(x.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(x.leaveRoom,s=>{const{peerId:t}=s.peer;this.selectedPeers.delete(t,this.context),this.onParticipantLeave(t)}),this.context.getValue("peerSessionStore").on(_.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(_.SOCKET_SERVICE_DISCONNECTED,()=>{this.participants.joined.clear(),this.participants.videoSubscribed.clear(),this.participants.audioSubscribed.clear(),this.participants.pinned.clear(),this.participants.currentPage=0,this.participants.viewMode="ACTIVE_GRID",this.participants.emit("viewModeChanged",{viewMode:"ACTIVE_GRID",currentPage:this.participants.currentPage,pageCount:this.participants.pageCount})}),this.context.getValue("peerSessionStore").on(_.CONSUMER_PAUSED,({id:s})=>{this.processConsumerPaused(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_RESUMED,({id:s})=>{this.processConsumerResumed(s)}),this.context.getValue("peerSessionStore").on(_.NEW_CONSUMER,({id:s})=>{this.processNewConsumer(s)}),this.context.getValue("peerSessionStore").on(_.CONSUMER_CLOSED,({id:s})=>{this.processConsumerClosed(s)}),this.context.getValue("peerSessionStore").on(_.ROOM_MESSAGE,async({payload:s,type:t,timestamp:e})=>{this.participants.emit("broadcastedMessage",{type:t,payload:s,timestamp:e})}),this.context.getValue("peerSessionStore").on(_.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(_.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(_.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(_.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(_.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,ts).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(_.UPDATE_STAGE_REQUESTS,{request:{displayName:s.name,userId:s.userId,peerId:s.id},add:!0})),this.context.getValue("peerSessionStore").emit(_.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(_.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(_.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(_.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(_.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(_.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(_.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(_.E2EE_ACTIVE_CONSUMER,{peerId:t,rtpReceiver:c,track:i})}static formatSocketPeerMessage(s){var e,r,i,n,o,c;if(!s)return;const t=nh(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(_.UPDATE_ACTIVE,{viewMode:this.participants.viewMode,page:this.participants.currentPage})}},ts=new WeakMap,vs=new WeakMap,aa=new WeakMap,OS);let er=Lf;fi([E.trace("ParticipantController.setupEvents")],er.prototype,"setupEvents",1),fi([E.trace("ParticipantController.setupEvents")],er.prototype,"setupEventsGlobal",1),fi([E.trace("ParticipantController.processMedia")],er.prototype,"processMedia",1),fi([E.trace("ParticipantController.processConsumerClosed")],er.prototype,"processConsumerClosed",1),fi([E.trace("ParticipantController.processConsumerResumed")],er.prototype,"processConsumerResumed",1),fi([E.trace("ParticipantController.processConsumerPaused")],er.prototype,"processConsumerPaused",1),fi([E.trace("ParticipantController.processNewConsumer")],er.prototype,"processNewConsumer",1);const Se=Is(Au().permissions),da=class extends Dt{constructor(e,r,i,n=!1){const o=e.getValue("logger");super(o);g(this,Tt);g(this,j,void 0);g(this,oa,void 0);g(this,ca,void 0);g(this,gl,e=>{var l,u,h;const{chat:r,connectedMeetings:i,plugins:n,polls:o,media:c,...d}=e;if(r&&(r.private&&br(a(this,j).chat.private,r.private),r.public&&br(a(this,j).chat.public,r.public),this.emit("chatUpdate")),i&&br(a(this,j).connectedMeetings,i),c){const m=y=>{switch(y){case _r.NONE:return q.Allowed;case _r.ALLOWED:return q.Allowed;case _r.NOT_ALLOWED:return q.NotAllowed;case _r.CAN_REQUEST:return q.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)}),br(a(this,j).media,S)}n&&(br(a(this,j).plugins,n),this.emit("pluginsUpdate")),o&&(br(a(this,j).polls,o),this.emit("pollsUpdate")),Object.keys(d).length!==0&&br(a(this,j),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,ca,e),f(this,oa,i),f(this,j,r),n&&this.setupEvents()}setupEvents(){a(this,ca).getValue("peerSessionStore").on(_.UPDATE_PERMISSIONS,a(this,gl))}static fromResponse(e,r,i){return new da(i,e,r,!0)}static default(e,r){return new da(e,Se,r)}static init(e,r,i){let n;return i?n=new da(e,i,r,!0):n=new da(e,Se,r),n}get mediaRoomType(){return"CF"}get stageEnabled(){var e;return((e=a(this,j))==null?void 0:e.stageEnabled)||a(this,oa)===qs.Webinar||a(this,oa)===qs.Livestream}get acceptStageRequests(){var e,r;return this.stageEnabled?((e=a(this,j))==null?void 0:e.acceptStageRequests)||((r=a(this,j))==null?void 0:r.canAcceptProductionRequests):!1}get stageAccess(){var e,r,i;return((e=a(this,j))==null?void 0:e.stageAccess)===q.NotAllowed?q.NotAllowed:((r=a(this,j))==null?void 0:r.stageAccess)===q.CanRequest?q.CanRequest:((i=a(this,j))==null?void 0:i.stageAccess)===q.Allowed||a(this,j).media.audio.canProduce===q.Allowed||a(this,j).media.video.canProduce===q.Allowed||a(this,j).media.screenshare.canProduce===q.Allowed?q.Allowed:a(this,j).media.audio.canProduce===q.CanRequest||a(this,j).media.video.canProduce===q.CanRequest||a(this,j).media.screenshare.canProduce===q.CanRequest?q.CanRequest:q.NotAllowed}get acceptWaitingRequests(){var e,r;return(r=(e=a(this,j))==null?void 0:e.acceptWaitingRequests)!=null?r:Se.acceptWaitingRequests}get requestProduceVideo(){var e,r,i;return((i=(r=(e=a(this,j))==null?void 0:e.media)==null?void 0:r.video)==null?void 0:i.canProduce)===q.CanRequest}get requestProduceAudio(){var e,r,i;return((i=(r=(e=a(this,j))==null?void 0:e.media)==null?void 0:r.audio)==null?void 0:i.canProduce)===q.CanRequest}get requestProduceScreenshare(){var e,r,i;return((i=(r=(e=a(this,j))==null?void 0:e.media)==null?void 0:r.screenshare)==null?void 0:i.canProduce)===q.CanRequest}get canAllowParticipantAudio(){var e,r;return(r=(e=a(this,j))==null?void 0:e.disableParticipantAudio)!=null?r:Se.disableParticipantAudio}get canAllowParticipantScreensharing(){var e,r;return(r=(e=a(this,j))==null?void 0:e.canAcceptProductionRequests)!=null?r:Se.canAcceptProductionRequests}get canAllowParticipantVideo(){var e,r;return(r=(e=a(this,j))==null?void 0:e.disableParticipantVideo)!=null?r:Se.disableParticipantVideo}get canDisableParticipantAudio(){return this.canAllowParticipantAudio}get canDisableParticipantVideo(){return this.canAllowParticipantVideo}get kickParticipant(){var e,r;return(r=(e=a(this,j))==null?void 0:e.kickParticipant)!=null?r:Se.kickParticipant}get pinParticipant(){var e,r;return(r=(e=a(this,j))==null?void 0:e.pinParticipant)!=null?r:Se.pinParticipant}get canRecord(){var e,r;return(r=(e=a(this,j))==null?void 0:e.canRecord)!=null?r:Se.canRecord}get waitingRoomType(){var e,r;return(r=(e=a(this,j))==null?void 0:e.waitingRoomType)!=null?r:Se.waitingRoomType}get waitingRoomBehaviour(){var e,r;return(r=(e=a(this,j))==null?void 0:e.waitingRoomType)!=null?r:Se.waitingRoomType}get plugins(){var e,r;return(r=(e=a(this,j))==null?void 0:e.plugins)!=null?r:Se.plugins}get polls(){var e,r;return(r=(e=a(this,j))==null?void 0:e.polls)!=null?r:Se.polls}get produceVideo(){return this.canProduceVideo}get requestProduce(){return a(this,j).media.audio.canProduce===q.CanRequest||a(this,j).media.video.canProduce===q.CanRequest||a(this,j).media.screenshare.canProduce===q.CanRequest}get canProduceVideo(){var r;const e=(r=a(this,j).media.video.canProduce)!=null?r:Se.media.video.canProduce;return this.stageEnabled&&(a(this,Tt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Tt,Gt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,Tt,Gt)==="OFF_STAGE"||a(this,Tt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get produceScreenshare(){return this.canProduceScreenshare}get canProduceScreenshare(){var r;const e=(r=a(this,j).media.screenshare.canProduce)!=null?r:Se.media.screenshare.canProduce;return this.stageEnabled&&(a(this,Tt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Tt,Gt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,Tt,Gt)==="OFF_STAGE"||a(this,Tt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get produceAudio(){return this.canProduceAudio}get canProduceAudio(){var r;const e=(r=a(this,j).media.audio.canProduce)!=null?r:Se.media.audio.canProduce;return this.stageEnabled&&(a(this,Tt,Gt)==="ACCEPTED_TO_JOIN_STAGE"||a(this,Tt,Gt)==="ON_STAGE")&&e===q.CanRequest?q.Allowed:this.stageEnabled&&(a(this,Tt,Gt)==="OFF_STAGE"||a(this,Tt,Gt)==="REQUESTED_TO_JOIN_STAGE")&&e===q.Allowed?q.NotAllowed:e}get chatPublic(){var e,r,i;return(i=(r=(e=a(this,j))==null?void 0:e.chat)==null?void 0:r.public)!=null?i:Se.chat.public}get chatPrivate(){var e,r,i;return(i=(r=(e=a(this,j))==null?void 0:e.chat)==null?void 0:r.private)!=null?i:Se.chat.private}get connectedMeetings(){var e,r;return(r=(e=a(this,j))==null?void 0:e.connectedMeetings)!=null?r:Se==null?void 0:Se.connectedMeetings}get hiddenParticipant(){var e,r;return(r=(e=a(this,j))==null?void 0:e.hiddenParticipant)!=null?r:Se.hiddenParticipant}get showParticipantList(){var e;return(e=a(this,j).showParticipantList)!=null?e:Se.showParticipantList}get canChangeParticipantRole(){var e,r;return(r=(e=a(this,j))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Se.canChangeParticipantPermissions}get canChangeParticipantPermissions(){var e,r;return(r=(e=a(this,j))==null?void 0:e.canChangeParticipantPermissions)!=null?r:Se.canChangeParticipantPermissions}get canChangeTheme(){return!1}get canPresent(){return a(this,j).media.audio.canProduce===q.Allowed||a(this,j).media.video.canProduce===q.Allowed||a(this,j).media.screenshare.canProduce===q.Allowed}get acceptPresentRequests(){return this.acceptStageRequests}get canEditDisplayName(){var e;return(e=a(this,j).canEditDisplayName)!=null?e:!1}get maxScreenShareCount(){return 1}get isRecorder(){return a(this,j).isRecorder}get canSpotlight(){return a(this,j).canSpotlight}get canLivestream(){return a(this,j).canLivestream}get transcriptionEnabled(){return a(this,j).transcriptionEnabled}};let fh=da;j=new WeakMap,oa=new WeakMap,ca=new WeakMap,gl=new WeakMap,Tt=new WeakSet,Gt=function(){return a(this,ca).getValue("stageStatus")};class xf extends Dt{constructor(e,r){super(r);p(this,"localMediaHandler");g(this,Ht,void 0);f(this,Ht,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,Ht).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_ERROR,m):a(this,Ht).getValue("peerSessionStore").emit(_.MEDIA_PERMISSION_UPDATE,m)};if(ge.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,Ht))==null||i.getValue("callstats").mediaPermission("AUDIO",e),(n=a(this,Ht))==null||n.getValue("callstats").mediaPermission("SPEAKER",e);break}case"video":{(o=a(this,Ht))==null||o.getValue("callstats").mediaPermission("VIDEO",e);break}case"screenshare":{(c=a(this,Ht))==null||c.getValue("callstats").mediaPermission("SCREENSHARE",e);break}}}get peerId(){var e;return(e=a(this,Ht))==null?void 0:e.getValue("peerId")}async init(e={},r=!1,i=null){var n,o,c,d,l,u,h;if(ge.init(),i&&f(this,Ht,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(_.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(_.MEDIA_PERMISSION_ERROR,async S=>{const{kind:y,message:w,constraints:b}=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:b,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,Ht,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})}}Ht=new WeakMap;var mD=Object.defineProperty,gD=Object.getOwnPropertyDescriptor,gt=(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};let We=(DS=class extends xf{constructor(t,e,r,i,n){var c;const o=t.getValue("logger");super(t,o);g(this,ur);g(this,Xe);g(this,ha);g(this,$e);g(this,Ho);p(this,"name");p(this,"picture");p(this,"customParticipantId");p(this,"waitlistStatus");g(this,la,void 0);g(this,yt,void 0);g(this,ua,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,pa,new Set);g(this,ma,new Set);f(this,Qe,t),this.userId=e.id,this.name=e.name,this.picture=e.picture,this.customParticipantId=(c=e.customParticipantId)!=null?c:e.clientSpecificId,this.waitlistStatus="none",f(this,yt,r),f(this,la,i),this.hidden=!1,f(this,ua,!1),this.organizationId=e.organizationId,this.supportsRemoteControl=ge.isElectron(),this.device=ge.getDeviceInfo(),this.presetName=n,this.updatePermission(),this.updateVideo=this.updateVideo.bind(this),$(this,Ho,Wh).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,ht).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,S,y,w,b,R;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 We(t,e,r,i,n),u=_O(i.mediaConstraints);br(u,(b=t.getValue("defaults"))==null?void 0:b.mediaConfiguration);const h=(R=t.getValue("defaults"))==null?void 0:R.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",$(this,Ho,Wh));const t=a(this,ha,eu);t&&t.onError(e=>{this.emit("autoplayError",e)}),this.localMediaHandler.on("AUDIO_TRACK_CHANGE",async()=>{if(this.logger.info("Self::setupEvents::AUDIO_TRACK_CHANGE",{...gi(this)}),a(this,$e,je)&&this.audioEnabled)try{await a(this,Xe,ht).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",{...gi(this)}),a(this,$e,je)&&this.rawVideoTrack===void 0)this.logger.info("Self::VIDEO_TRACK_CHANGE::Forcing_disable_video"),this.disableVideo();else if(this.videoEnabled&&a(this,$e,je))try{await a(this,Xe,ht).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,ha,eu))==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,je)){this.logger.error("Self.SCREENSHARE_TRACK_CHANGE.LocalMediaInitialized_WithoutRoomNode");return}if(this.screenShareEnabled)try{await a(this,Xe,ht).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",{...gi(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",{...gi(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,je)&&await a(this,Xe,ht).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!==q.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!==q.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!==q.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,la)}get roomJoined(){var t;return a(this,la).viewType===qs.Livestream&&this.stageStatus!=="ON_STAGE"?((t=a(this,Qe).getValue("connectionHandler"))==null?void 0:t.socketJoined)===!0:a(this,$e,je)}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!==q.NotAllowed&&!(a(this,yt).canProduceAudio===q.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,je)&&this.stageStatus==="ON_STAGE"){if(this.audioTrack)try{await a(this,Xe,ht).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!==q.NotAllowed&&!(a(this,yt).canProduceVideo===q.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,je)&&this.stageStatus==="ON_STAGE")try{await a(this,Xe,ht).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",{...gi(this)})}}async updateVideoConstraints(t){if(!this.localMediaHandler.updateVideoConstraints)throw new C("Unsupported","1102");await this.localMediaHandler.updateVideoConstraints(t)}async enableScreenShare(){if(!a(this,$e,je))throw new C("Can`t enable screenshare without joining room","1105");if(a(this,yt).canProduceScreenshare!==q.NotAllowed&&!(a(this,yt).canProduceScreenshare===q.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,ht).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,je)&&a(this,Xe,ht).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,je)&&await a(this,Xe,ht).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,je)&&await a(this,Xe,ht).disableScreenShare(),this.emit("screenShareUpdate",{screenShareEnabled:this.screenShareEnabled,screenShareTracks:this.screenShareTracks}))}getAllDevices(){return this.localMediaHandler.getAllDevices()}setIsPinned(t,e=!0){var i;f(this,ua,t);const r=t?"pinned":"unpinned";(i=a(this,ur,pn))==null||i.updateSource(this.id,{pinned:t}),e&&this.emit(r,this)}get isPinned(){return a(this,ua)}async pin(){if(!a(this,$e,je))throw new C("Can`t pin participants without joining room","1105");return this.show(),a(this,Xe,ht).pinPeer(this.id)}async unpin(){if(!a(this,$e,je))throw new C("Can`t unpin participants without joining room","1105");return a(this,Xe,ht).pinPeer(null)}async hide(){if(!a(this,$e,je))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,je))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,je)&&await a(this,Xe,ht).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,je)&&await a(this,Xe,ht).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,ha,eu))==null?void 0:t.play()}registerVideoElement(t,e=!1){var r,i;t&&(e?a(this,pa).add(t):a(this,ma).add(t),this.updateVideo(t),e||(i=a(this,ur,pn))==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,ur,pn).removeSource(this.id);return}t.srcObject=void 0,e?a(this,pa).delete(t):(a(this,ma).delete(t),a(this,ur,pn).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,ur,pn))==null||i.enableSource(this.id)}else t.srcObject=void 0,e||(n=a(this,ur,pn))==null||n.disableSource(this.id);t.style.display=this.videoEnabled?"block":"none"}},la=new WeakMap,yt=new WeakMap,ua=new WeakMap,Qe=new WeakMap,ur=new WeakSet,pn=function(){return a(this,Qe).getValue("pip")},Xe=new WeakSet,ht=function(){return a(this,Qe).getValue("roomNodeClient")},ha=new WeakSet,eu=function(){return a(this,Qe).getValue("audioPlayback")},$e=new WeakSet,je=function(){var t;return((t=a(this,Qe).getValue("connectionHandler"))==null?void 0:t.mediaJoined)===!0},pa=new WeakMap,ma=new WeakMap,Ho=new WeakSet,Wh=function(){Array.from(a(this,ma)).forEach(t=>this.updateVideo(t,!1)),Array.from(a(this,pa)).forEach(t=>this.updateVideo(t,!0))},DS);gt([E.trace("Self.cleanupEvents")],We.prototype,"cleanupEvents",1),gt([E.trace("Self.setupEvents")],We.prototype,"setupEvents",1),gt([E.trace("Self.setupTracks")],We.prototype,"setupTracks",1),gt([E.trace("Self.destructMediaHandler")],We.prototype,"destructMediaHandler",1),gt([E.trace("Self.removeDocumentEventListeners")],We.prototype,"removeDocumentEventListeners",1),gt([Xs.executeWithLock({methodName:"meeting.self.enableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.enableAudio")],We.prototype,"enableAudio",1),gt([Xs.executeWithLock({methodName:"meeting.self.enableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.enableVideo")],We.prototype,"enableVideo",1),gt([E.trace("Self.updateVideoConstraints")],We.prototype,"updateVideoConstraints",1),gt([E.trace("Self.enableScreenShare"),Xs.executeWithLock({methodName:"meeting.self.enableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3})],We.prototype,"enableScreenShare",1),gt([E.trace("Self.updateScreenshareConstraints")],We.prototype,"updateScreenshareConstraints",1),gt([Xs.executeWithLock({methodName:"meeting.self.disableAudio",lockName:"Self.toggleAudio",timeout:3e3}),E.trace("Self.disableAudio")],We.prototype,"disableAudio",1),gt([Xs.executeWithLock({methodName:"meeting.self.disableVideo",lockName:"Self.toggleVideo",timeout:3e3}),E.trace("Self.disableVideo")],We.prototype,"disableVideo",1),gt([Xs.executeWithLock({methodName:"meeting.self.disableScreenShare",lockName:"Self.toggleScreenShare",timeout:3e3}),E.trace("Self.disableScreenShare")],We.prototype,"disableScreenShare",1),gt([E.trace("Self.setDevice")],We.prototype,"setDevice",1),We=gt([nt("1100")],We);class Sh extends Error{constructor(t){super(t!=null?t:"AwaitQueue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Sh)}}class vh extends Error{constructor(t){super(t!=null?t:"AwaitQueue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,vh)}}class Th{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 Sh);this.stopping=!1}remove(t){const e=Array.from(this.pendingTasks.values())[t];e&&e.reject(new vh)}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 fD(s,t){const e=new Error(t);return e.name=s,e}class ao extends Error{constructor(t){super(t),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,ao):this.stack=new Error(t).stack}}class Ct extends Error{constructor(t){super(t),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ct):this.stack=new Error(t).stack}}class Or extends Error{constructor(t){super(t),this.name="TransportConnectionError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,Ct):this.stack=new Error(t).stack}}const Uf=s=>new Promise(t=>setTimeout(t,s));async function $f(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 Uf(o*(c+1)):i==="exponential"&&await Uf(o*(c+Math.max(0,c-1)));else break}c+=1}return r(d)})}function SD(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 xd(s){return{codecs:SD(s.codecs),headerExtensions:vD(s.headerExtensions?s.headerExtensions:[])}}function TD(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:xd(t),video:xd(e)};return{sender:{audio:xd(r),video:xd(i)},receiver:n}}class yD{constructor(t){g(this,Ze,void 0);p(this,"events");f(this,Ze,t),this.events=us}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:jC.toBinary(n),timeout:5e3})).payload}async connectTransport(t){const e=(await a(this,Ze).sendMessagePromise(this.events.createWebRTCTransport,vC.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,nk.toBinary(t))).payload,r=Fk.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,ZC.toBinary(t))).payload,{consumerIdsMap:{map:r},description:i}=$k.fromBinary(e);return{consumerStateMap:r,sessionDescription:i}}async closeProducer(t){const e=(await a(this,Ze).sendMessagePromise(this.events.closeProducer,hk.toBinary(t))).payload,{description:r}=Kk.fromBinary(e);return r}async closeConsumer(t){return(await a(this,Ze).sendMessagePromise(this.events.closeConsumer,mk.toBinary(t))).payload}async updateConsumersSimulcastConfig(t){return(await a(this,Ze).sendMessagePromise(this.events.updateConsumersSimulcastConfig,rk.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,yk.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,Ze).sendMessagePromise(this.events.hostControlAllPeers,wk.toBinary(e))).payload;if(!r)return!1;const{status:i}=rR.fromBinary(r);return i==="success"}async kickAll(){const t={propagateKickAcrossRooms:!1};a(this,Ze).sendMessagePromise(x.kickAll,Mg.toBinary(t))}async kickPeer(t){a(this,Ze).sendMessagePromise(x.kick,Wg.toBinary(t))}async changeDisplayName(t){const e=(await a(this,Ze).sendMessagePromise(this.events.changeDisplayName,vk.toBinary(t))).payload;if(!e)return!1;const{status:r}=nR.fromBinary(e);return r==="success"}async notifySelfJoinComplete(){const t={},e=(await a(this,Ze).sendMessagePromise(this.events.selfJoinComplete,WC.toBinary(t))).payload;return $u.fromBinary(e)}async audioActivity(t){a(this,Ze).sendMessage(this.events.audioActivity,yC.toBinary(t))}}Ze=new WeakMap;var An=(s=>(s.NEW="new",s.CONNECTING="connecting",s.RECONNECTING="reconnecting",s.DISCONNECTED="disconnected",s.CONNECTED="connected",s.FAILED="failed",s.CLOSED="closed",s))(An||{});class Ud extends it.EventEmitter{constructor(e){super();g(this,jo,void 0);f(this,jo,e),this.setMaxListeners(1/0)}get logger(){return a(this,jo).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)}})}}jo=new WeakMap;class yh extends Ud{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 Eh extends yh{static createFactory(t){return()=>new Eh(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 Bf={},$d={},ED={get exports(){return $d},set exports(s){$d=s}},Ff=ED.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(Ff).forEach(function(s){var t=Ff[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=$d,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}})})}}(Bf);var wh=$d,wD=/%[sdv%]/g,bD=function(s){var t=1,e=arguments,r=e.length;return s.replace(wD,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""}})},oo=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)},PD=["v","o","s","i","u","e","p","c","b","t","r","z","a"],_D=["i","c","b","a"],CD=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||PD,r=t.innerOrder||_D,i=[];return e.forEach(function(n){wh[n].forEach(function(o){o.name in s&&s[o.name]!=null?i.push(oo(n,o,s)):o.push in s&&s[o.push]!=null&&s[o.push].forEach(function(c){i.push(oo(n,o,c))})})}),s.media.forEach(function(n){i.push(oo("m",wh.m[0],n)),r.forEach(function(o){wh[o].forEach(function(c){c.name in n&&n[c.name]!=null?i.push(oo(o,c,n)):c.push in n&&n[c.push]!=null&&n[c.push].forEach(function(d){i.push(oo(o,c,d))})})})}),i.join(`\r
|
|
16
16
|
`)+`\r
|
|
17
|
-
`},Pi=Yf,jD=qD,zd=jD,_i=Pi.parse;Pi.parseParams,Pi.parseFmtpConfig,Pi.parsePayloads,Pi.parseRemoteCandidates,Pi.parseImageAttributes,Pi.parseSimulcastStreamList;class Yd extends Ih{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 $;const S=_i(h),y=S.media[S.media.length-1],w=y.rtp.filter(L=>m.some(F=>F.name===L.codec)),P=y.fmtp.filter(L=>w.some(F=>F.payload===L.payload)),C=($=y.rtcpFb)==null?void 0:$.filter(L=>w.some(F=>F.payload===L.payload)),O=w.map(L=>L.payload);return S.media[S.media.length-1].rtp=w,S.media[S.media.length-1].fmtp=P,S.media[S.media.length-1].rtcpFb=C,S.media[S.media.length-1].payloads=O.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 Dh extends Ih{static createFactory(t){return()=>new Dh(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 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 Jd{constructor(e,r){var i;super(e);g(this,qs);g(this,Qo);g(this,kl);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,Yo,void 0);g(this,zi,void 0);g(this,Hs,void 0);g(this,_l,void 0);this.id=r.id,this.localId=r.localId,f(this,Yo,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Hs,!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,U(this,kl,sv).call(this),f(this,_l,e)}get closed(){return a(this,Hs)}get kind(){return this.track.kind}get paused(){return a(this,zi)}close(e,r){a(this,Hs)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,qs,ui)),f(this,Hs,!0),r&&(U(this,Rl,rv).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Hs))throw new Mt("closed");return a(this,Yo).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,qs,ui)),a(this,Hs)){this.logger.error("consumer::pause() | Consumer closed",a(this,qs,ui));return}f(this,zi,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,qs,ui)),a(this,Hs)){this.logger.error("Consumer::resume() | Consumer closed",a(this,qs,ui));return}f(this,zi,!1),this.track.enabled=!0,this.safeEmit("resume")}}Yo=new WeakMap,zi=new WeakMap,Hs=new WeakMap,_l=new WeakMap,qs=new WeakSet,ui=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Qo=new WeakSet,sp=function(){this.logger.debug('Consumer::track "ended" event',a(this,qs,ui)),this.safeEmit("trackended")},kl=new WeakSet,sv=function(){this.track.addEventListener("ended",U(this,Qo,sp).bind(this))},Rl=new WeakSet,rv=function(){try{this.track.removeEventListener("ended",U(this,Qo,sp)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,qs,ui),error:e})}};class JD extends Jd{constructor(e,r){var i,n;super(e);g(this,Kt);p(this,"id");p(this,"localId");g(this,Rs,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,wa,void 0);g(this,Pa,void 0);g(this,Yi,void 0);g(this,ds,!1);g(this,at,void 0);g(this,ii,void 0);g(this,_a,void 0);g(this,Cl,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,ii,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,_a,void 0),f(this,wa,r.stopTracks),f(this,Pa,r.disableTrackOnPause),f(this,Yi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Rs,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Cl,e)}get closed(){return a(this,ds)}get track(){return a(this,at)}get paused(){return a(this,ii)}get maxSpatialLayer(){return a(this,_a)}async close(e){if(a(this,ds))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,Kt,Ns)),f(this,ds,!0),this._destroyTrack(),e===Xd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Rs).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,ds))throw new Mt("closed");return a(this,Rs).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,Kt,Ns)),a(this,ds)&&this.logger.error("Producer::pause() | Producer closed",a(this,Kt,Ns)),f(this,ii,!0),a(this,at)&&a(this,Pa)&&(a(this,at).enabled=!1),a(this,Yi)&&a(this,Rs).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,Kt,Ns)),a(this,ds)){this.logger.error("Producer::resume() | Producer closed",a(this,Kt,Ns));return}f(this,ii,!1),a(this,at)&&a(this,Pa)&&(a(this,at).enabled=!0),a(this,Yi)&&a(this,Rs).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,Kt,Ns)),a(this,ds)){if(e&&a(this,wa))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,Kt,Ns),error:r})}throw new Mt("closed")}else if(e&&e.readyState==="ended")throw new Mt("track ended");if(e===a(this,at)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,Kt,Ns));return}(!a(this,Yi)||!a(this,ii))&&await a(this,Rs).replaceTrack(this.localId,e),this._destroyTrack(),f(this,at,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,ds))throw new Mt("closed");if(this.kind!=="video")throw new go("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Rs).setMaxSpatialLayer(this.localId,e),f(this,_a,e)}async setRtpEncodingParameters(e){if(a(this,ds))throw new Mt("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Rs).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,Kt,Ns)),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,wa)&&a(this,at).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,Kt,Ns),error:r})}}}Rs=new WeakMap,wa=new WeakMap,Pa=new WeakMap,Yi=new WeakMap,ds=new WeakMap,at=new WeakMap,ii=new WeakMap,_a=new WeakMap,Cl=new WeakMap,Kt=new WeakSet,Ns=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Xf(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Oh(s){return Math.random().toString(36).substring(2,2+s)}const Qd=1;function Zf(s){const t=s;return delete t.payload._bolt,t}function KD(s){return s.payload&&Xf(s.payload)}function zD(s){var t,e;return KD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const ka=class extends ot.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");g(this,ni,new Map);g(this,Il,void 0);g(this,Qi,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=ka.createErrorResponse(e,r):n=ka.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=ka.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=ka.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,ni).has(e.id)||a(this,ni).set(e.id,[]);const r=a(this,ni).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,ni).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,ni).delete(e.id);const c=JSON.parse(o);if(!c.payload||!Xf(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(Zf(e)):i.resolve(Zf(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:Oh(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,Il,e),f(this,Qi,e.getValue("logger")),this.channel=r,this.queue=new Map}};let ki=ka;ni=new WeakMap,Il=new WeakMap,Qi=new WeakMap,p(ki,"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:Oh(8),type:"REQUEST",version:Qd}}}}),p(ki,"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(ki,"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:Oh(8),type:"NOTIFY",version:Qd}}}}),p(ki,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Qd}}}));const Xd="transport closed",Ra=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,P,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=GD(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 Ch(m,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(P=h==null?void 0:h.enableStereo)!=null?P:!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(O=>{const $=setTimeout(()=>{m.error("ICE connection timeout - possible firewall blocking WebRTC or TURN unreachable",{transport:{id:this.id,type:this.direction}}),O(!1)},y);this.once("connected",()=>{clearTimeout($),O(!0)}),this.once("disconnect",()=>{clearTimeout($),O(!1)}),this.once("close",()=>{clearTimeout($),O(!1)})}),this.eventsDCReadyPromise=new Promise(O=>{this.eventsDCReadyPromiseResolver=O}),this.handler.on("@connectionstatechange",O=>{O!==this.connectionState&&(this.logger.debug(`connection state changed to ${O}`),this.connectionState=O,O==="connected"&&(this.connected=!0,this.emit("connected")),O==="disconnected"&&(this.connected=!1,this.emit("disconnect")),(O==="failed"||O==="closed")&&(this.connected=!1,this.emit("close")),this.closed||this.safeEmit("connectionstatechange",O))}),this.handler.on("@icecandidate",({candidate:O})=>{this.closed||this.safeEmit("icecandidate",O)}),this.handler.on("dc_open",O=>{let $=this.datachannels.get(O.label);$||($||($=new ki(a(this,Xi),O,O.label,this.serverId),this.datachannels.set(O.label,$)),this.eventsDCFailureTimer=setTimeout(()=>{O.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",O.label))},5e3))}),this.handler.on("datachannel",(O,$)=>{O.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const L=this.datachannels.get(O.label);if(!L){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:O.label,message:$}});return}try{const F=JSON.parse($);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:F.id,count:F.count,chunkIndex:F.chunkIndex,chunk:F.chunk,transprtId:this.serverId}});const Q=L.processMessage(F);if(!Q)return;this.logger.debug(`datachannel message with id:${F.id} on transport:${this.serverId}complete - ${JSON.stringify(Q)}`),this.emit(`datachannel:${O.label}`,L.label,Q)}catch(F){this.logger.error("error parsing message",{error:F})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=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(Xd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(Xd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Mt("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 Mt("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new go("not a sending Transport");if(r.readyState==="ended")throw new Mt("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 Br("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:P,sender:C,mid:O}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:$,producerId:L}=await r({offer:w,kind:n.kind,paused:l?!n.enabled||Object.hasOwn(n,"fakeTracks"):!1,appData:{...h||{},mid:O},codecOptions:c,producingTransportId:this.serverId}),F=await P($);return{producerId:L,localId:F,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 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 Mt("closed");if(this.direction!=="recv")throw new go("not a receiving transport");if(!await this.transportConnectionPromise)throw new Br("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=_i(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=_i(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=_i(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=_i(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=Ra.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ra.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=Ra.setCodecAndFmtpMappings(c,i,n),c=Ra.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=_i(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,P)=>{const C=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,P(y)},5e3),O=(L,F)=>{try{if(L.readyState==="ended")clearTimeout(C),P(y);else{const Q=L;Q.enabled=!0,this.handler.midTransceiverMap.set(F.mid,F);const X=new WD(a(this,Xi),{id:r,localId:F.mid,transceiver:F,track:Q,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:F.receiver,mimeType:m});this.consumers.set(r,X),X.once("close",()=>{this.consumers.delete(X.id),this.handler.midTransceiverMap.delete(F.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",X),clearTimeout(C),w(X)}}catch(Q){this.logger.warn("error while creating consumer:",Q),clearTimeout(C),P(y)}},$=this.unknownTracksMap.get(S);$?(this.logger.info(`track event already received [trackId: ${$.track.id}] [mid: ${$.transceiver.mid}]`),this.unknownTracksMap.delete(S),O($.track,$.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,O))})}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 OD("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 Nh=Ra;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=mp.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,Tr,void 0);g(this,Zi,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,Tr,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=Ah.createFactory(a(this,Tr));break;case"Safari12":this.handlerFactory=Dh.createFactory(a(this,Tr));break;case"Firefox60":this.handlerFactory=Yd.createFactory(a(this,Tr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Yd.createFactory(a(this,Tr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=vn();return new Nh(a(this,Tr),{id:e,...t,handlerFactory:this.handlerFactory})}}Tr=new WeakMap,Zi=new WeakMap;const XD=2e3;class ZD extends ot.EventEmitter{constructor(e,r){super();g(this,Ma);g(this,tc);g(this,Al);g(this,sc);g(this,Ml);g(this,Dl);g(this,Ol);g(this,Nl);g(this,Vl);g(this,rc);g(this,ic);p(this,"context");g(this,Ca,void 0);g(this,pt,void 0);g(this,mt,void 0);g(this,Xo,void 0);g(this,Zo,void 0);g(this,en,void 0);g(this,Ia,void 0);g(this,ec,void 0);g(this,Aa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,tn,void 0);g(this,js,"all");this.context=e,f(this,en,r),f(this,Ca,new QD(e)),f(this,Ia,new xD(r)),f(this,ec,vs),a(this,Ma,lu).mediaState={send:{state:Nn.NEW},recv:{state:Nn.NEW}},Pn(this.context,"forceRelay")&&f(this,js,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,js)}`),U(this,tc,rp).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,Ia)}get sendTransport(){return a(this,pt)}get recvTransport(){return a(this,mt)}get events(){return a(this,ec)}set sendTransportConnectedCallback(e){f(this,Xo,e)}set recvTransportConnectedCallback(e){f(this,Zo,e)}async setupTransports(e){await U(this,Al,iv).call(this,e);let r,i;e.send&&(r=U(this,sc,ip).call(this,a(this,pt)).then(n=>{try{a(this,Xo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=U(this,sc,ip).call(this,a(this,mt)).then(n=>{try{a(this,Zo).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,pt);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,pt).close(),a(this,pt).removeAllListeners(),f(this,pt,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,mt);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,mt))==null||r.close(),(i=a(this,mt))==null||i.removeAllListeners(),f(this,mt,void 0)}U(this,tc,rp).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}Ca=new WeakMap,pt=new WeakMap,mt=new WeakMap,Xo=new WeakMap,Zo=new WeakMap,en=new WeakMap,Ia=new WeakMap,ec=new WeakMap,Aa=new WeakMap,tn=new WeakMap,js=new WeakMap,Ma=new WeakSet,lu=function(){return this.context.getValue("connectionHandler")},tc=new WeakSet,rp=function(){f(this,tn,{send:void 0,recv:void 0})},Al=new WeakSet,iv=async function(e){var o,c,d,l,u,h,m,S;Pn(this.context,"forceRelay")&&f(this,js,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,js)}`);const n=await vt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&U(this,Dl,av).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,js)}),e.recv&&U(this,Ol,ov).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,js)})},sc=new WeakSet,ip=async function(e){const{id:r,serverId:i,direction:n}=e;U(this,Nl,cv).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 Br("Cannot reconnect closed transport");await U(this,Ml,nv).call(this,e)}catch(l){if(l instanceof Br){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}},Ml=new WeakSet,nv=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 Br("Socket is not connected");if(e.connectionState==="closed")throw new Br("Transport is closed");try{await e.connect(n=>U(this,Vl,dv).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,Aa).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Br(n.message):n}},Dl=new WeakSet,av=function(e){var r,i;if(a(this,pt)&&a(this,pt).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,pt))==null?void 0:r.id,serverId:(i=a(this,pt))==null?void 0:i.serverId,type:"send"}});return}f(this,pt,a(this,Ca).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,pt))},Ol=new WeakSet,ov=function(e){var r,i;if(a(this,mt)&&a(this,mt).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,mt))==null?void 0:r.id,serverId:(i=a(this,mt))==null?void 0:i.serverId,type:"recv"}});return}f(this,mt,a(this,Ca).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,mt))},Nl=new WeakSet,cv=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{U(this,ic,ap).call(this,{state:n,direction:r}),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,Aa).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 U(this,rc,np).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 U(this,rc,np).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"))})},Vl=new WeakSet,dv=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?Zs.SUBSCRIBER:Zs.PUBLISHER},producers:[]};return a(this,Ia).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},rc=new WeakSet,np=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,en).isConnected&&a(this,Aa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,js,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,pt)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,mt)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}U(this,ic,ap).call(this,{state:Nn.CONNECTED,direction:e})},ic=new WeakSet,ap=function(e){const{state:r,direction:i}=e;a(this,Ma,lu).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,Ma,lu).mediaState[i]})};class eO{constructor(t,e,r,i,n){g(this,Ll,void 0);g(this,ls,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,Ll,t),f(this,ls,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,ls).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,ls).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,ls).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:Zs.SUBSCRIBER}};return a(this,ls).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,Ok.toBinary(r)),a(this,ls).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,ls).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,ls).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:Zs.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=aC.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,ls).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}Ll=new WeakMap,ls=new WeakMap;class Vh{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return _i(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=Vh.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Zs.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}}}class tO extends ZD{constructor(e,r){super(e,r);g(this,ac);g(this,Ul);g(this,$l);g(this,Bl);g(this,Fl);g(this,sn,void 0);g(this,ai,void 0);g(this,Da,void 0);g(this,nc,void 0);g(this,Gs,void 0);g(this,xl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,yr,[]);g(this,Oa,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,nc,new Vh(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,Da).clear(),f(this,Gs,new eO(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,sn)}get consumers(){return a(this,ai)}get producerIdToConsumerIdMap(){return a(this,Da)}get logger(){return this.context.getValue("logger")}reset(){f(this,sn,new Map),f(this,ai,new Map),f(this,Da,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,U(this,Ul,lv).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,o),U(this,$l,uv).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,xl).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(_.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,sn).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,Oa)||clearTimeout(a(this,Oa)),f(this,yr,a(this,yr).concat(e)),await U(this,ac,op).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Gs))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,Gs).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,ai).keys()))}async switchConsumersToLayer(e,r){a(this,Gs).switchConsumersToLayer(e,r)}}sn=new WeakMap,ai=new WeakMap,Da=new WeakMap,nc=new WeakMap,Gs=new WeakMap,xl=new WeakMap,yr=new WeakMap,Oa=new WeakMap,ac=new WeakSet,op=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,yr).splice(0,a(this,yr).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,U(this,Bl,hv).bind(this),a(this,Gs).negotiate.bind(a(this,Gs)));if(o.forEach(U(this,Fl,pv).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,yr,a(this,yr).concat(d)),f(this,Oa,setTimeout(U(this,ac,op).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(n){}await this.setupTransports({recv:!0})}}},Ul=new WeakSet,lv=function(e){return a(this,nc).create(e)},$l=new WeakSet,uv=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!==Xd){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Zs.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,sn).set(e.id,e)},Bl=new WeakSet,hv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Gs).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Fl=new WeakSet,pv=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,ai).delete(e.id),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:e.id})}),a(this,ai).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(_.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};const Wl=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,Hl);g(this,ql);g(this,oc,void 0);g(this,cc,void 0);g(this,dc,void 0);g(this,Na,void 0);g(this,Va,void 0);g(this,La,void 0);g(this,lc,void 0);g(this,uc,void 0);g(this,xa,void 0);g(this,Ot,void 0);g(this,Cs,void 0);g(this,Is,!1);g(this,rn,0);g(this,nn,0);g(this,Er,[]);g(this,hc,void 0);f(this,Na,t),f(this,Ot,t),f(this,oc,e),f(this,cc,r),f(this,dc,i),f(this,Va,n),f(this,La,o),f(this,lc,c),f(this,uc,d),f(this,xa,l),f(this,hc,u),f(this,Cs,t/2)}get voiceDetected(){return a(this,Is)}processAudioChunk(t){var o,c;const e=U(o=Wl,jl,fv).call(o,t),r=U(c=Wl,Gl,Sv).call(c,t);return U(this,Hl,mv).call(this,e),e/a(this,Cs)>a(this,xa)&&e>a(this,Ot)&&r>a(this,oc)?(f(this,rn,a(this,rn)+1),f(this,nn,a(this,dc)),a(this,rn)>=a(this,cc)&&f(this,Is,!0)):(f(this,rn,0),a(this,nn)>0?f(this,nn,a(this,nn)-1):a(this,Is)&&f(this,Is,!1),a(this,Is)||U(this,ql,gv).call(this,e)),{energy:e,isVoice:a(this,Is)}}reset(){f(this,Is,!1),f(this,rn,0),f(this,nn,0),f(this,Ot,a(this,Na)),f(this,Cs,a(this,Na)/2),f(this,Er,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Ot),backgroundNoiseEnergy:a(this,Cs),energyRatioThreshold:a(this,xa)}}};let So=Wl;oc=new WeakMap,cc=new WeakMap,dc=new WeakMap,Na=new WeakMap,Va=new WeakMap,La=new WeakMap,lc=new WeakMap,uc=new WeakMap,xa=new WeakMap,Ot=new WeakMap,Cs=new WeakMap,Is=new WeakMap,rn=new WeakMap,nn=new WeakMap,Er=new WeakMap,hc=new WeakMap,Hl=new WeakSet,mv=function(t){a(this,Is)?f(this,Ot,a(this,La)*a(this,Ot)+(1-a(this,La))*t):f(this,Ot,a(this,Va)*a(this,Ot)+(1-a(this,Va))*a(this,Cs)),f(this,Ot,Math.max(a(this,lc),Math.min(a(this,uc),a(this,Ot))))},ql=new WeakSet,gv=function(t){if(t<a(this,Ot)*1.2)if(a(this,Er).push(t),a(this,Er).length>a(this,hc)&&a(this,Er).shift(),a(this,Er).length>=10){const e=[...a(this,Er)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,Cs,e[r])}else f(this,Cs,.95*a(this,Cs)+.05*t)},jl=new WeakSet,fv=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Gl=new WeakSet,Sv=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(So,jl),g(So,Gl);class eS{constructor(t){p(this,"RNAudioSampleHandler");g(this,pc,void 0);f(this,pc,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,pc).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()}}pc=new WeakMap;class tS{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,mc,void 0);f(this,mc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,mc).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)}}mc=new WeakMap;class sO{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 rO=60,iO=400,Sc=class{constructor(t,e){g(this,Jl);g(this,Kl);g(this,br,void 0);g(this,wr,void 0);g(this,Pr,void 0);g(this,gc,void 0);g(this,Ua,void 0);g(this,$a,void 0);g(this,oi,void 0);g(this,an,void 0);g(this,Ba,void 0);g(this,on,void 0);g(this,_r,void 0);g(this,Ws,void 0);this.reportRequest=e,f(this,on,t),f(this,$a,new So);const{isReactNative:r}=navigator;f(this,_r,r?new eS(a(this,on)):new tS(a(this,on))),f(this,Ws,r?sO:Lf)}get logger(){return a(this,on).getValue("logger")}set producerId(t){f(this,Pr,t)}set audioTrack(t){f(this,gc,t),a(this,_r)instanceof tS&&(a(this,_r).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Pr)}`),a(this,br)&&a(this,Ws).clearInterval(a(this,br)),f(this,br,a(this,Ws).setInterval(async()=>{var i;if(!a(this,gc)||!a(this,Pr))return;const{energy:t}=U(this,Jl,vv).call(this),e=U(i=Sc,fc,cp).call(i,t);let r=.9;a(this,Ba)!==e&&a(this,Ba)?r=.9:e?r=.3:r=.5,f(this,Ua,(a(this,Ua)||0)*(1-r)+t*r)},rO)),a(this,wr)&&a(this,Ws).clearInterval(a(this,wr)),f(this,wr,a(this,Ws).setInterval(U(this,Kl,Tv).bind(this),iO))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Pr)}`),a(this,br)&&(a(this,Ws).clearInterval(a(this,br)),f(this,br,void 0)),a(this,wr)&&(a(this,Ws).clearInterval(a(this,wr)),f(this,wr,void 0))}catch(t){}a(this,$a).reset(),a(this,_r)instanceof eS&&a(this,_r).stop()}};let vo=Sc;br=new WeakMap,wr=new WeakMap,Pr=new WeakMap,gc=new WeakMap,Ua=new WeakMap,$a=new WeakMap,oi=new WeakMap,an=new WeakMap,Ba=new WeakMap,on=new WeakMap,_r=new WeakMap,Ws=new WeakMap,Jl=new WeakSet,vv=function(){var o;const{samples:t}=a(this,_r),{energy:e,isVoice:r}=a(this,$a).processAudioChunk(t),i=U(o=Sc,zl,yv).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,oi)||i<a(this,oi))&&f(this,oi,i),(!a(this,an)||i>a(this,an))&&f(this,an,i),{energy:(i-a(this,oi))/(a(this,an)-a(this,oi))*10||0,isVoice:r})},fc=new WeakSet,cp=function(t){return t<5},Kl=new WeakSet,Tv=function(t=a(this,Ua)){var r;if(!a(this,Pr)||!t)return;const e={producerId:a(this,Pr),energy:Math.round(t),silent:U(r=Sc,fc,cp).call(r,t)};f(this,Ba,e.silent),this.reportRequest(e)},zl=new WeakSet,yv=function(t){const e=Math.log10(t);return Math.round(e)},g(vo,fc),g(vo,zl);var nO=Object.defineProperty,aO=Object.getOwnPropertyDescriptor,oe=(s,t,e,r)=>{for(var i=r>1?void 0:r?aO(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&&nO(t,e,i),i};class re{constructor(t,e){g(this,ci);g(this,Ql);g(this,Xl);g(this,Zl);g(this,Ec);g(this,eu);g(this,tu);g(this,Ct);g(this,un);g(this,su);g(this,ru);g(this,iu);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,vc,void 0);g(this,Tc,void 0);g(this,gt,void 0);g(this,G,void 0);g(this,Yl,void 0);g(this,kt,void 0);g(this,cn,void 0);g(this,dn,void 0);g(this,ln,void 0);g(this,yc,void 0);g(this,us,null);g(this,kr,void 0);g(this,Rt,void 0);g(this,Nt,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,gt,r),f(this,cn,!1),f(this,G,new tO(t,r)),f(this,kt,a(this,G).events),f(this,kr,new Set),f(this,Rt,new Map),f(this,dn,!1),f(this,ln,new Ch(t.getValue("logger"))),f(this,Nt,new vo(this.context,a(this,G).socketHandler.audioActivity.bind(a(this,G).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,yc,Lu(async()=>{if(!a(this,ci,ja).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,Tc),a(this,vc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.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,ci,ja).mediaJoined}set mediaJoined(t){a(this,ci,ja).mediaJoined=t}reset(){a(this,G).closeAllProducers(),a(this,G).closeAllConsumers(),a(this,Rt).clear(),a(this,kr).clear(),f(this,us,null),a(this,ln).stop(),a(this,G).stopAllTransports(),a(this,G).reset(),f(this,ln,new Ch)}async joinRoom(t,e,r=!1,i=!1,n={}){a(this,ci,ja).mediaJoinAttempted=!0,f(this,cn,!0),r&&this.reset();try{return await a(this,ln).push(()=>U(this,Ql,Ev).call(this,t,e,i,n),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,us)?a(this,us):(f(this,us,(async()=>{try{await U(this,Ec,dp).call(this,t,e,r,i)}catch(n){throw f(this,us,null),n}})()),a(this,us))}getConsumers(){return a(this,G).consumers}getProducers(){return a(this,G).producers}async leaveRoom(){a(this,G).stopAllTransports(),f(this,dn,!1),a(this,ci,ja).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,gt).sendMessagePromise(a(this,kt).leaveRoom,iR.toBinary(t)).then(r=>{var i;(i=WR.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,G).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,G).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,G).closeConsumers(e)}async _shareWebcam(t){var u,h,m,S;const e=Me.WEBCAM,r=U(this,Ct,Qt).call(this,e);if(r){const y=await r;if(a(this,G).producers.has(y)){const w=a(this,G).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=U(this,iu,Cv).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=B1(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,Rt).delete(e)},l=a(this,G).createProducer(i,d);return U(this,un,Kc).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:fe.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,Rt).delete(Me.SCREENSHARE_VIDEO),a(this,Rt).delete(Me.SCREENSHARE_AUDIO)},o=a(this,G).createProducer(i,n);U(this,un,Kc).call(this,Me.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:fe.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,G).createProducer(d,l),U(this,un,Kc).call(this,Me.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 Mt("track undefined");const e=U(this,Ct,Qt).call(this,Me.MIC);if(e){const o=await e;if(a(this,G).producers.has(o)){const c=a(this,G).producers.get(o);if(!c.closed){await c.replaceTrack({track:t}),await this.resumeMic(),a(this,Nt)&&(a(this,Nt).audioTrack=t,a(this,Nt).producerId=o,a(this,Nt).start());return}await a(this,G).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=U(this,ru,Rv).call(this,t),i=()=>{a(this,Rt).delete(Me.MIC)},n=a(this,G).createProducer(r,i);U(this,un,Kc).call(this,Me.MIC,n.then(o=>o.id)),await n.then(o=>{a(this,Nt)&&(a(this,Nt).audioTrack=o.track,a(this,Nt).producerId=o.id,a(this,Nt).start())})}catch(e){throw new k(e)}}async pauseMic(){var i;const t=await U(this,Ct,Qt).call(this,Me.MIC),e=a(this,G).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,Nt))==null||i.stop();const r={producerId:e.id,pause:!0};a(this,gt).sendMessage(a(this,kt).toggleProducer,Cd.toBinary(r))}async pauseWebcam(){const t=await U(this,Ct,Qt).call(this,Me.WEBCAM),e=a(this,G).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,gt).sendMessage(a(this,kt).toggleProducer,Cd.toBinary(r))}async resumeMic(){const t=await U(this,Ct,Qt).call(this,Me.MIC),e=a(this,G).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(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,gt).sendMessage(a(this,kt).toggleProducer,Cd.toBinary(r))}async resumeWebcam(t=Me.WEBCAM){const e=await U(this,Ct,Qt).call(this,t),r=a(this,G).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(_.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,gt).sendMessage(a(this,kt).toggleProducer,Cd.toBinary(i))}async disableWebcam(){const t=Me.WEBCAM,e=await U(this,Ct,Qt).call(this,t);U(this,su,kv).call(this,t),e&&await a(this,G).closeProducer(e)}async disableMic(){var e;const t=await U(this,Ct,Qt).call(this,Me.MIC);t&&await a(this,G).closeProducer(t),(e=a(this,Nt))==null||e.stop(),a(this,Rt).delete(Me.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await U(this,Ct,Qt).call(this,Me.SCREENSHARE_VIDEO),e=await U(this,Ct,Qt).call(this,Me.SCREENSHARE_AUDIO);t&&await a(this,G).closeProducer(t),e&&await a(this,G).closeProducer(e),a(this,kr).clear(),a(this,Rt).delete(Me.SCREENSHARE_VIDEO),a(this,Rt).delete(Me.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await U(this,Ct,Qt).call(this,Me.WEBCAM);await a(this,G).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await U(this,Ct,Qt).call(this,Me.SCREENSHARE_VIDEO);await a(this,G).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,G).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,G).socketHandler.kickPeer(e)}kickAll(){a(this,G).socketHandler.kickAll()}async muteAll(t){if(!await a(this,G).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,G).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,G).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,G).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,gt).sendMessagePromise(a(this,kt).globalPinPeer,vR.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,G).producers.get(t.producerId)&&a(this,kr).add(t.consumerPeerId),a(this,kr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,G).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,gt).on(a(this,kt).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=bC.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===er.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===er.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,gt).on(a(this,kt).peerProducerToggleBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,initiatorParticipantId:r,producerState:{kind:i,pause:n,producerId:o,screenShare:c}}=jg.fromBinary(t);if(c)return;const d=i===er.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(jg.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.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(_.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,gt).on(a(this,kt).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=zu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,kr).delete(e),a(this,G).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,gt).on(a(this,kt).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=_C.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,G).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,G).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,G).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(_.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,gt).on(a(this,kt).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,cn)&&!a(this,dn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,yc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,G).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(_.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,G).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(_.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}vc=new WeakMap,Tc=new WeakMap,gt=new WeakMap,G=new WeakMap,Yl=new WeakMap,kt=new WeakMap,cn=new WeakMap,dn=new WeakMap,ln=new WeakMap,yc=new WeakMap,us=new WeakMap,kr=new WeakMap,Rt=new WeakMap,Nt=new WeakMap,ci=new WeakSet,ja=function(){return this.context.getValue("connectionHandler")},Ql=new WeakSet,Ev=async function(t,e,r,i){f(this,Tc,t);try{a(this,us)?await a(this,us):await U(this,Ec,dp).call(this,t,e,r,i),U(this,Zl,wv).call(this,e);const{joined:n,error:o}=await U(this,Xl,bv).call(this);return{roomJoined:n,error:o}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1,error:n}}finally{f(this,us,null)}},Xl=new WeakSet,bv=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,G).socketHandler.notifySelfJoinComplete();return f(this,vc,t.roomUuid),f(this,dn,!0),f(this,cn,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},Zl=new WeakSet,wv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...fe.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)},Ec=new WeakSet,dp=async function(t,e,r,i){try{const n=U(this,eu,Pv).call(this);await U(this,tu,_v).call(this,t,e,r,n),await a(this,G).setupTransports({send:!0,recv:!0})}catch(n){throw this.logger.error("Failed to initialize connection",{error:n}),n}},eu=new WeakSet,Pv=function(){const t=LD("video/VP8");return f(this,Yl,t),t},tu=new WeakSet,_v=async function(t,e,r,i){await zf(async(n,o)=>{if(!a(this,gt).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,G).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})},Ct=new WeakSet,Qt=function(t){return a(this,Rt).get(t)},un=new WeakSet,Kc=function(t,e){return a(this,Rt).set(t,e)},su=new WeakSet,kv=function(t){return a(this,Rt).delete(t)},ru=new WeakSet,Rv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},iu=new WeakSet,Cv=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},oe([E.trace("MediaNodeClient.reset")],re.prototype,"reset",1),oe([E.trace("MediaNodeClient.joinRoom")],re.prototype,"joinRoom",1),oe([E.trace("MediaNodeClient.leaveRoom")],re.prototype,"leaveRoom",1),oe([E.trace("MediaNodeClient.activatePeers")],re.prototype,"activatePeers",1),oe([E.trace("MediaNodeClient.createConsumers")],re.prototype,"createConsumers",1),oe([E.trace("MediaNodeClient.closeConsumers")],re.prototype,"closeConsumers",1),oe([E.trace("MediaNodeClient._shareWebcam")],re.prototype,"_shareWebcam",1),oe([E.trace("MediaNodeClient.shareWebcam")],re.prototype,"shareWebcam",1),oe([E.trace("MediaNodeClient.shareScreen")],re.prototype,"shareScreen",1),oe([E.trace("MediaNodeClient.shareMic")],re.prototype,"shareMic",1),oe([E.trace("MediaNodeClient.pauseMic")],re.prototype,"pauseMic",1),oe([E.trace("MediaNodeClient.pauseWebcam")],re.prototype,"pauseWebcam",1),oe([E.trace("MediaNodeClient.resumeMic")],re.prototype,"resumeMic",1),oe([E.trace("MediaNodeClient.resumeWebcam")],re.prototype,"resumeWebcam",1),oe([E.trace("MediaNodeClient.disableWebcam")],re.prototype,"disableWebcam",1),oe([E.trace("MediaNodeClient.disableMic")],re.prototype,"disableMic",1),oe([E.trace("MediaNodeClient.disableScreenShare")],re.prototype,"disableScreenShare",1),oe([E.trace("MediaNodeClient.muteSelf")],re.prototype,"muteSelf",1),oe([E.trace("MediaNodeClient.resetVideoProducers")],re.prototype,"resetVideoProducers",1),oe([E.trace("MediaNodeClient.changeDisplayName")],re.prototype,"changeDisplayName",1),oe([E.trace("MediaNodeClient.kickPeer")],re.prototype,"kick",1),oe([E.trace("MediaNodeClient.kickAllPeers")],re.prototype,"kickAll",1),oe([E.trace("MediaNodeClient.muteAll")],re.prototype,"muteAll",1),oe([E.trace("MediaNodeClient.muteAllVideo")],re.prototype,"muteAllVideo",1),oe([E.trace("MediaNodeClient.disableAudio")],re.prototype,"disableAudio",1),oe([E.trace("MediaNodeClient.disableVideo")],re.prototype,"disableVideo",1),oe([E.trace("MediaNodeClient.pinPeer")],re.prototype,"pinPeer",1),oe([E.trace("MediaNodeClient.validateScreenShare")],re.prototype,"validateScreenShare",1);function sS(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 re(s,t);return s.setValue("roomNodeClient",r),r}function oO(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 cO=Object.defineProperty,dO=Object.getOwnPropertyDescriptor,Ri=(s,t,e,r)=>{for(var i=r>1?void 0:r?dO(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};const rS=(jS=class{constructor(s,t,e,r){g(this,Vt);p(this,"self");p(this,"authToken");g(this,Fa,void 0);p(this,"viewType");g(this,As,void 0);g(this,Z,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,Z,s),this.viewType=r,this.authToken=n,f(this,Fa,i),f(this,As,e),this.setupEvents()}get peerId(){return a(this,Z).getValue("peerId")}get telemetry(){return a(this,Z).getValue("telemetry")}get logger(){return a(this,Z).getValue("logger")}get mediaJoined(){return a(this,Z).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=vt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await ze.__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:fe.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:w_(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 rS(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===H.Allowed&&r)try{await a(this,Vt,ps).shareMic(s),this.self.audioEnabled||a(this,Vt,ps).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===H.Allowed&&i)try{await a(this,Vt,ps).shareWebcam(t),this.self.videoEnabled||a(this,Vt,ps).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===H.Allowed&&n)try{await((c=a(this,Vt,ps))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){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,Z).getValue("callstats").callEnded(),a(this,Vt,ps).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,Z).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,Z).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,Fa).updateURL(t),a(this,Z).getValue("telemetry").resetPeerId(t),vt().setHeader("tracing-id",t),Dr.remapContext(t,a(this,Z)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,Z).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,As).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,As).on(Nd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,Z).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,As).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,As).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,As).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,Z).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(_.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,Z).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,Z).getValue("callstats").audioOff())}),a(this,Z).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,Z).getValue("callstats").videoOff())}),a(this,Z).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,Z).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,As).joinRoom(this.self);a(this,As).socket.flush();const e=gh(t.stageType);if(a(this,Z).setValue("stageStatus",e,!1),t.waitlisted){this.waitlistedHandler();return}}catch(t){throw this.logger.error("SelfController.joinRoom: socket join failed",{error:t}),new k("Check the network and try again.","0002")}try{await this.joinMediaRoom(s),a(this,Z).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Br&&t.message==="ice connection failed"?new k("A firewall or network restriction may be blocking the connection.","0014"):new k("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,Z).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,Z).setValue("roomNodeClient",void 0),a(this,Z).notify("stageStatus"),(t=a(this,Z).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,Z).getAllValues();try{if(e===Qs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}sS(a(this,Z),{socket:a(this,Fa),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,Vt,ps))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");i==="ON_STAGE"&&await this.shareMediaTracks(),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,Z).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===Qs.Webinar)&&a(this,Vt,ps)&&(a(this,Vt,ps).mediaJoined&&s!=="disconnected"&&await a(this,Vt,ps).leaveRoom(),!(s==="stageLeft"&&t===Qs.Livestream)&&(a(this,Vt,ps).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()}},Fa=new WeakMap,As=new WeakMap,Z=new WeakMap,Vt=new WeakSet,ps=function(){return a(this,Z).getValue("roomNodeClient")},jS);let Fr=rS;Ri([E.trace("SelfController.resetSelf")],Fr.prototype,"resetSelf",1),Ri([E.trace("SelfController.setupEvents")],Fr.prototype,"setupEvents",1),Ri([E.trace("SelfController.joinRoom")],Fr.prototype,"joinRoom",1),Ri([E.trace("SelfController.leaveRoom")],Fr.prototype,"leaveRoom",1),Ri([E.trace("SelfController.joinMediaRoom")],Fr.prototype,"joinMediaRoom",1),Ri([E.trace("SelfController.leaveMediaRoom")],Fr.prototype,"leaveMediaRoom",1),Ri([E.trace("SelfController.init")],Fr,"init",1);class lO{constructor(t){g(this,bc,void 0);f(this,bc,t)}on(t,e){let r;t===x.roomPeerCount?r=Jg.fromBinary.bind(Jg):r=uf.fromBinary.bind(uf),a(this,bc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const n=r(i);e(n)})}}bc=new WeakMap;class uO{constructor(t,e){g(this,wc,void 0);g(this,Pc,void 0);f(this,wc,e),f(this,Pc,t)}get logger(){return a(this,Pc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=Yu.fromBinary.bind(Yu),i=Yu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,wc).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)})}}wc=new WeakMap,Pc=new WeakMap;var hO=Object.defineProperty,pO=Object.getOwnPropertyDescriptor,Lh=(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};class Zd{constructor(t,e){g(this,Rr,void 0);g(this,Ha,void 0);f(this,Rr,e),f(this,Ha,t)}get logger(){return a(this,Ha).getValue("logger")}get telemetry(){return a(this,Ha).getValue("telemetry")}getPolls(){return a(this,Rr).sendMessagePromise(sr.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,Rr).sendMessage(sr.createPoll,cM.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,Rr).sendMessage(sr.votePoll,lM.toBinary(r))}on(t,e){let r,i;switch(t){case sr.updatePoll:case sr.createPoll:case sr.votePoll:{r=dh.fromBinary.bind(dh),i=dh.create();break}}a(this,Rr).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,Rr).removeListeners(t)}}Rr=new WeakMap,Ha=new WeakMap,Lh([E.trace("PollSocketHandler.getPolls")],Zd.prototype,"getPolls",1),Lh([E.trace("PollSocketHandler.createPoll")],Zd.prototype,"createPoll",1),Lh([E.trace("PollSocketHandler.votePoll")],Zd.prototype,"votePoll",1);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};class iS{constructor(t,e){p(this,"socket");g(this,zt,void 0);f(this,zt,t),this.socket=e,this.handleSocketEvents(),a(this,zt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,zt).getValue("telemetry")}get logger(){return a(this,zt).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(x.joinRoom,e0.toBinary(e));try{const{peer:n}=Rn.fromBinary((await r).payload);a(this,zt).getValue("connectionHandler").socketJoined=!0,a(this,zt).getValue("peerSessionStore").emit(_.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,zt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,zt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return U0.fromBinary((await this.socket.sendMessagePromise(x.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(x.getRoomPeersInfo,jC.toBinary(n));i=Zu.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(x.getRoomPeersInfo);t=Zu.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(x.getRoomPeersInfo);t=Zu.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(x.getPeerInfo,Yg.toBinary({peerId:t}));e=Rn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=zg.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=zg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=sf.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=sf.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(x.broadcastMessage,ao.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(x.broadcastToEntity,ao.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(x.broadcastToEntity,ao.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(x.leaveRoom,s0.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,ef.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,$g.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,j0.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,W0.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Nd.updateUserPreset,EI.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=ao.fromBinary(t);a(this,zt).getValue("peerSessionStore").emit(_.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(x.broadcastToEntity,({payload:t})=>{try{const e=ao.fromBinary(t);a(this,zt).getValue("peerSessionStore").emit(_.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 x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=Rn.fromBinary.bind(Rn),i=Rn.create();break}case x.getWaitingRoomRequests:{r=(n,o)=>n?tf.fromBinary(n,o):{requests:[]},i=tf.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=gf.fromBinary.bind(gf);break}case Nd.updateUserPreset:{r=nf.fromBinary.bind(nf);break}case vs.peerJoinedBroadcast:case Vr.peerJoinedBroadcast:{r=Hg.fromBinary.bind(Hg);break}case vs.selfJoinComplete:case Vr.selfJoinComplete:{r=Ku.fromBinary.bind(Ku);break}case vs.globalPeerPinBroadcast:case Vr.globalPeerPinBroadcast:{r=Gg.fromBinary.bind(Gg);break}case vs.selectedPeer:case Vr.selectedPeer:{r=Ju.fromBinary.bind(Ju);break}case vs.selectedPeerDiff:case Vr.selectedPeerDiff:{r=Fg.fromBinary.bind(Fg);break}case vs.leaveRoom:case Vr.leaveRoom:{r=zu.fromBinary.bind(zu);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(Nd.getUserPresets,mI.toBinary(e)),i=vI.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}}}zt=new WeakMap,fO([E.trace("RoomSocketHandler.joinRoom")],iS.prototype,"joinRoom",1);class SO{constructor(t){g(this,Lt,void 0);f(this,Lt,t)}async getStageRequests(){const{payload:t}=await a(this,Lt).sendMessagePromise(x.getStageRequests);return t?ch.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Lt).sendMessage(x.requestStageAccess)}cancelRequestAccess(){a(this,Lt).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Lt).sendMessage(x.grantStageAccess,XA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Lt).sendMessage(x.denyStageAccess,eM.toBinary(e))}joinStage(){return a(this,Lt).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Lt).sendMessagePromise(x.leaveStage,pf.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Lt).sendMessagePromise(x.leaveStage,pf.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=hf.fromBinary.bind(hf);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=ch.fromBinary.bind(ch);break}case x.peerStageStatusUpdate:{r=Wg.fromBinary.bind(Wg);break}}a(this,Lt).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,Lt).sendMessagePromise(x.getPeerInfo,Yg.toBinary({peerId:t}));return Rn.fromBinary(e.payload)}}Lt=new WeakMap;class vO{constructor(t,e){g(this,We,void 0);g(this,_c,void 0);f(this,We,e),f(this,_c,t)}get logger(){return a(this,_c).getValue("logger")}addPlugin(t,e){a(this,We).sendMessage(j.addPlugin,gA.toBinary({pluginId:t,staggered:e}))}removePlugin(t){a(this,We).sendMessage(j.removePlugin,SA.toBinary({pluginId:t,staggered:!1}))}async getActivePlugins(){const{payload:t}=await a(this,We).sendMessagePromise(j.getPlugins);return t?BA.fromBinary(t):{plugins:[]}}customPluginEventToRoom(t,e,r){const i={pluginId:t,pluginData:new TextEncoder().encode(JSON.stringify(e))};a(this,We).sendMessage(j.customPluginEventToRoom,RA.toBinary(i),r)}customPluginEventToPeers(t,e,r,i){const n={pluginId:t,peerIds:e,pluginData:new TextEncoder().encode(JSON.stringify(r))};a(this,We).sendMessage(j.customPluginEventToPeers,IA.toBinary(n),i)}enablePluginForRoom(t,e){a(this,We).sendMessage(j.enablePluginForRoom,TA.toBinary({pluginId:t}),e)}enablePluginForPeers(t,e,r){a(this,We).sendMessage(j.enablePluginForPeers,wA.toBinary({pluginId:t,peerIds:e}),r)}disablePluginForRoom(t,e){a(this,We).sendMessage(j.disablePluginForRoom,EA.toBinary({pluginId:t}),e)}disablePluginForPeers(t,e,r){a(this,We).sendMessage(j.disablePluginForPeers,_A.toBinary({pluginId:t,peerIds:e}),r)}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,We).sendMessage(j.storeInsertKeys,of.toBinary(n),i)}storeGetKeys(t,e,r,i){const n={pluginId:t,storeName:e,getKeys:r.map(o=>({storeKey:o.key}))};a(this,We).sendMessage(j.storeGetKeys,OA.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,We).sendMessage(j.storeDeleteKeys,VA.toBinary(n),i)}storeDelete(t,e,r){a(this,We).sendMessage(j.storeDelete,xA.toBinary({pluginId:t,storeName:e}),r)}getPluginDataOld(t,e){this.logger.info("getPluginDataOld",{plugin:{id:t,storeName:e}})}storePluginDataOld(t,e,r){const i={pluginId:t,storeName:e,insertKeys:[{storeKey:r.key,payload:new TextEncoder().encode(JSON.stringify(r))}]};a(this,We).sendMessage(j.storeInsertKeys,of.toBinary(i))}on(t,e){let r;switch(t){case j.addPlugin:case j.enablePluginForPeers:case j.enablePluginForRoom:{r=oh.fromBinary.bind(oh);break}case j.removePlugin:case j.disablePluginForPeers:case j.disablePluginForRoom:{r=cf.fromBinary.bind(cf);break}case j.customPluginEventToPeers:case j.customPluginEventToRoom:{r=lf.fromBinary.bind(lf);break}case j.storeInsertKeys:case j.storeGetKeys:case j.storeDeleteKeys:case j.storeDelete:{r=df.fromBinary.bind(df);break}}a(this,We).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}We=new WeakMap,_c=new WeakMap;var TO=Object.defineProperty,yO=(s,t,e)=>t in s?TO(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,EO=(s,t,e)=>(yO(s,typeof t!="symbol"?t+"":t,e),e),xh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},D=(s,t,e)=>(xh(s,t,"read from private field"),e?e.call(s):t.get(s)),Te=(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)=>(xh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),be=(s,t,e)=>(xh(s,t,"access private method"),e),el={},bO={get exports(){return el},set exports(s){el=s}},Vn=typeof Reflect=="object"?Reflect:null,nS=Vn&&typeof Vn.apply=="function"?Vn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},tl;Vn&&typeof Vn.ownKeys=="function"?tl=Vn.ownKeys:Object.getOwnPropertySymbols?tl=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:tl=function(s){return Object.getOwnPropertyNames(s)};function wO(s){console&&console.warn&&console.warn(s)}var aS=Number.isNaN||function(s){return s!==s};function ce(){ce.init.call(this)}bO.exports=ce,el.once=RO,ce.EventEmitter=ce,ce.prototype._events=void 0,ce.prototype._eventsCount=0,ce.prototype._maxListeners=void 0;var oS=10;function sl(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 oS},set:function(s){if(typeof s!="number"||s<0||aS(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");oS=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(s){if(typeof s!="number"||s<0||aS(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 cS(s){return s._maxListeners===void 0?ce.defaultMaxListeners:s._maxListeners}ce.prototype.getMaxListeners=function(){return cS(this)},ce.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")nS(c,this,t);else for(var d=c.length,l=pS(c,d),e=0;e<d;++e)nS(l[e],this,t);return!0};function dS(s,t,e,r){var i,n,o;if(sl(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=cS(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,wO(c)}return s}ce.prototype.addListener=function(s,t){return dS(this,s,t,!1)},ce.prototype.on=ce.prototype.addListener,ce.prototype.prependListener=function(s,t){return dS(this,s,t,!0)};function PO(){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 lS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=PO.bind(r);return i.listener=e,r.wrapFn=i,i}ce.prototype.once=function(s,t){return sl(t),this.on(s,lS(this,s,t)),this},ce.prototype.prependOnceListener=function(s,t){return sl(t),this.prependListener(s,lS(this,s,t)),this},ce.prototype.removeListener=function(s,t){var e,r,i,n,o;if(sl(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():_O(e,i),e.length===1&&(r[s]=e[0]),r.removeListener!==void 0&&this.emit("removeListener",s,o||t)}return this},ce.prototype.off=ce.prototype.removeListener,ce.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 uS(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?kO(i):pS(i,i.length)}ce.prototype.listeners=function(s){return uS(this,s,!0)},ce.prototype.rawListeners=function(s){return uS(this,s,!1)},ce.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):hS.call(s,t)},ce.prototype.listenerCount=hS;function hS(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?tl(this._events):[]};function pS(s,t){for(var e=new Array(t),r=0;r<t;++r)e[r]=s[r];return e}function _O(s,t){for(;t+1<s.length;t++)s[t]=s[t+1];s.pop()}function kO(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function RO(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))}mS(s,t,n,{once:!0}),t!=="error"&&CO(s,i,{once:!0})})}function CO(s,t,e){typeof s.on=="function"&&mS(s,"error",t,e)}function mS(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 IO 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 gS=new IO;class fS{static encode(t){return gS.toBinary(t)}static decode(t){return gS.fromBinary(new Uint8Array(t))}}function AO(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Hr;class MO{constructor(t={}){EO(this,"opts"),Te(this,Hr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},ie(this,Hr,0)}async wait(){ie(this,Hr,D(this,Hr)+1);const t=AO(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**D(this,Hr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return D(this,Hr)}reset(){ie(this,Hr,0)}}Hr=new WeakMap;const qr={debug:0,info:1,warn:2,error:3};var Ci,Ii;class DO{constructor(t){Te(this,Ci,void 0),Te(this,Ii,void 0),ie(this,Ci,console),ie(this,Ii,t)}debug(...t){qr[D(this,Ii)]>qr.debug||D(this,Ci).debug("[Sockrates]:",...t)}info(...t){qr[D(this,Ii)]>qr.info||D(this,Ci).info("[Sockrates]:",...t)}warn(...t){qr[D(this,Ii)]>qr.warn||D(this,Ci).warn("[Sockrates]:",...t)}error(...t){qr[D(this,Ii)]>qr.error||D(this,Ci).error("[Sockrates]:",...t)}}Ci=new WeakMap,Ii=new WeakMap;var SS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(SS||{});const OO="2",NO="3";var De,Ln,we,xe,jr,Ye,or,Gr,bs,xn,cr,Uh,vS,To,rl,$h,TS,Bh,yS,il,Fh,Hh,ES,yo,nl,Eo,al,ol,qh,Un,bo,wo,cl;class VO{constructor(t,e){var m,S,y,w,P,C,O,$,L,F;Te(this,Uh),Te(this,To),Te(this,$h),Te(this,Bh),Te(this,il),Te(this,Hh),Te(this,yo),Te(this,Eo),Te(this,ol),Te(this,Un),Te(this,wo),Te(this,De,void 0),Te(this,Ln,void 0),Te(this,we,void 0),Te(this,xe,void 0),Te(this,jr,void 0),Te(this,Ye,void 0),Te(this,or,void 0),Te(this,Gr,void 0),Te(this,bs,void 0),Te(this,xn,void 0),Te(this,cr,void 0);var r,i,n,o,c,d,l,u,h;ie(this,Ln,t),ie(this,jr,[]),ie(this,Ye,new el),ie(this,or,!0),ie(this,bs,!1),ie(this,we,e!=null?e:{}),(m=(r=D(this,we)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=D(this,we)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=D(this,we)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=D(this,we)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(P=(c=D(this,we)).debug)!=null||(c.debug=!0),(C=(d=D(this,we)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(O=(l=D(this,we)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),($=(u=D(this,we)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(L=(h=D(this,we)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),ie(this,Gr,{code:void 0,reason:void 0}),ie(this,xe,(F=D(this,we).logger)!=null?F:new DO(D(this,we).debug?"debug":"info")),ie(this,cr,new MO)}get readyState(){var t;return(t=D(this,De))==null?void 0:t.readyState}get url(){return D(this,Ln)}updateURL(t){ie(this,Ln,t),be(this,Hh,ES).call(this)}get config(){return D(this,we)}get sendQueue(){return D(this,jr)}flush(){if(!D(this,we).queueOnDisconnect)return!1;const t=[];return D(this,jr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),ie(this,jr,t),D(this,jr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){D(this,xe).debug("Websocket was already connecting or connected.");return}if(D(this,or)!==!1)return new Promise((e,r)=>{be(this,Un,bo).call(this),be(this,wo,cl).call(this);try{ie(this,De,new WebSocket(be(this,Uh,vS).call(this,D(this,Ln)))),D(this,De).binaryType="arraybuffer",D(this,xe).debug("Connecting");const i=setTimeout(()=>{D(this,xe).debug("Connection timeout. Closing socket"),ie(this,or,!0),be(this,wo,cl).call(this),D(this,De).close(3001,"Connection Timeout"),D(this,we).autoReconnect&&!D(this,bs)&&(D(this,Ye).emit("reconnecting"),be(this,yo,nl).call(this)),r(new Error("Connection timed out!"))},D(this,we).connectionTimeout);D(this,De).onopen=()=>{D(this,xe).debug(`Ready State: ${SS[D(this,De).readyState]}`),i&&clearTimeout(i),be(this,ol,qh).call(this),ie(this,Gr,{code:void 0,reason:void 0}),D(this,Ye).emit("connected"),D(this,we).flushOnReconnect&&this.flush(),e()},D(this,De).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),D(this,xe).debug("Socket closed. Close event:",{event:n}),D(this,xe).debug(`Connection closed code: ${o}`),D(this,xe).debug(`Connection closed reason: ${c}`),D(this,bs)||be(this,il,Fh).call(this,o,c)}catch(o){be(this,To,rl).call(this,o)}},D(this,De).onerror=n=>{be(this,To,rl).call(this,n)},D(this,De).onmessage=n=>be(this,$h,TS).call(this,n)}catch(i){be(this,To,rl).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(D(this,we).queueOnDisconnect&&(!D(this,De)||D(this,De).readyState!==1))return D(this,xe).debug("Queuing message since socket is not connected!",n),D(this,jr).push(n),!1;const o=fS.encode(n);return be(this,Eo,al).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return be(this,Eo,al).call(this,t)}receive(t,e){return D(this,Ye).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")){D(this,Ye).on(t,e);return}this.receive(t,e)}removeAllListeners(){D(this,Ye).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){D(this,Ye).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){D(this,Ye).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){ie(this,or,!1),be(this,Un,bo).call(this),this.removeAllListeners(),ie(this,Gr,{code:1e3,reason:"Sockrates disconnect method called"}),D(this,De).close(1e3,"Sockrates disconnect method called.")}}De=new WeakMap,Ln=new WeakMap,we=new WeakMap,xe=new WeakMap,jr=new WeakMap,Ye=new WeakMap,or=new WeakMap,Gr=new WeakMap,bs=new WeakMap,xn=new WeakMap,cr=new WeakMap,Uh=new WeakSet,vS=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)://.")},To=new WeakSet,rl=function(s,t){D(this,xe).error("Error:",{error:s}),D(this,Ye).emit("errored",{error:s}),t==null||t(s)},$h=new WeakSet,TS=function(s){if(be(this,ol,qh).call(this),s.data===OO){D(this,xe).debug("Received ping from server"),be(this,Eo,al).call(this,NO);return}const t=fS.decode(s.data),{id:e,payload:r}=t;D(this,xe).debug("Received message",{event:t.event,messageID:e}),D(this,Ye).emit(t.event.toString(),{id:e,payload:r})},Bh=new WeakSet,yS=function(){return D(this,De).readyState===1},il=new WeakSet,Fh=function(s,t){ie(this,Gr,{reason:t,code:s}),D(this,Ye).emit("disconnected",{code:s,reason:t})},Hh=new WeakSet,ES=function(){const{reason:s,code:t}=D(this,Gr);t&&t!==1e3&&D(this,or)&&D(this,we).autoReconnect&&!D(this,bs)&&(D(this,xe).debug(`Triggering reconnection due to ${s}.`),D(this,Ye).emit("reconnecting"),be(this,yo,nl).call(this))},yo=new WeakSet,nl=async function(s=!0){if(s&&D(this,bs)){D(this,xe).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(D(this,bs)||D(this,cr).reset(),D(this,we).maxReconnectionAttempts!==null&&D(this,cr).getAttempts()>=D(this,we).maxReconnectionAttempts){D(this,Ye).emit("failed"),ie(this,bs,!1);return}ie(this,bs,!0),be(this,wo,cl).call(this),be(this,Un,bo).call(this);try{if(await D(this,cr).wait(),D(this,or)===!1)return;if(D(this,xe).debug(`Reconnection attempt ${D(this,cr).getAttempts()}`),D(this,Ye).emit("reconnectAttempt",{attempt:D(this,cr).getAttempts()}),await this.connect(),!be(this,Bh,yS).call(this))throw Error("Reconnect Failed");ie(this,bs,!1),ie(this,Gr,{code:void 0,reason:void 0}),D(this,Ye).emit("reconnected")}catch(t){D(this,xe).debug("Failed to reconnect."),D(this,Ye).emit("reconnectFailure",{attempt:D(this,cr).getAttempts()}),be(this,yo,nl).call(this,!1)}},Eo=new WeakSet,al=function(s){try{return D(this,De).send(s),!0}catch(t){return D(this,xe).error(t.message),!1}},ol=new WeakSet,qh=function(){this.config.disconnectOnPingTimeout&&(D(this,xe).debug("Resetting ping timeout"),be(this,Un,bo).call(this),ie(this,xn,setTimeout(()=>{var s;D(this,xe).debug("Disconnecting the socket due to ping timeout"),ie(this,or,!0);const t=3002,e="Ping timeout";(s=D(this,De))==null||s.close(t,e),be(this,il,Fh).call(this,t,e)},D(this,we).pingTimeout)))},Un=new WeakSet,bo=function(){D(this,xn)&&(clearTimeout(D(this,xn)),ie(this,xn,void 0))},wo=new WeakSet,cl=function(){D(this,De)&&(D(this,De).onopen=void 0,D(this,De).onerror=void 0,D(this,De).onmessage=void 0,D(this,De).onclose=void 0)};var LO=Object.defineProperty,xO=Object.getOwnPropertyDescriptor,dl=(s,t,e,r)=>{for(var i=r>1?void 0:r?xO(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};const bS=65535,UO=3e3,wS=(GS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Ie);g(this,kc);g(this,Rc);g(this,di,void 0);g(this,Ce,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,hs,void 0);g(this,rt,void 0);var n;if(!t||!e||!r)throw new k("peerId, meetingId, or authToken can not be empty","0404");f(this,hs,void 0),f(this,rt,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,di,U(this,kc,lp).call(this,t)),f(this,Ce,new VO(a(this,di),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),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,di,U(this,kc,lp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,Ce).updateURL(a(this,di))}static getSocketEdgeDomain(s){return _n({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,di)}async connect(){a(this,Ie,He).socketJoinAttempted=!0,await a(this,Ce).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,Ce).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,Ce).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,rt).getValue("telemetry").injectContext(r),a(this,Ce).send(s,e!=null?e:U(this,Rc,up).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(bS,w),a(this,Ce).removeListener(Vr.errorResponse,w),a(this,Ce).removeListener(vs.errorResponse,w)},l=r!=null?r:U(this,Rc,up).call(this),u={};a(this,rt).getValue("telemetry").injectContext(u);const m=({id:y,payload:w})=>{if(l===y){let P;try{const C=LR.fromBinary(w);P=new Error(C.errorMessage)}catch(C){P=new Error("failed to parse error message",{cause:C});try{const O=xC.fromBinary(w);P=new Error(O.message)}catch(O){P=new Error("failed to parse error message",{cause:O})}}c(P),d(S,m)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,m))};a(this,Ce).on(n,S),a(this,Ce).on(bS,m),a(this,Ce).on(Vr.errorResponse,m),a(this,Ce).on(vs.errorResponse,m),setTimeout(()=>{d(S,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,hs)&&(clearTimeout(a(this,hs)),f(this,hs,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)!==Nn.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==Nn.CONNECTED?a(this,rt).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ie,He).joinAttempted}):f(this,hs,setTimeout(()=>{a(this,rt).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Ie,He).joinAttempted}),f(this,hs,void 0)},UO)),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,hs)&&(clearTimeout(a(this,hs)),f(this,hs,void 0)),a(this,rt).getValue("peerSessionStore").emit(_.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(_.SOCKET_SERVICE_FAILED),a(this,Ie,He).updateSocketConnectionState("failed")})}},di=new WeakMap,Ce=new WeakMap,Ie=new WeakSet,He=function(){return a(this,rt).getValue("connectionHandler")},hs=new WeakMap,rt=new WeakMap,kc=new WeakSet,lp=function(s){const t=a(this,rt).getValue("socketBaseURI")||a(this,rt).getValue("baseURI");let e=wS.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=>Id[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,up=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},GS);let Po=wS;dl([E.trace("SocketService.connect")],Po.prototype,"connect",1),dl([E.trace("SocketService.disconnect")],Po.prototype,"disconnect",1),dl([E.trace("SocketService.sendMessagePromise")],Po.prototype,"sendMessagePromise",1),dl([E.trace("SocketService.sendMessagePromiseWithTimeout")],Po.prototype,"sendMessagePromiseWithTimeout",1);class $O{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=l0.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=L0.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Zg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return Xg.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return k0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(x.createConnectedRooms,m0.toBinary({payloads:t}));return Xg.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(x.deleteConnectedRooms,P0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,D0.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 BO=Object.defineProperty,FO=Object.getOwnPropertyDescriptor,HO=(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&&BO(t,e,i),i};class PS extends Ut{constructor(e){const r=e.getValue("logger");super(r);p(this,"meetings",[]);p(this,"parentMeeting",null);g(this,Ms,void 0);f(this,Ms,e)}get supportsConnectedMeetings(){return a(this,Ms).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
18
|
-
Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,
|
|
19
|
-
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,ge).getValue("self").videoEnabled,audio:a(this,ge).getValue("self").audioEnabled};try{a(this,ge).getValue("self").cleanupEvents(),await a(this,ge).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,ge).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 RS.init({...a(this,ge).getValue("options"),cachedUserDetails:null,defaults:{...a(this,ge).getValue("options").defaults,...e,mediaHandler:a(this,ge).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,ge).getValue("self");r.self.setName(a(this,ge).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,ge).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,ge).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,ge).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,ge).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})}},ge=new WeakMap,WS);let ll=_S;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 GO=Object.defineProperty,WO=Object.getOwnPropertyDescriptor,Gh=(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};const _o=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 L,F,Q;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(oO(s),fe.isSupported()===!1)throw new k("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 y1(s);s.setValue("connectionHandler",l);let u="",h="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=((L=m.meeting)==null?void 0:L.title)||"",h=((F=m.socket)==null?void 0:F.baseUri)||s.getValue("baseURI"),s.setValue("presetName",m.preset.name),s.setValue("socketBaseURI",h),c.info(`Socket Base URI ${h} is being used`)}catch(X){throw c.error("Failed to get user details",{error:X}),X instanceof uh?X.status===401?new k("Unauthorized. The auth token may be invalid or expired. (401)","0004"):X.status===403?new k("Access denied. Insufficient permissions to join the meeting. (403)","0004"):X.status===404?new k("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"):X.status>=500?new k(`The server encountered an error. Try again. (${X.status})`,"0001"):X.isHttpError?new k(`Request rejected by the server. (${X.status})`,"0001"):X.isTimeout?new k("Connection timed out. Check the network and try again.","0001"):new k("Unable to connect to the server. Check the internet connection.","0001"):new k((X==null?void 0:X.message)||"Failed to initialize.","0001")}const S=_o.createSocketService(s),y=S.connect(),w=d.getPlugins();try{await y}catch(X){c.error("[Controller]: Failed to connect to socket server:",{error:X})}const P=wh.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",P);const C=_h.init(s,P.viewType,m.preset.permissions),O=_o.setupControllers(S,s,m,w,u,P,C);d1(P)&&((Q=_o.createRoomNodeClient(s,S).initializeConnection(m.participant.name,i,!1,C))==null||Q.catch(it=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:it})}));const{controllers:$}=await O;return j_(),new _o(e,$,s)}static async setupControllers(s,t,e,r,i,n,o){var V,R,je;const c=t.getValue("modules"),{participant:d}=e,l=t.getValue("defaults"),u=t.getValue("logger"),{viewType:h,mediaConstraints:{audio:m}}=n;t.setValue("viewType",h),t.setValue("defaults",{mediaConfiguration:{audio:{enableHighBitrate:(V=m.enableHighBitrate)!=null?V:!1,enableStereo:(R=m.enableStereo)!=null?R:!1}},...l}),t.setValue("maxPreferredStreams",fe.isMobile()?n.maxVideoStreams.mobile:n.maxVideoStreams.desktop);let S,y,w,P,C,O,$,L,F;const Q=new uO(t,s),X=new $O(s);t.setValue("connectedMeetingsSocketHandler",X);const it=new Zd(t,s),Ds=new rr(t,s),fn=new SO(s),Os=new iS(t,s),I=new vO(t,s),T=new lO(s),b=await Fr.init(t,Os,d,o,n);t.setValue("selfController",b);const B=await Pf.init(t,b.self,Os,Q,i);if(c.participant&&(L=new ar(t,b.self,Os)),(je=c.e2ee)!=null&&je.enabled&&c.e2ee.manager.init(u,t.getValue("peerSessionStore")),c.chat&&(y=await ts.init(t,Ds,b.self,L.participants)),c.internals&&(C=await vh.init(t)),c.livestream&&n.viewType===Qs.Livestream&&($=new jf(t,b.self,T)),c.poll&&(S=await yf.init(t,b.self,it)),c.recording&&(O=new If(t,b.self,Os)),c.stage&&(w=new _f(t,fn,Os,b.self,L.participants)),c.plugin){if(!L)throw new k("The plugin module cannot be initialized without the `participant` module","0102");const Cr=await r;P=await lo.init(t,Cr,I,Ds,y==null?void 0:y.chat,b.self,L.participants,i)}if(c.connectedMeetings&&(F=await ll.init(t)),c.pip){const Cr=await Bu._init(t,b.self);t.setValue("pip",Cr)}const Fe={storesManager:new vD(t,I),pollController:S,selfController:b,metaController:B,chatController:y,stageController:w,pluginController:P,recordingController:O,internalsController:C,livestreamController:$,participantController:L,connectedMeetingsController:F};return{theme:n,permissions:o,controllers:Fe}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return sS(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 Po(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let ul=_o;Gh([E.trace("Controller.init")],ul,"init",1),Gh([E.trace("Controller.createRoomNodeClient")],ul,"createRoomNodeClient",1),Gh([E.trace("Controller.createSocketService")],ul,"createSocketService",1);class JO{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 kS=new JO;function KO(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=Si.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 k("Invalid auth token","0004")}}class zO{constructor(){g(this,nu);g(this,li,new Audio);g(this,hn,new MediaStream);g(this,pn,new Map);g(this,Cc,void 0);a(this,li).srcObject=a(this,hn),a(this,li).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,pn).has(e.id)||(a(this,hn).addTrack(e),a(this,pn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,li).setSinkId(t)}removeTrack(t){const e=a(this,pn).get(t);e&&(a(this,hn).removeTrack(e),a(this,pn).delete(t))}async play(){return a(this,li).srcObject=a(this,hn),a(this,li).play().catch(t=>{U(this,nu,Iv).call(this,t)})}onError(t){f(this,Cc,t)}}li=new WeakMap,hn=new WeakMap,pn=new WeakMap,Cc=new WeakMap,nu=new WeakSet,Iv=function(t){var e;(e=a(this,Cc))==null||e.call(this,t)};class YO extends zO{constructor(){super();g(this,mn,void 0);f(this,mn,new Map)}addParticipantTrack(e,r){a(this,mn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,mn).get(e);r&&this.removeTrack(r),a(this,mn).delete(e)}}mn=new WeakMap;var QO=Object.defineProperty,XO=Object.getOwnPropertyDescriptor,hl=(s,t,e,r)=>{for(var i=r>1?void 0:r?XO(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&&QO(t,e,i),i};let Wr=(JS=class{constructor(t,e){g(this,Je,void 0);g(this,gn,void 0);f(this,gn,t),f(this,Je,e)}get peerId(){return a(this,gn).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=Dr.createContext(i,{peerId:i}),o=n.getValue("logger");o.init(n);const c=new Jf(n,o);return await c.init(t,e,n),n.setValue("defaults",{mediaHandler:c}),c}static async init(t){var m,S,y,w,P,C,O,$,L;fe.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}=KO(r,i);if((y=o.baseURI)!=null&&y.includes("dyte.io"))throw new k("Dyte Base URIs are no longer supported. Use RealtimeKit Base URIs.","0001");window.__zone_symbol__DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION=!0;const c=Wr.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");Ov(l),kS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(P=(w=t.modules)==null?void 0:w.tracing)!=null?P:!0,(O=(C=t==null?void 0:t.modules)==null?void 0:C.devTools)==null?void 0:O.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${($=t.authToken)==null?void 0:$.slice(0,10)}...
|
|
20
|
-
${(L=t.authToken)==null?void 0:L.slice(-10)}`}});const u=await
|
|
17
|
+
`},Si=Bf,kD=CD,Bd=kD,vi=Si.parse;Si.parseParams,Si.parseFmtpConfig,Si.parsePayloads,Si.parseRemoteCandidates,Si.parseImageAttributes,Si.parseSimulcastStreamList;class Fd extends yh{constructor(e,r){super(e);p(this,"supportsSendEncodings",!1);this.supportsSendEncodings=r.supportsSendEncodings}static createFactory(e,r){return()=>new Fd(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 U;const S=vi(h),y=S.media[S.media.length-1],w=y.rtp.filter(L=>m.some(F=>F.name===L.codec)),b=y.fmtp.filter(L=>w.some(F=>F.payload===L.payload)),R=(U=y.rtcpFb)==null?void 0:U.filter(L=>w.some(F=>F.payload===L.payload)),N=w.map(L=>L.payload);return S.media[S.media.length-1].rtp=w,S.media[S.media.length-1].fmtp=b,S.media[S.media.length-1].rtcpFb=R,S.media[S.media.length-1].payloads=N.join(" "),Bd(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 bh extends yh{static createFactory(t){return()=>new bh(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 RD(s,t){return typeof s=="undefined"?t:typeof window!="undefined"&&Object.getOwnPropertyDescriptor(window,"structuredClone")?structuredClone(s):JSON.parse(JSON.stringify(s))}class ID extends Ud{constructor(e,r){var i;super(e);g(this,Ns);g(this,Wo);g(this,Sl);g(this,vl);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,Go,void 0);g(this,ji,void 0);g(this,Ds,void 0);g(this,fl,void 0);this.id=r.id,this.localId=r.localId,f(this,Go,r.handler),this.appData=r.appData,this.peerId=r.producingPeerId,this.producingTransportId=r.producingTransportId,f(this,Ds,!1),this.producerId=r.producerId,this.track=r.track,f(this,ji,(i=r.paused)!=null?i:!1),this.mimeType=r.mimeType,this.transceiver=r.transceiver,this.rtpReceiver=r.rtpReceiver,$(this,Sl,WS).call(this),f(this,fl,e)}get closed(){return a(this,Ds)}get kind(){return this.track.kind}get paused(){return a(this,ji)}close(e,r){a(this,Ds)||(this.logger.debug(`Consumer::close() ${e?`with reason ${e}`:""}`,a(this,Ns,ii)),f(this,Ds,!0),r&&($(this,vl,JS).call(this),this.transceiver.stop()),this.safeEmit("close",e))}async getStats(){if(a(this,Ds))throw new Ct("closed");return a(this,Go).getReceiverStats(this.localId)}pause(){if(this.logger.debug("consumer::pause()",a(this,Ns,ii)),a(this,Ds)){this.logger.error("consumer::pause() | Consumer closed",a(this,Ns,ii));return}f(this,ji,!0),this.track.enabled=!1,this.safeEmit("pause")}resume(){if(this.logger.debug("consumer::resume()",a(this,Ns,ii)),a(this,Ds)){this.logger.error("Consumer::resume() | Consumer closed",a(this,Ns,ii));return}f(this,ji,!1),this.track.enabled=!0,this.safeEmit("resume")}}Go=new WeakMap,ji=new WeakMap,Ds=new WeakMap,fl=new WeakMap,Ns=new WeakSet,ii=function(){return{consumer:{id:this.id,appData:this.appData,peerId:this.peerId,kind:this.kind}}},Wo=new WeakSet,Jh=function(){this.logger.debug('Consumer::track "ended" event',a(this,Ns,ii)),this.safeEmit("trackended")},Sl=new WeakSet,WS=function(){this.track.addEventListener("ended",$(this,Wo,Jh).bind(this))},vl=new WeakSet,JS=function(){try{this.track.removeEventListener("ended",$(this,Wo,Jh)),this.track.stop()}catch(e){this.logger.error("Consumer::destroyTrack()",{...a(this,Ns,ii),error:e})}};class AD extends Ud{constructor(e,r){var i,n;super(e);g(this,qt);p(this,"id");p(this,"localId");g(this,Ts,void 0);p(this,"kind");p(this,"appData");p(this,"rtpSender");g(this,ga,void 0);g(this,fa,void 0);g(this,Gi,void 0);g(this,ss,!1);g(this,rt,void 0);g(this,Yr,void 0);g(this,Sa,void 0);g(this,Tl,void 0);this.id=r.id,this.localId=r.localId,f(this,rt,r.track),this.kind=(i=r.track)==null?void 0:i.kind,f(this,Yr,r.disableTrackOnPause?!((n=r.track)!=null&&n.enabled):!1),f(this,Sa,void 0),f(this,ga,r.stopTracks),f(this,fa,r.disableTrackOnPause),f(this,Gi,r.zeroRtpOnPause),this.appData=r.appData||{},this._onTrackEnded=this._onTrackEnded.bind(this),f(this,Ts,r.handler),this.rtpSender=r.rtpSender,this._handleTrack(),f(this,Tl,e)}get closed(){return a(this,ss)}get track(){return a(this,rt)}get paused(){return a(this,Yr)}get maxSpatialLayer(){return a(this,Sa)}async close(e){if(a(this,ss))return;if(this.logger.debug(`Producer::close() ${e?`with reason ${e}`:""}`,a(this,qt,_s)),f(this,ss,!0),this._destroyTrack(),e===qd){this.safeEmit("close",{reason:e});return}const{offerSdp:r,callback:i}=await a(this,Ts).stopSending(this.localId),{answer:n}=await this.safeEmitAsPromise("close",{offer:r,reason:e});i(n)}async getStats(){if(a(this,ss))throw new Ct("closed");return a(this,Ts).getSenderStats(this.localId)}pause(){this.logger.debug("Producer::pause()",a(this,qt,_s)),a(this,ss)&&this.logger.error("Producer::pause() | Producer closed",a(this,qt,_s)),f(this,Yr,!0),a(this,rt)&&a(this,fa)&&(a(this,rt).enabled=!1),a(this,Gi)&&a(this,Ts).replaceTrack(this.localId,null),this.emit("pause")}resume(){if(this.logger.debug("Producer::resume()",a(this,qt,_s)),a(this,ss)){this.logger.error("Producer::resume() | Producer closed",a(this,qt,_s));return}f(this,Yr,!1),a(this,rt)&&a(this,fa)&&(a(this,rt).enabled=!0),a(this,Gi)&&a(this,Ts).replaceTrack(this.localId,a(this,rt)),this.emit("resume")}async replaceTrack({track:e}){if(this.logger.debug(`Producer::replaceTrack() trackId: ${e==null?void 0:e.id}`,a(this,qt,_s)),a(this,ss)){if(e&&a(this,ga))try{e.stop()}catch(r){this.logger.error("Producer::replaceTrack",{...a(this,qt,_s),error:r})}throw new Ct("closed")}else if(e&&e.readyState==="ended")throw new Ct("track ended");if(e===a(this,rt)){this.logger.debug(`replaceTrack() | same track, ignored trackId: ${e.id}`,a(this,qt,_s));return}(!a(this,Gi)||!a(this,Yr))&&await a(this,Ts).replaceTrack(this.localId,e),this._destroyTrack(),f(this,rt,e),this._handleTrack()}async setMaxSpatialLayer(e){if(a(this,ss))throw new Ct("closed");if(this.kind!=="video")throw new ao("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");await a(this,Ts).setMaxSpatialLayer(this.localId,e),f(this,Sa,e)}async setRtpEncodingParameters(e){if(a(this,ss))throw new Ct("closed");if(typeof e!="object")throw new TypeError("invalid params");await a(this,Ts).setRtpEncodingParameters(this.localId,e)}_onTrackEnded(){this.logger.debug(`Producer::track "ended" event trackId: ${this.track.id}`,a(this,qt,_s)),this.safeEmit("trackended",this.track.id)}_handleTrack(){a(this,rt)&&a(this,rt).addEventListener("ended",this._onTrackEnded)}_destroyTrack(){var e;if(a(this,rt))try{a(this,rt).removeEventListener("ended",this._onTrackEnded),a(this,ga)&&a(this,rt).stop()}catch(r){this.logger.error(`Producer::_destroyTrack trackId: ${(e=this.track)==null?void 0:e.id}`,{...a(this,qt,_s),error:r})}}}Ts=new WeakMap,ga=new WeakMap,fa=new WeakMap,Gi=new WeakMap,ss=new WeakMap,rt=new WeakMap,Yr=new WeakMap,Sa=new WeakMap,Tl=new WeakMap,qt=new WeakSet,_s=function(){return{producer:{id:this.id,appData:this.appData,kind:this.kind}}};function Hf(s){return typeof s=="object"&&!Array.isArray(s)&&s!==null}function Ph(s){return Math.random().toString(36).substring(2,2+s)}const Hd=1;function qf(s){const t=s;return delete t.payload._bolt,t}function MD(s){return s.payload&&Hf(s.payload)}function OD(s){var t,e;return MD(s)&&(e=(t=s.payload._bolt)==null?void 0:t.id)!=null?e:""}const va=class extends it.EventEmitter{constructor(e,r,i,n){super();p(this,"channel");p(this,"queue");p(this,"serverProtocolVersion");g(this,Qr,new Map);g(this,yl,void 0);g(this,Wi,void 0);p(this,"respond",(e,r,i=!1)=>{let n;i?n=va.createErrorResponse(e,r):n=va.createResponse(e,r),this.channel.send(JSON.stringify(n))});p(this,"notify",e=>{const r=va.createNotification(e);this.channel.send(JSON.stringify(r))});p(this,"request",async e=>{const r=va.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=mn();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,Wi).debug(`Sending message chunk over dc: ${m}`),this.channel.send(m)}}else a(this,Wi).debug(`Sending message over dc: ${r}`),this.channel.send(r)});p(this,"processMessage",e=>{var i;a(this,Qr).has(e.id)||a(this,Qr).set(e.id,[]);const r=a(this,Qr).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,Qr).get(e.id),o=n==null?void 0:n.reduce((d,l)=>d+l.chunk,"");a(this,Qr).delete(e.id);const c=JSON.parse(o);if(!c.payload||!Hf(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,Wi).debug(`resolving pending request with id: ${r}, complete response: ${JSON.stringify(e)}`),e.type==="error"?i.cancel(qf(e)):i.resolve(qf(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:Ph(8),{type:"_bolt",payload:{message:"pong"}}),!0):!1});this.label=i,this.transportId=n,f(this,yl,e),f(this,Wi,e.getValue("logger")),this.channel=r,this.queue=new Map}};let Ti=va;Qr=new WeakMap,yl=new WeakMap,Wi=new WeakMap,p(Ti,"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:Ph(8),type:"REQUEST",version:Hd}}}}),p(Ti,"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:Hd}}}}),p(Ti,"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:Ph(8),type:"NOTIFY",version:Hd}}}}),p(Ti,"createErrorResponse",(e,r)=>({type:"error",payload:{error:r.message,_bolt:{id:e,type:"RESPONSE",version:Hd}}}));const qd="transport closed",Ta=class extends Ud{constructor(e,{id:r,direction:i,handlerFactory:n,iceServers:o,iceTransportPolicy:c,proprietaryConstraints:d,additionalSettings:l,appData:u,config:h}){var w,b,R;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,Ji,void 0);f(this,Ji,e);const m=e.getValue("logger");m.debug(`constructor() [id: ${r}, direction: ${i}]`),this.id=r,this.direction=i;const S=RD(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 Th(m,!0),this.handler=n(),this.handler.enableHighBitrate=(w=h==null?void 0:h.enableHighBitrate)!=null?w:!1,this.handler.enableStereo=(b=h==null?void 0:h.enableStereo)!=null?b:!1,this.handler.enableDtx=(R=h==null?void 0:h.enableDtx)!=null?R:!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 U=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(U),N(!0)}),this.once("disconnect",()=>{clearTimeout(U),N(!1)}),this.once("close",()=>{clearTimeout(U),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 U=this.datachannels.get(N.label);U||(U||(U=new Ti(a(this,Ji),N,N.label,this.serverId),this.datachannels.set(N.label,U)),this.eventsDCFailureTimer=setTimeout(()=>{N.label==="events"&&(this.eventsDCReadyPromiseResolver(!1),this.safeEmit("dc_error",N.label))},5e3))}),this.handler.on("datachannel",(N,U)=>{N.label==="events"&&(this.eventsDCReadyPromiseResolver(!0),this.eventsDCFailureTimer&&clearTimeout(this.eventsDCFailureTimer));const L=this.datachannels.get(N.label);if(!L){this.logger.error("unregistered datachannel for message",{rtcChannel:{label:N.label,message:U}});return}try{const F=JSON.parse(U);this.logger.debug("datachannel message chunk recieved",{dataChannelMessageChunk:{id:F.id,count:F.count,chunkIndex:F.chunkIndex,chunk:F.chunk,transprtId:this.serverId}});const H=L.processMessage(F);if(!H)return;this.logger.debug(`datachannel message with id:${F.id} on transport:${this.serverId}complete - ${JSON.stringify(H)}`),this.emit(`datachannel:${N.label}`,L.label,H)}catch(F){this.logger.error("error parsing message",{error:F})}})}get closed(){return this.connectionState==="closed"}setServerId(e){this.serverId=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(qd).catch(()=>{})}),this.producers.clear(),Array.from(this.consumers.values()).forEach(e=>{e.close(qd)}),this.consumers.clear(),this.consumerTrackEvents.clear(),this.emit("close"))}async getStats(){if(this.closed)throw new Ct("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 Ct("closed");return this.handler.restartIce()}async canProduce(e){const{track:r,appData:i}=e;if(r){if(this.direction!=="send")throw new ao("not a sending Transport");if(r.readyState==="ended")throw new Ct("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 Or("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:b,sender:R,mid:N}=await this.handler.send({track:n,encodings:o,codecOptions:c,screenShare:h==null?void 0:h.screenShare}),{answer:U,producerId:L}=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}),F=await b(U);return{producerId:L,localId:F,rtpSender:R}},"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 AD(a(this,Ji),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 Ct("closed");if(this.direction!=="recv")throw new ao("not a receiving transport");if(!await this.transportConnectionPromise)throw new Or("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=vi(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=vi(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:Bd(n)}}static parseHeaderExtensionMappings(e){const r=vi(e.sdp),i={};return r.media.forEach(n=>{i[n.mid]=n.ext}),i}static setHeaderExtensionMappings(e,r){const i=vi(e.sdp);return i.media=i.media.map(o=>{const c={...o};return c.ext=r[o.mid],c}),{...e,sdp:Bd(i)}}async closeConsumers(e,r){try{const i=e.map(l=>l.transceiver.mid),n=Ta.parseCodecAndFmtpMappings(this.handler.pc.remoteDescription,i),o=Ta.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=Ta.setCodecAndFmtpMappings(c,i,n),c=Ta.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=vi(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=Bd(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,b)=>{const R=setTimeout(()=>{this.logger.warn(`Timed out waiting for track event ${S} producingPeerId: ${n}`),this.consumerTrackEvents.delete(S),y.isTimedout=!0,b(y)},5e3),N=(L,F)=>{try{if(L.readyState==="ended")clearTimeout(R),b(y);else{const H=L;H.enabled=!0,this.handler.midTransceiverMap.set(F.mid,F);const ie=new ID(a(this,Ji),{id:r,localId:F.mid,transceiver:F,track:H,paused:d,producerId:i,producingPeerId:n,producingTransportId:o,handler:this.handler,appData:{...u,screenShare:l,peerId:n},rtpReceiver:F.receiver,mimeType:m});this.consumers.set(r,ie),ie.once("close",()=>{this.consumers.delete(ie.id),this.handler.midTransceiverMap.delete(F.mid)}),this.logger.info("consumer created for ",{consumer:{id:r,kind:h,appData:{screenShare:l},peerId:n,producerId:i}}),this.emit("newconsumer",ie),clearTimeout(R),w(ie)}}catch(H){this.logger.warn("error while creating consumer:",H),clearTimeout(R),b(y)}},U=this.unknownTracksMap.get(S);U?(this.logger.info(`track event already received [trackId: ${U.track.id}] [mid: ${U.transceiver.mid}]`),this.unknownTracksMap.delete(S),N(U.track,U.transceiver)):(this.logger.info(`Registering onTrack handler for key ${S} [producingPeerId: ${n}]`),this.consumerTrackEvents.set(S,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 fD("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 _h=Ta;Ji=new WeakMap;function DD(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=np.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 ND{constructor(t,{handlerName:e,handlerFactory:r}={}){p(this,"handlerFactory");g(this,hr,void 0);g(this,Ki,void 0);const i=t.getValue("logger");if(i.debug("constructor()"),f(this,hr,t),f(this,Ki,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,Ki).debug(`Device::constructor() | handler given: ${e}`);else if(e=DD(a(this,Ki)),e)a(this,Ki).debug(`Device::constructor() | detected handler: ${e}`);else throw new Error("device not supported");switch(e){case"Chrome74":this.handlerFactory=Eh.createFactory(a(this,hr));break;case"Safari12":this.handlerFactory=bh.createFactory(a(this,hr));break;case"Firefox60":this.handlerFactory=Fd.createFactory(a(this,hr),{supportsSendEncodings:!1});break;case"Firefox110":this.handlerFactory=Fd.createFactory(a(this,hr),{supportsSendEncodings:!0});break;default:throw new TypeError(`unknown handlerName "${e}"`)}}}createTransport(t){const e=mn();return new _h(a(this,hr),{id:e,...t,handlerFactory:this.handlerFactory})}}hr=new WeakMap,Ki=new WeakMap;const VD=2e3;class LD extends it.EventEmitter{constructor(e,r){super();g(this,ba);g(this,Yo);g(this,El);g(this,Qo);g(this,wl);g(this,bl);g(this,Pl);g(this,_l);g(this,Cl);g(this,Xo);g(this,Zo);p(this,"context");g(this,ya,void 0);g(this,ct,void 0);g(this,dt,void 0);g(this,Jo,void 0);g(this,Ko,void 0);g(this,zi,void 0);g(this,Ea,void 0);g(this,zo,void 0);g(this,wa,{transportFailureCount:{send:0,recv:0},lastConnectionTime:0});g(this,Yi,void 0);g(this,Vs,"all");this.context=e,f(this,zi,r),f(this,ya,new ND(e)),f(this,Ea,new yD(r)),f(this,zo,us),a(this,ba,tu).mediaState={send:{state:An.NEW},recv:{state:An.NEW}},yn(this.context,"forceRelay")&&f(this,Vs,"relay"),this.logger.info(`ICE Transport Policy initially set to ${a(this,Vs)}`),$(this,Yo,Kh).call(this)}get telemetry(){return this.context.getValue("telemetry")}get logger(){return this.context.getValue("logger")}get socket(){return a(this,zi)}get socketHandler(){return a(this,Ea)}get sendTransport(){return a(this,ct)}get recvTransport(){return a(this,dt)}get events(){return a(this,zo)}set sendTransportConnectedCallback(e){f(this,Jo,e)}set recvTransportConnectedCallback(e){f(this,Ko,e)}async setupTransports(e){await $(this,El,KS).call(this,e);let r,i;e.send&&(r=$(this,Qo,zh).call(this,a(this,ct)).then(n=>{try{a(this,Jo).call(this,n)}catch(o){this.logger.error("Failed to run send transport callback")}})),e.recv&&(i=$(this,Qo,zh).call(this,a(this,dt)).then(n=>{try{a(this,Ko).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,ct);this.logger.info("Closing send transport",{transport:{id:n,serverId:o,type:c}}),a(this,ct).close(),a(this,ct).removeAllListeners(),f(this,ct,void 0)}if(e.recv&&this.recvTransport!==void 0){const{id:n,serverId:o,direction:c}=a(this,dt);this.logger.info("Closing recv transport",{transport:{id:n,serverId:o,type:c}}),(r=a(this,dt))==null||r.close(),(i=a(this,dt))==null||i.removeAllListeners(),f(this,dt,void 0)}$(this,Yo,Kh).call(this)}stopAllTransports(){this.logger.info("Closing all transports"),this.stopTransports({send:!0,recv:!0})}handleErrors(e){throw new Error("Method not implemented.")}}ya=new WeakMap,ct=new WeakMap,dt=new WeakMap,Jo=new WeakMap,Ko=new WeakMap,zi=new WeakMap,Ea=new WeakMap,zo=new WeakMap,wa=new WeakMap,Yi=new WeakMap,Vs=new WeakMap,ba=new WeakSet,tu=function(){return this.context.getValue("connectionHandler")},Yo=new WeakSet,Kh=function(){f(this,Yi,{send:void 0,recv:void 0})},El=new WeakSet,KS=async function(e){var o,c,d,l,u,h,m,S;yn(this.context,"forceRelay")&&f(this,Vs,"relay"),this.logger.info(`ICE Transport Policy set to ${a(this,Vs)}`);const n=await Pt().getICEServers().catch(y=>(this.logger.warn(`failed to get iceservers from server: ${y.message}`),[]));e.send&&$(this,bl,YS).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,Vs)}),e.recv&&$(this,Pl,QS).call(this,{iceServers:n,additionalSettings:{encodedInsertableStreams:(S=this.context.getValue("modules").e2ee)==null?void 0:S.enabled},iceTransportPolicy:a(this,Vs)})},Qo=new WeakSet,zh=async function(e){const{id:r,serverId:i,direction:n}=e;$(this,_l,XS).call(this,e);try{return await $f(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 Or("Cannot reconnect closed transport");await $(this,wl,zS).call(this,e)}catch(l){if(l instanceof Or){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}},wl=new WeakSet,zS=async function(e){const{id:r,direction:i}=e;if(this.logger.info(`Connecting ${i} transport`,{transport:{id:r,type:i}}),!a(this,zi).isConnected)throw new Or("Socket is not connected");if(e.connectionState==="closed")throw new Or("Transport is closed");try{await e.connect(n=>$(this,Cl,ZS).call(this,i,n)),this.logger.info(`Connected ${i} transport`,{transport:{id:r,serverId:e.serverId,type:i}})}catch(n){throw a(this,wa).transportFailureCount[i]+=1,n.message==="ice connection failed"?new Or(n.message):n}},bl=new WeakSet,YS=function(e){var r,i;if(a(this,ct)&&a(this,ct).connected){this.logger.info("Transport send is already connected",{transport:{id:(r=a(this,ct))==null?void 0:r.id,serverId:(i=a(this,ct))==null?void 0:i.serverId,type:"send"}});return}f(this,ct,a(this,ya).createTransport({...e,direction:"send"})),this.context.getValue("callstats").configureSendTransport(a(this,ct))},Pl=new WeakSet,QS=function(e){var r,i;if(a(this,dt)&&a(this,dt).connected){this.logger.info("Transport recv is already connected",{transport:{id:(r=a(this,dt))==null?void 0:r.id,serverId:(i=a(this,dt))==null?void 0:i.serverId,type:"recv"}});return}f(this,dt,a(this,ya).createTransport({...e,direction:"recv"})),this.context.getValue("callstats").configureRecvTransport(a(this,dt))},_l=new WeakSet,XS=function(e){const{direction:r,id:i}=e;e.on("connectionstatechange",async n=>{$(this,Zo,Qh).call(this,{state:n,direction:r}),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,Yi)[r];c!==void 0&&(clearTimeout(c),a(this,Yi)[r]=void 0)};switch(n){case"connected":o(),a(this,wa).lastConnectionTime=performance.now();break;case"disconnected":a(this,Yi)[r]=setTimeout(async()=>{this.logger.warn(`${r} transport is in disconnected state, reconnecting transport`,{transport:{id:i,serverId:e.serverId,type:r}}),await $(this,Xo,Yh).call(this,e.direction)},VD);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 $(this,Xo,Yh).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,OD(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"))})},Cl=new WeakSet,ZS=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?Gs.SUBSCRIBER:Gs.PUBLISHER},producers:[]};return a(this,Ea).connectTransport(c)}catch(n){throw this.logger.error(`Error in ${e} transport connection:`,{error:n}),n}},Xo=new WeakSet,Yh=async function(e){switch(this.logger.info("Called reconnect transport",{transport:{type:e}}),this.stopTransports({[e]:!0}),a(this,zi).isConnected&&a(this,wa).transportFailureCount[e]>2&&(this.logger.warn(`Multiple disconnections in ${e} transport, forcing relay`),f(this,Vs,"relay")),await this.setupTransports({[e]:!0}),e){case"send":{this.logger.info("Transport reconnected",{transport:a(this,ct)}),this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE);break}case"recv":{this.logger.info("Transport reconnected",{transport:a(this,dt)}),this.context.getValue("peerSessionStore").emit(_.UPDATE_ACTIVE,{createAllConsumers:!0});break}default:this.logger.warn("Unknown transport direction",{transport:{type:e}})}$(this,Zo,Qh).call(this,{state:An.CONNECTED,direction:e})},Zo=new WeakSet,Qh=function(e){const{state:r,direction:i}=e;a(this,ba,tu).mediaState[i]={state:r},this.context.getValue("peerSessionStore").emit(_.TRANSPORT_STATE_UPDATE,{transport:i,...a(this,ba,tu).mediaState[i]})};class xD{constructor(t,e,r,i,n){g(this,kl,void 0);g(this,rs,void 0);this.events=e,this.recvTransport=r,this.socket=i,this.socketHandler=n,f(this,kl,t),f(this,rs,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,rs).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,rs).info("Negotiating socket consumer",{transport:this.recvTransport}),a(this,rs).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:Gs.SUBSCRIBER}};return a(this,rs).debug(`sending renegotiate request: ${JSON.stringify(r)} on recvTransport`,{transport:this.recvTransport}),await this.socket.sendMessagePromise(this.events.renegotiateSessionDescription,bC.toBinary(r)),a(this,rs).info("Renegotiation done",{transport:this.recvTransport}),e}catch(e){a(this,rs).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,rs).info(`Closing consumers: ${JSON.stringify(n)}`);const o={description:{sdp:i.sdp,type:i.type,target:Gs.SUBSCRIBER},consumerIds:n,consumingTransportId:this.recvTransport.serverId},c=await this.socketHandler.closeConsumer(o),d=Yk.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,rs).info(`Consumers switched layers to ${e}`,{consumerIds:i==null?void 0:i.map(({id:n})=>n)})}}kl=new WeakMap,rs=new WeakMap;class Ch{constructor(t){this.socketHandler=t}static getMSIDFromSDP(t,e){return vi(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=Ch.getMSIDFromSDP(t.sdp,e),d={description:{sdp:t.sdp,type:t.type,target:Gs.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}}}class UD extends LD{constructor(e,r){super(e,r);g(this,tc);g(this,Il);g(this,Al);g(this,Ml);g(this,Ol);g(this,Qi,void 0);g(this,Xr,void 0);g(this,Pa,void 0);g(this,ec,void 0);g(this,Ls,void 0);g(this,Rl,{producerCreationFailureCount:0,consumerCreationFailureCount:0,producerNotReadyFailureCount:0});g(this,pr,[]);g(this,_a,void 0);this.context=e,this.sendTransportConnectedCallback=async()=>{f(this,ec,new Ch(this.socketHandler))},this.recvTransportConnectedCallback=async i=>{a(this,Pa).clear(),f(this,Ls,new xD(this.context,this.events,i,this.socket,this.socketHandler))},this.reset()}get socketHandler(){return super.socketHandler}get producers(){return a(this,Qi)}get consumers(){return a(this,Xr)}get producerIdToConsumerIdMap(){return a(this,Pa)}get logger(){return this.context.getValue("logger")}reset(){f(this,Qi,new Map),f(this,Xr,new Map),f(this,Pa,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,$(this,Il,ev).bind(this));return(i=e.appData)!=null&&i.e2ee&&this.context.getValue("peerSessionStore").emit(_.E2EE_ACTIVE_PRODUCER,o),$(this,Al,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,Rl).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(_.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,Qi).entries()).map(([,e])=>e.close()))}createConsumer(e){return this.createConsumers([e])}async createConsumers(e){a(this,_a)||clearTimeout(a(this,_a)),f(this,pr,a(this,pr).concat(e)),await $(this,tc,Xh).call(this)}closeConsumer(e){return this.closeConsumers([e])}async closeConsumers(e){if(!a(this,Ls))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,Ls).close(r);i!=null&&i.length&&this.logger.warn("Failed to close some consumers",{consumerIds:i})}closeAllConsumers(){return this.closeConsumers(Array.from(a(this,Xr).keys()))}async switchConsumersToLayer(e,r){a(this,Ls).switchConsumersToLayer(e,r)}}Qi=new WeakMap,Xr=new WeakMap,Pa=new WeakMap,ec=new WeakMap,Ls=new WeakMap,Rl=new WeakMap,pr=new WeakMap,_a=new WeakMap,tc=new WeakSet,Xh=async function(){if(!this.recvTransport||this.recvTransport.closed)throw new Error("Recv transport is closed");const e=500,r=a(this,pr).splice(0,a(this,pr).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,$(this,Ml,sv).bind(this),a(this,Ls).negotiate.bind(a(this,Ls)));if(o.forEach($(this,Ol,rv).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,pr,a(this,pr).concat(d)),f(this,_a,setTimeout($(this,tc,Xh).bind(this),e))}}catch(i){if(this.logger.error("failed to consume on transport",{error:i}),i.errorCode==="internal_error"&&i.errorDescription==="Backend error"||i.errorCode==="invalid_session_description"){this.logger.error("Irrecoverable error, closing current recvTransport to create a new one",{transport:this.recvTransport,error:{code:i.errorCode,message:i.errorDescription}});try{this.stopTransports({recv:!0})}catch(n){}await this.setupTransports({recv:!0})}}},Il=new WeakSet,ev=function(e){return a(this,ec).create(e)},Al=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!==qd){const d={producerId:e.id,description:{sdp:o.sdp,type:o.type,target:Gs.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,Qi).set(e.id,e)},Ml=new WeakSet,sv=async function(e){try{return await this.recvTransport.canConsume(),await a(this,Ls).create(e)}catch(r){throw this.logger.error("Error in consume request",{error:r}),r}},Ol=new WeakSet,rv=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,Xr).delete(e.id),this.context.getValue("peerSessionStore").emit(_.CONSUMER_CLOSED,{id:e.id})}),a(this,Xr).set(e.id,e),this.producerIdToConsumerIdMap.set(e.producerId,e.id),this.context.getValue("peerSessionStore").emit(_.NEW_CONSUMER,{id:e.id,appData:e.appData,peerId:e.peerId})};const xl=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,Dl);g(this,Nl);g(this,sc,void 0);g(this,rc,void 0);g(this,ic,void 0);g(this,Ca,void 0);g(this,ka,void 0);g(this,Ra,void 0);g(this,nc,void 0);g(this,ac,void 0);g(this,Ia,void 0);g(this,Rt,void 0);g(this,ys,void 0);g(this,Es,!1);g(this,Xi,0);g(this,Zi,0);g(this,mr,[]);g(this,oc,void 0);f(this,Ca,t),f(this,Rt,t),f(this,sc,e),f(this,rc,r),f(this,ic,i),f(this,ka,n),f(this,Ra,o),f(this,nc,c),f(this,ac,d),f(this,Ia,l),f(this,oc,u),f(this,ys,t/2)}get voiceDetected(){return a(this,Es)}processAudioChunk(t){var o,c;const e=$(o=xl,Vl,av).call(o,t),r=$(c=xl,Ll,ov).call(c,t);return $(this,Dl,iv).call(this,e),e/a(this,ys)>a(this,Ia)&&e>a(this,Rt)&&r>a(this,sc)?(f(this,Xi,a(this,Xi)+1),f(this,Zi,a(this,ic)),a(this,Xi)>=a(this,rc)&&f(this,Es,!0)):(f(this,Xi,0),a(this,Zi)>0?f(this,Zi,a(this,Zi)-1):a(this,Es)&&f(this,Es,!1),a(this,Es)||$(this,Nl,nv).call(this,e)),{energy:e,isVoice:a(this,Es)}}reset(){f(this,Es,!1),f(this,Xi,0),f(this,Zi,0),f(this,Rt,a(this,Ca)),f(this,ys,a(this,Ca)/2),f(this,mr,[])}getThresholdInfo(){return{currentEnergyThreshold:a(this,Rt),backgroundNoiseEnergy:a(this,ys),energyRatioThreshold:a(this,Ia)}}};let co=xl;sc=new WeakMap,rc=new WeakMap,ic=new WeakMap,Ca=new WeakMap,ka=new WeakMap,Ra=new WeakMap,nc=new WeakMap,ac=new WeakMap,Ia=new WeakMap,Rt=new WeakMap,ys=new WeakMap,Es=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,mr=new WeakMap,oc=new WeakMap,Dl=new WeakSet,iv=function(t){a(this,Es)?f(this,Rt,a(this,Ra)*a(this,Rt)+(1-a(this,Ra))*t):f(this,Rt,a(this,ka)*a(this,Rt)+(1-a(this,ka))*a(this,ys)),f(this,Rt,Math.max(a(this,nc),Math.min(a(this,ac),a(this,Rt))))},Nl=new WeakSet,nv=function(t){if(t<a(this,Rt)*1.2)if(a(this,mr).push(t),a(this,mr).length>a(this,oc)&&a(this,mr).shift(),a(this,mr).length>=10){const e=[...a(this,mr)].sort((i,n)=>i-n),r=Math.floor(e.length/2);f(this,ys,e[r])}else f(this,ys,.95*a(this,ys)+.05*t)},Vl=new WeakSet,av=function(t){return Math.sqrt(t.map(e=>e*e).reduce((e,r)=>e+r)/t.length)},Ll=new WeakSet,ov=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(co,Vl),g(co,Ll);class jf{constructor(t){p(this,"RNAudioSampleHandler");g(this,cc,void 0);f(this,cc,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,cc).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()}}cc=new WeakMap;class Gf{constructor(t){p(this,"audioContext");p(this,"analyser");g(this,dc,void 0);f(this,dc,t),this.audioContext=new AudioContext,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048}get logger(){return a(this,dc).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)}}dc=new WeakMap;class $D{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 BD=60,FD=400,hc=class{constructor(t,e){g(this,Ul);g(this,$l);g(this,gr,void 0);g(this,fr,void 0);g(this,Sr,void 0);g(this,lc,void 0);g(this,Aa,void 0);g(this,Ma,void 0);g(this,Zr,void 0);g(this,en,void 0);g(this,Oa,void 0);g(this,tn,void 0);g(this,vr,void 0);g(this,xs,void 0);this.reportRequest=e,f(this,tn,t),f(this,Ma,new co);const{isReactNative:r}=navigator;f(this,vr,r?new jf(a(this,tn)):new Gf(a(this,tn))),f(this,xs,r?$D:Cf)}get logger(){return a(this,tn).getValue("logger")}set producerId(t){f(this,Sr,t)}set audioTrack(t){f(this,lc,t),a(this,vr)instanceof Gf&&(a(this,vr).audioTrack=t)}start(){this.logger.debug(`AudioActivityReporter: Starting audio activity reporter: ${a(this,Sr)}`),a(this,gr)&&a(this,xs).clearInterval(a(this,gr)),f(this,gr,a(this,xs).setInterval(async()=>{var i;if(!a(this,lc)||!a(this,Sr))return;const{energy:t}=$(this,Ul,cv).call(this),e=$(i=hc,uc,Zh).call(i,t);let r=.9;a(this,Oa)!==e&&a(this,Oa)?r=.9:e?r=.3:r=.5,f(this,Aa,(a(this,Aa)||0)*(1-r)+t*r)},BD)),a(this,fr)&&a(this,xs).clearInterval(a(this,fr)),f(this,fr,a(this,xs).setInterval($(this,$l,dv).bind(this),FD))}stop(){try{this.logger.debug(`AudioActivityReporter: Stopping audio activity reporter: ${a(this,Sr)}`),a(this,gr)&&(a(this,xs).clearInterval(a(this,gr)),f(this,gr,void 0)),a(this,fr)&&(a(this,xs).clearInterval(a(this,fr)),f(this,fr,void 0))}catch(t){}a(this,Ma).reset(),a(this,vr)instanceof jf&&a(this,vr).stop()}};let lo=hc;gr=new WeakMap,fr=new WeakMap,Sr=new WeakMap,lc=new WeakMap,Aa=new WeakMap,Ma=new WeakMap,Zr=new WeakMap,en=new WeakMap,Oa=new WeakMap,tn=new WeakMap,vr=new WeakMap,xs=new WeakMap,Ul=new WeakSet,cv=function(){var o;const{samples:t}=a(this,vr),{energy:e,isVoice:r}=a(this,Ma).processAudioChunk(t),i=$(o=hc,Bl,lv).call(o,e);return i===-1/0||e<1e-6?{energy:0,isVoice:!1}:((!a(this,Zr)||i<a(this,Zr))&&f(this,Zr,i),(!a(this,en)||i>a(this,en))&&f(this,en,i),{energy:(i-a(this,Zr))/(a(this,en)-a(this,Zr))*10||0,isVoice:r})},uc=new WeakSet,Zh=function(t){return t<5},$l=new WeakSet,dv=function(t=a(this,Aa)){var r;if(!a(this,Sr)||!t)return;const e={producerId:a(this,Sr),energy:Math.round(t),silent:$(r=hc,uc,Zh).call(r,t)};f(this,Oa,e.silent),this.reportRequest(e)},Bl=new WeakSet,lv=function(t){const e=Math.log10(t);return Math.round(e)},g(lo,uc),g(lo,Bl);var HD=Object.defineProperty,qD=Object.getOwnPropertyDescriptor,ae=(s,t,e,r)=>{for(var i=r>1?void 0:r?qD(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 te{constructor(t,e){g(this,ei);g(this,Hl);g(this,ql);g(this,jl);g(this,fc);g(this,Gl);g(this,Wl);g(this,bt);g(this,an);g(this,Jl);g(this,Kl);g(this,zl);p(this,"context");p(this,"authToken");p(this,"e2ee");g(this,pc,void 0);g(this,mc,void 0);g(this,lt,void 0);g(this,G,void 0);g(this,Fl,void 0);g(this,Et,void 0);g(this,sn,void 0);g(this,rn,void 0);g(this,nn,void 0);g(this,gc,void 0);g(this,is,null);g(this,Tr,void 0);g(this,wt,void 0);g(this,It,void 0);var i,n;this.context=t;const{socket:r}=e;this.mediaJoined=!1,f(this,lt,r),f(this,sn,!1),f(this,G,new UD(t,r)),f(this,Et,a(this,G).events),f(this,Tr,new Set),f(this,wt,new Map),f(this,rn,!1),f(this,nn,new Th(t.getValue("logger"))),f(this,It,new lo(this.context,a(this,G).socketHandler.audioActivity.bind(a(this,G).socketHandler))),this.e2ee=(n=(i=t.getValue("modules").e2ee)==null?void 0:i.enabled)!=null?n:!1,this.handleSocketEvents(),this.handleCallstatsEvents(),f(this,gc,ku(async()=>{if(!a(this,ei,xa).mediaJoinAttempted)return;const{roomJoined:o}=await this.joinRoom(a(this,mc),a(this,pc),!0,!0);o&&(this.context.getValue("peerSessionStore").emit(_.RESET_PRODUCER_STATE),this.context.getValue("peerSessionStore").emit(_.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,ei,xa).mediaJoined}set mediaJoined(t){a(this,ei,xa).mediaJoined=t}reset(){a(this,G).closeAllProducers(),a(this,G).closeAllConsumers(),a(this,wt).clear(),a(this,Tr).clear(),f(this,is,null),a(this,nn).stop(),a(this,G).stopAllTransports(),a(this,G).reset(),f(this,nn,new Th)}async joinRoom(t,e,r=!1,i=!1,n={}){a(this,ei,xa).mediaJoinAttempted=!0,f(this,sn,!0),r&&this.reset();try{return await a(this,nn).push(()=>$(this,Hl,uv).call(this,t,e,i,n),"joinRoom")}catch(o){return this.logger.error("Error in room joining process",{error:o}),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_FAILED),{roomJoined:!1,error:o}}}async initializeConnection(t,e,r=!1,i={}){return a(this,is)?a(this,is):(f(this,is,(async()=>{try{await $(this,fc,ep).call(this,t,e,r,i)}catch(n){throw f(this,is,null),n}})()),a(this,is))}getConsumers(){return a(this,G).consumers}getProducers(){return a(this,G).producers}async leaveRoom(){a(this,G).stopAllTransports(),f(this,rn,!1),a(this,ei,xa).mediaJoinAttempted=!1;const t={closeRoom:!1};a(this,lt).sendMessagePromise(a(this,Et).leaveRoom,KC.toBinary(t)).then(r=>{var i;(i=Lk.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,G).createConsumers(t)}async closeConsumers(t){if(!t.length)return;const e=t.reduce((r,i)=>{const n=a(this,G).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,G).closeConsumers(e)}async _shareWebcam(t){var u,h,m,S;const e=Ie.WEBCAM,r=$(this,bt,Wt).call(this,e);if(r){const y=await r;if(a(this,G).producers.has(y)){const w=a(this,G).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=$(this,zl,vv).call(this,t),n=yn(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=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,wt).delete(e)},l=a(this,G).createProducer(i,d);return $(this,an,Hc).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:ge.isElectron()},stopTracks:!1},n=()=>{this.logger.info("Disabling screenShare due to the producer closure"),a(this,wt).delete(Ie.SCREENSHARE_VIDEO),a(this,wt).delete(Ie.SCREENSHARE_AUDIO)},o=a(this,G).createProducer(i,n);$(this,an,Hc).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:ge.isElectron()},stopTracks:!1,zeroRtpOnPause:!1},l=()=>{};c=a(this,G).createProducer(d,l),$(this,an,Hc).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 Ct("track undefined");const e=$(this,bt,Wt).call(this,Ie.MIC);if(e){const o=await e;if(a(this,G).producers.has(o)){const c=a(this,G).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,G).closeProducer(o,{stopTrack:!1})}await this.shareMic(t);return}const r=$(this,Kl,Sv).call(this,t),i=()=>{a(this,wt).delete(Ie.MIC)},n=a(this,G).createProducer(r,i);$(this,an,Hc).call(this,Ie.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 C(e)}}async pauseMic(){var i;const t=await $(this,bt,Wt).call(this,Ie.MIC),e=a(this,G).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,lt).sendMessage(a(this,Et).toggleProducer,wd.toBinary(r))}async pauseWebcam(){const t=await $(this,bt,Wt).call(this,Ie.WEBCAM),e=a(this,G).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,lt).sendMessage(a(this,Et).toggleProducer,wd.toBinary(r))}async resumeMic(){const t=await $(this,bt,Wt).call(this,Ie.MIC),e=a(this,G).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(_.E2EE_ACTIVE_PRODUCER,e);const r={producerId:e.id,pause:!1};a(this,lt).sendMessage(a(this,Et).toggleProducer,wd.toBinary(r))}async resumeWebcam(t=Ie.WEBCAM){const e=await $(this,bt,Wt).call(this,t),r=a(this,G).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(_.E2EE_ACTIVE_PRODUCER,r);const i={producerId:r.id,pause:!1};a(this,lt).sendMessage(a(this,Et).toggleProducer,wd.toBinary(i))}async disableWebcam(){const t=Ie.WEBCAM,e=await $(this,bt,Wt).call(this,t);$(this,Jl,fv).call(this,t),e&&await a(this,G).closeProducer(e)}async disableMic(){var e;const t=await $(this,bt,Wt).call(this,Ie.MIC);t&&await a(this,G).closeProducer(t),(e=a(this,It))==null||e.stop(),a(this,wt).delete(Ie.MIC)}async disableScreenShare(){this.logger.info("screen_sharing_stopped"),this.context.getValue("callstats").screenShareStop();const t=await $(this,bt,Wt).call(this,Ie.SCREENSHARE_VIDEO),e=await $(this,bt,Wt).call(this,Ie.SCREENSHARE_AUDIO);t&&await a(this,G).closeProducer(t),e&&await a(this,G).closeProducer(e),a(this,Tr).clear(),a(this,wt).delete(Ie.SCREENSHARE_VIDEO),a(this,wt).delete(Ie.SCREENSHARE_AUDIO)}async muteSelf(){this.pauseMic()}async resetVideoProducers(t,e){if(t){const r=await $(this,bt,Wt).call(this,Ie.WEBCAM);await a(this,G).closeProducer(r,{stopTrack:!1}),this.shareWebcam(t)}if(e){const r=await $(this,bt,Wt).call(this,Ie.SCREENSHARE_VIDEO);await a(this,G).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,G).socketHandler.changeDisplayName(r))throw new Error("failed to change display name!")}kick(t){const e={peerIds:[t]};a(this,G).socketHandler.kickPeer(e)}kickAll(){a(this,G).socketHandler.kickAll()}async muteAll(t){if(!await a(this,G).socketHandler.hostControlForAll("audio"))throw new Error("failed to mute all participant")}async muteAllVideo(){if(!await a(this,G).socketHandler.hostControlForAll("video"))throw new Error("failed to mute all video participant")}async disableAudio(t){if(!await a(this,G).socketHandler.hostControlForPeer(t,"audio"))throw new Error("failed to mute given participant")}async disableVideo(t){if(!await a(this,G).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,lt).sendMessagePromise(a(this,Et).globalPinPeer,ck.toBinary(e))}catch(r){this.logger.error("Error in pinning peer:",{error:r})}}validateScreenShare(t){return this.peerId===t.peerId&&a(this,G).producers.get(t.producerId)&&a(this,Tr).add(t.consumerPeerId),a(this,Tr).size}async switchConsumersToLayer(t,e){const r=t.map(i=>this.getConsumers().get(i));a(this,G).switchConsumersToLayer(r,e)}async handleSocketEvents(){a(this,lt).on(a(this,Et).peerProducerCreateBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:r}=hR.fromBinary(t);if(e===this.peerId)return;r!=null&&r.mimeType||(r.mimeType=r.kind===Ws.AUDIO?"audio/opus":"video/VP8"),this.logger.info(`producer created broadcast: ${e}, producer state: ${r}`),this.context.getValue("peerSessionStore").emit(_.NEW_PRODUCER,{peerId:e,producer:{...r,kind:r.kind===Ws.AUDIO?"audio":"video",producingPeerId:e}})}catch(e){this.logger.error("error in peer-producer-create-broadcast",{error:e})}}),a(this,lt).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}}=Lg.fromBinary(t);if(c)return;const d=i===Ws.AUDIO?"audio":"video";if(this.logger.info(`producer toggle broadcast: ${e}, producerId: ${o}, kind:${d}, paused:${n} payload: ${JSON.stringify(Lg.fromBinary(t))}`),e===this.peerId&&r!==this.peerId&&n&&this.context.getValue("peerSessionStore").emit(d==="audio"?_.MUTE_SELF:_.MUTE_SELF_VIDEO),e===this.peerId)return;this.context.getValue("peerSessionStore").emit(_.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(_.CONSUMER_PAUSED,{id:u.id})):(u.resume(),this.context.getValue("peerSessionStore").emit(_.CONSUMER_RESUMED,{id:u.id})))})}catch(e){this.logger.error("error in producer toggle broadcast handler",{error:e})}}),a(this,lt).on(a(this,Et).peerLeaveBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e}=Bu.fromBinary(t);if(e===this.peerId)return;this.logger.info(`peer left broadcast:${e}`),a(this,Tr).delete(e),a(this,G).consumers.forEach(r=>{r.peerId===e&&r.close()}),this.context.getValue("peerSessionStore").emit(_.PEER_CLOSED,{id:e})}catch(e){this.logger.error("error in peer left broadcast",{error:e})}}),a(this,lt).on(a(this,Et).peerProducerCloseBroadcast,({payload:t})=>{if(this.mediaJoined)try{const{participantId:e,producerState:{producerId:r}}=gR.fromBinary(t);if(e===this.peerId)return;this.logger.info(`producer closed broadcast:${e}`),this.context.getValue("peerSessionStore").emit(_.PRODUCER_CLOSED,{peerId:e,producerId:r});const i=a(this,G).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,G).closeConsumer(i).then(()=>{this.logger.info(`closed consumer: ${i}`),a(this,G).producerIdToConsumerIdMap.delete(r),this.context.getValue("peerSessionStore").emit(_.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,lt).on(a(this,Et).mediaRoomTerminationBroadcastResponse,()=>{!this.mediaJoined&&!a(this,sn)&&!a(this,rn)||(this.logger.warn("media hub termination broadcast received, rejoining room"),this.context.getValue("peerSessionStore").emit(_.ROOM_NODE_DISCONNECTED),a(this,gc).call(this))})}handleCallstatsEvents(){this.context.getValue("callstats").onConsumerScore(t=>{t.forEach((e,r)=>{const i=a(this,G).consumers.get(r);i&&this.context.getValue("peerSessionStore").emit(_.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,G).producers.values()).find(n=>n.id===r);i&&this.context.getValue("peerSessionStore").emit(_.PRODUCER_SCORE_UPDATE,{id:r,kind:i.kind,appData:i.appData,score:e.score,scoreStats:e})})})}}pc=new WeakMap,mc=new WeakMap,lt=new WeakMap,G=new WeakMap,Fl=new WeakMap,Et=new WeakMap,sn=new WeakMap,rn=new WeakMap,nn=new WeakMap,gc=new WeakMap,is=new WeakMap,Tr=new WeakMap,wt=new WeakMap,It=new WeakMap,ei=new WeakSet,xa=function(){return this.context.getValue("connectionHandler")},Hl=new WeakSet,uv=async function(t,e,r,i){f(this,mc,t);try{a(this,is)?await a(this,is):await $(this,fc,ep).call(this,t,e,r,i),$(this,jl,pv).call(this,e);const{joined:n,error:o}=await $(this,ql,hv).call(this);return{roomJoined:n,error:o}}catch(n){return this.logger.error("Failed to complete room join",{error:n}),{roomJoined:!1,error:n}}finally{f(this,is,null)}},ql=new WeakSet,hv=async function(){try{this.mediaJoined=!0;const{roomState:t}=await a(this,G).socketHandler.notifySelfJoinComplete();return f(this,pc,t.roomUuid),f(this,rn,!0),f(this,sn,!1),{joined:!0}}catch(t){return this.logger.error("Error completing room join",{error:t}),this.mediaJoined=!1,{joined:!1,error:t}}},jl=new WeakSet,pv=function(t){navigator.product!=="ReactNative"&&setTimeout(()=>{try{const r={userId:this.context.getValue("userId"),peerId:this.peerId,roomUUID:t,roomViewType:"groupCall",deviceInfo:{...ge.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)},fc=new WeakSet,ep=async function(t,e,r,i){try{const n=$(this,Gl,mv).call(this);await $(this,Wl,gv).call(this,t,e,r,n),await a(this,G).setupTransports({send:!0,recv:!0})}catch(n){throw this.logger.error("Failed to initialize connection",{error:n}),n}},Gl=new WeakSet,mv=function(){const t=TD("video/VP8");return f(this,Fl,t),t},Wl=new WeakSet,gv=async function(t,e,r,i){await $f(async(n,o)=>{if(!a(this,lt).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,G).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,wt).get(t)},an=new WeakSet,Hc=function(t,e){return a(this,wt).set(t,e)},Jl=new WeakSet,fv=function(t){return a(this,wt).delete(t)},Kl=new WeakSet,Sv=function(t){return{track:t,encodings:[{priority:"high"}],codecOptions:[{name:"opus"}],appData:{e2ee:this.e2ee},stopTracks:!1,zeroRtpOnPause:!1}},zl=new WeakSet,vv=function(t){return{track:t,codecOptions:[{name:"VP8"}],appData:{screenShare:!1,e2ee:this.e2ee},stopTracks:!1}},ae([E.trace("MediaNodeClient.reset")],te.prototype,"reset",1),ae([E.trace("MediaNodeClient.joinRoom")],te.prototype,"joinRoom",1),ae([E.trace("MediaNodeClient.leaveRoom")],te.prototype,"leaveRoom",1),ae([E.trace("MediaNodeClient.activatePeers")],te.prototype,"activatePeers",1),ae([E.trace("MediaNodeClient.createConsumers")],te.prototype,"createConsumers",1),ae([E.trace("MediaNodeClient.closeConsumers")],te.prototype,"closeConsumers",1),ae([E.trace("MediaNodeClient._shareWebcam")],te.prototype,"_shareWebcam",1),ae([E.trace("MediaNodeClient.shareWebcam")],te.prototype,"shareWebcam",1),ae([E.trace("MediaNodeClient.shareScreen")],te.prototype,"shareScreen",1),ae([E.trace("MediaNodeClient.shareMic")],te.prototype,"shareMic",1),ae([E.trace("MediaNodeClient.pauseMic")],te.prototype,"pauseMic",1),ae([E.trace("MediaNodeClient.pauseWebcam")],te.prototype,"pauseWebcam",1),ae([E.trace("MediaNodeClient.resumeMic")],te.prototype,"resumeMic",1),ae([E.trace("MediaNodeClient.resumeWebcam")],te.prototype,"resumeWebcam",1),ae([E.trace("MediaNodeClient.disableWebcam")],te.prototype,"disableWebcam",1),ae([E.trace("MediaNodeClient.disableMic")],te.prototype,"disableMic",1),ae([E.trace("MediaNodeClient.disableScreenShare")],te.prototype,"disableScreenShare",1),ae([E.trace("MediaNodeClient.muteSelf")],te.prototype,"muteSelf",1),ae([E.trace("MediaNodeClient.resetVideoProducers")],te.prototype,"resetVideoProducers",1),ae([E.trace("MediaNodeClient.changeDisplayName")],te.prototype,"changeDisplayName",1),ae([E.trace("MediaNodeClient.kickPeer")],te.prototype,"kick",1),ae([E.trace("MediaNodeClient.kickAllPeers")],te.prototype,"kickAll",1),ae([E.trace("MediaNodeClient.muteAll")],te.prototype,"muteAll",1),ae([E.trace("MediaNodeClient.muteAllVideo")],te.prototype,"muteAllVideo",1),ae([E.trace("MediaNodeClient.disableAudio")],te.prototype,"disableAudio",1),ae([E.trace("MediaNodeClient.disableVideo")],te.prototype,"disableVideo",1),ae([E.trace("MediaNodeClient.pinPeer")],te.prototype,"pinPeer",1),ae([E.trace("MediaNodeClient.validateScreenShare")],te.prototype,"validateScreenShare",1);function Wf(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 te(s,t);return s.setValue("roomNodeClient",r),r}function jD(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 GD=Object.defineProperty,WD=Object.getOwnPropertyDescriptor,yi=(s,t,e,r)=>{for(var i=r>1?void 0:r?WD(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&&GD(t,e,i),i};const Jf=(NS=class{constructor(s,t,e,r){g(this,At);p(this,"self");p(this,"authToken");g(this,Da,void 0);p(this,"viewType");g(this,ws,void 0);g(this,Q,void 0);const{socket:i}=e,n=s.getValue("authToken");this.self=t,f(this,Q,s),this.viewType=r,this.authToken=n,f(this,Da,i),f(this,ws,e),this.setupEvents()}get peerId(){return a(this,Q).getValue("peerId")}get telemetry(){return a(this,Q).getValue("telemetry")}get logger(){return a(this,Q).getValue("logger")}get mediaJoined(){return a(this,Q).getValue("connectionHandler").mediaJoined}static async init(s,t,e,r,i){const n=Pt(),o=s.getValue("peerId"),c=!!s.getValue("cachedUserDetails"),d=await We.__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:ge.getDeviceInfo().engineName,env:s.getValue("env")==="prod"?"prod":"devel",iceServers:await n.getICEServers(),apiBase:s.getValue("apiBase"),flags:{},logger:l,apiHostnames:p_(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 Jf(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===q.Allowed&&r)try{await a(this,At,as).shareMic(s),this.self.audioEnabled||a(this,At,as).pauseMic()}catch(d){this.self.disableAudio()}if(e.canProduceVideo===q.Allowed&&i)try{await a(this,At,as).shareWebcam(t),this.self.videoEnabled||a(this,At,as).pauseWebcam()}catch(d){this.self.disableVideo()}if(e.canProduceScreenshare===q.Allowed&&n)try{await((c=a(this,At,as))==null?void 0:c.shareScreen({video:o.video,audio:o.audio}))}catch(d){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,Q).getValue("callstats").callEnded(),a(this,At,as).reset(),s&&await this.joinRoom(s)}setupEvents(){a(this,Q).getValue("peerSessionStore").on(_.RESET_PRODUCER_STATE,async()=>{this.mediaJoined&&this.shareMediaTracks()}),a(this,Q).getValue("peerSessionStore").on(_.ROOM_NODE_RECONNECTED,()=>{this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:!0})}),a(this,Q).getValue("peerSessionStore").on(_.ROOM_NODE_DISCONNECTED,()=>{this.self.roomState!=="disconnected"&&(this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"}))}),a(this,Q).getValue("peerSessionStore").on(_.ROOM_NODE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,Q).getValue("peerSessionStore").on(_.SOCKET_SERVICE_RECONNECTED,({wasJoinAttempted:s})=>{s===!1&&(this.self.roomState="init"),this.resetSelf(s)}),a(this,Q).getValue("peerSessionStore").on(_.SOCKET_SERVICE_DISCONNECTED,({joinAttempted:s})=>{if(this.self.roomState==="disconnected")return;const{peerId:t}=this;a(this,Da).updateURL(t),a(this,Q).getValue("telemetry").resetPeerId(t),Pt().setHeader("tracing-id",t),Pr.remapContext(t,a(this,Q)),this.self.roomState="disconnected",this.self.emit("roomLeft",{state:"disconnected"})}),a(this,Q).getValue("peerSessionStore").on(_.SOCKET_SERVICE_FAILED,()=>{this.self.roomState="failed",this.self.emit("roomLeft",{state:"failed"})}),a(this,ws).on(x.waitingRoomRequestAccepted,()=>{this.waitlistAcceptHandler()}),a(this,ws).on(Rd.updateUserPreset,s=>{s.updatePeersPresets.forEach(t=>{t.userIds===this.self.userId&&a(this,Q).getValue("peerSessionStore").emit(_.UPDATE_PERMISSIONS,t.patch)})}),a(this,ws).on(x.waitingRoomRequestDenied,()=>{this.waitlistRejectedHandler()}),a(this,ws).on(x.kick,()=>{this.kickHandler({kickType:"kick"})}),a(this,ws).on(x.kickAll,()=>{this.kickHandler({kickType:"kickAll"})}),a(this,Q).getValue("peerSessionStore").onAsync(_.JOIN_MEDIA_ROOM,this.joinMediaRoom.bind(this)),a(this,Q).getValue("peerSessionStore").on(_.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,Q).getValue("peerSessionStore").on(_.MUTE_SELF,async()=>{this.self.audioEnabled&&(await this.self.disableAudio(),a(this,Q).getValue("callstats").audioOff())}),a(this,Q).getValue("peerSessionStore").on(_.MUTE_SELF_VIDEO,async()=>{this.self.videoEnabled&&(await this.self.disableVideo(),a(this,Q).getValue("callstats").videoOff())}),a(this,Q).getValue("peerSessionStore").onAsync(_.LEAVE_MEDIA_ROOM,this.leaveMediaRoom.bind(this)),a(this,Q).getValue("peerSessionStore").on(_.PIP_HANGUP,this.leaveRoom.bind(this))}async joinRoom(s=!1){try{const{peer:t}=await a(this,ws).joinRoom(this.self);a(this,ws).socket.flush();const e=nh(t.stageType);if(a(this,Q).setValue("stageStatus",e,!1),t.waitlisted){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{await this.joinMediaRoom(s),a(this,Q).notify("stageStatus")}catch(t){throw this.logger.error("SelfController.joinRoom: media room join failed",{error:t}),t instanceof Or&&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,Q).setValue("stageStatus","OFF_STAGE",!1),await this.leaveMediaRoom(s),a(this,Q).setValue("roomNodeClient",void 0),a(this,Q).notify("stageStatus"),(t=a(this,Q).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,Q).getAllValues();try{if(e===qs.Livestream){if(i!=="ON_STAGE"){this.self.roomState="joined",this.self.emit("roomJoined",{reconnected:s});return}Wf(a(this,Q),{socket:a(this,Da),peerId:t})}const{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l}=this.self.permissions,{roomJoined:u,error:h}=(o=await((n=a(this,At,as))==null?void 0:n.joinRoom(this.self.name,r,s,s,{canProduceAudio:c,canProduceVideo:d,canProduceScreenshare:l})))!=null?o:{};if(!u)throw h!=null?h:new Error("Could not connect to media server");i==="ON_STAGE"&&await this.shareMediaTracks(),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,Q).getValue("viewType");s!=="connected-meeting"&&await this.cleanupSelf(),!(s==="stageLeft"&&t===qs.Webinar)&&a(this,At,as)&&(a(this,At,as).mediaJoined&&s!=="disconnected"&&await a(this,At,as).leaveRoom(),!(s==="stageLeft"&&t===qs.Livestream)&&(a(this,At,as).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()}},Da=new WeakMap,ws=new WeakMap,Q=new WeakMap,At=new WeakSet,as=function(){return a(this,Q).getValue("roomNodeClient")},NS);let Dr=Jf;yi([E.trace("SelfController.resetSelf")],Dr.prototype,"resetSelf",1),yi([E.trace("SelfController.setupEvents")],Dr.prototype,"setupEvents",1),yi([E.trace("SelfController.joinRoom")],Dr.prototype,"joinRoom",1),yi([E.trace("SelfController.leaveRoom")],Dr.prototype,"leaveRoom",1),yi([E.trace("SelfController.joinMediaRoom")],Dr.prototype,"joinMediaRoom",1),yi([E.trace("SelfController.leaveMediaRoom")],Dr.prototype,"leaveMediaRoom",1),yi([E.trace("SelfController.init")],Dr,"init",1);class JD{constructor(t){g(this,Sc,void 0);f(this,Sc,t)}on(t,e){let r;t===x.roomPeerCount?r=$g.fromBinary.bind($g):r=Zg.fromBinary.bind(Zg),a(this,Sc).on(t,({payload:i})=>{if(t===x.roomPeerCount&&!i)return;const n=r(i);e(n)})}}Sc=new WeakMap;class KD{constructor(t,e){g(this,vc,void 0);g(this,Tc,void 0);f(this,vc,e),f(this,Tc,t)}get logger(){return a(this,Tc).getValue("logger")}on(t,e){let r,i;switch(t){case x.transcript:{r=Fu.fromBinary.bind(Fu),i=Fu.create();break}default:{this.logger.debug("AISocketHandler switch case hit default, event not accounted for.");break}}a(this,vc).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)})}}vc=new WeakMap,Tc=new WeakMap;var zD=Object.defineProperty,YD=Object.getOwnPropertyDescriptor,kh=(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&&zD(t,e,i),i};class jd{constructor(t,e){g(this,yr,void 0);g(this,Na,void 0);f(this,yr,e),f(this,Na,t)}get logger(){return a(this,Na).getValue("logger")}get telemetry(){return a(this,Na).getValue("telemetry")}getPolls(){return a(this,yr).sendMessagePromise(zs.getPolls)}createPoll(t,e,r=!1,i=!1){const n={anonymous:r,hideVotes:i,question:t,options:e};return a(this,yr).sendMessage(zs.createPoll,jA.toBinary(n))}votePoll(t,e){const r={index:e,pollId:t};return a(this,yr).sendMessage(zs.votePoll,WA.toBinary(r))}on(t,e){let r,i;switch(t){case zs.updatePoll:case zs.createPoll:case zs.votePoll:{r=Zu.fromBinary.bind(Zu),i=Zu.create();break}}a(this,yr).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,yr).removeListeners(t)}}yr=new WeakMap,Na=new WeakMap,kh([E.trace("PollSocketHandler.getPolls")],jd.prototype,"getPolls",1),kh([E.trace("PollSocketHandler.createPoll")],jd.prototype,"createPoll",1),kh([E.trace("PollSocketHandler.votePoll")],jd.prototype,"votePoll",1);var QD=Object.defineProperty,XD=Object.getOwnPropertyDescriptor,ZD=(s,t,e,r)=>{for(var i=r>1?void 0:r?XD(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&&QD(t,e,i),i};class Kf{constructor(t,e){p(this,"socket");g(this,jt,void 0);f(this,jt,t),this.socket=e,this.handleSocketEvents(),a(this,jt).setValue("roomSocketHandler",this)}get telemetry(){return a(this,jt).getValue("telemetry")}get logger(){return a(this,jt).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(x.joinRoom,jR.toBinary(e));try{const{peer:n}=bn.fromBinary((await r).payload);a(this,jt).getValue("connectionHandler").socketJoined=!0,a(this,jt).getValue("peerSessionStore").emit(_.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,jt).getValue("peerSessionStore").emit(_.ROOM_STATE,d),a(this,jt).getValue("peerSessionStore").emit(_.SOCKET_PEERS,l),{peer:n}}catch(n){throw this.logger.error("RoomSocketHandler.joinRoom.failed",{error:n}),n}}async getAllAddedParticipants(){try{return R0.fromBinary((await this.socket.sendMessagePromise(x.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(x.getRoomPeersInfo,NR.toBinary(n));i=ju.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(x.getRoomPeersInfo);t=ju.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(x.getRoomPeersInfo);t=ju.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(x.getPeerInfo,Hg.toBinary({peerId:t}));e=bn.fromBinary(r.payload)}catch(r){this.logger.error("getPeerInfo::binary_decode_error",{error:r})}return e}async getRoomState(){let t=Fg.create();try{const e=await this.socket.sendMessagePromise(x.getRoomInfo);t=Fg.fromBinary(e.payload)}catch(e){this.logger.error("getRoomState::binary_decode_error",{error:e})}return t}async getRoomStageState(){let t=Kg.create();try{const e=await this.socket.sendMessagePromise(x.getRoomStageState);t=Kg.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(x.broadcastMessage,Xa.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(x.broadcastToEntity,Xa.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(x.broadcastToEntity,Xa.toBinary(i))}async leaveRoom(){this.socket.joinAttempted=!1,this.socket.sendMessagePromise(x.leaveRoom,WR.toBinary({}))}async kick(t){const e={peerIds:[t]};this.socket.sendMessage(x.kick,Wg.toBinary(e))}async kickAll(t=!1){const e={propagateKickAcrossRooms:t};this.socket.sendMessage(x.kickAll,Mg.toBinary(e))}getWaitingRoomRequests(){this.socket.sendMessage(x.getWaitingRoomRequests)}acceptWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.acceptWaitingRoomRequests,N0.toBinary(e))}rejectWaitingRoomRequest(t){const e={userIds:t};this.socket.sendMessage(x.denyWaitingRoomRequests,L0.toBinary(e))}async updatePermissions(t,e){const r={updatePeersPresets:[]};return t.forEach(i=>{r.updatePeersPresets.push({userIds:i,patch:e})}),this.socket.sendMessagePromise(Rd.updateUserPreset,uI.toBinary(r))}handleSocketEvents(){this.socket.on(x.broadcastMessage,({payload:t})=>{try{const e=Xa.fromBinary(t);a(this,jt).getValue("peerSessionStore").emit(_.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(x.broadcastToEntity,({payload:t})=>{try{const e=Xa.fromBinary(t);a(this,jt).getValue("peerSessionStore").emit(_.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 x.joinRoom:case x.leaveRoom:case x.kick:case x.kickAll:{r=bn.fromBinary.bind(bn),i=bn.create();break}case x.getWaitingRoomRequests:{r=(n,o)=>n?Jg.fromBinary(n,o):{requests:[]},i=Jg.create();break}case x.recordingPaused:case x.recordingStarted:case x.recordingStopped:{r=rf.fromBinary.bind(rf);break}case Rd.updateUserPreset:{r=Yg.fromBinary.bind(Yg);break}case us.peerJoinedBroadcast:case kr.peerJoinedBroadcast:{r=Ng.fromBinary.bind(Ng);break}case us.selfJoinComplete:case kr.selfJoinComplete:{r=$u.fromBinary.bind($u);break}case us.globalPeerPinBroadcast:case kr.globalPeerPinBroadcast:{r=xg.fromBinary.bind(xg);break}case us.selectedPeer:case kr.selectedPeer:{r=Uu.fromBinary.bind(Uu);break}case us.selectedPeerDiff:case kr.selectedPeerDiff:{r=Dg.fromBinary.bind(Dg);break}case us.leaveRoom:case kr.leaveRoom:{r=Bu.fromBinary.bind(Bu);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(Rd.getUserPresets,iI.toBinary(e)),i=cI.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}}}jt=new WeakMap,ZD([E.trace("RoomSocketHandler.joinRoom")],Kf.prototype,"joinRoom",1);class e1{constructor(t){g(this,Mt,void 0);f(this,Mt,t)}async getStageRequests(){const{payload:t}=await a(this,Mt).sendMessagePromise(x.getStageRequests);return t?Xu.fromBinary(t):{stageRequests:[]}}requestAccess(){a(this,Mt).sendMessage(x.requestStageAccess)}cancelRequestAccess(){a(this,Mt).sendMessage(x.cancelStageRequest)}async grantAccess(t){const e={userIds:t};a(this,Mt).sendMessage(x.grantStageAccess,NA.toBinary(e))}async denyAccess(t){const e={userIds:t};a(this,Mt).sendMessage(x.denyStageAccess,LA.toBinary(e))}joinStage(){return a(this,Mt).sendMessagePromise(x.joinStage,void 0,void 0,x.peerStageStatusUpdate)}leaveStage(t){const e={userIds:[t]};return a(this,Mt).sendMessagePromise(x.leaveStage,tf.toBinary(e),void 0,x.peerStageStatusUpdate)}kick(t){const e={userIds:t};return a(this,Mt).sendMessagePromise(x.leaveStage,tf.toBinary(e))}on(t,e){let r;switch(t){case x.grantStageAccess:case x.denyStageAccess:{r=void 0;break}case x.getStagePeers:{r=ef.fromBinary.bind(ef);break}case x.getStageRequests:case x.requestStageAccess:case x.cancelStageRequest:{r=Xu.fromBinary.bind(Xu);break}case x.peerStageStatusUpdate:{r=Ug.fromBinary.bind(Ug);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(x.getPeerInfo,Hg.toBinary({peerId:t}));return bn.fromBinary(e.payload)}}Mt=new WeakMap;class t1{constructor(t,e){g(this,ti,void 0);g(this,Va,void 0);f(this,ti,e),f(this,Va,t)}get logger(){return a(this,Va).getValue("logger")}get peerId(){return a(this,Va).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,ti).sendMessage(Ks.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,ti).sendMessage(Ks.storeGetKeys,fA.toBinary(n),i)}storeDeleteKeys(t,e,r,i){const n={pluginId:t,storeName:e,deleteKeys:r.map(o=>({storeKey:o.key}))};a(this,ti).sendMessage(Ks.storeDeleteKeys,vA.toBinary(n),i)}on(t,e){const r=Xg.fromBinary.bind(Xg);a(this,ti).on(t,({payload:i,id:n})=>{const o=r(i);return e(o,n)})}}ti=new WeakMap,Va=new WeakMap;var s1=Object.defineProperty,r1=(s,t,e)=>t in s?s1(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,i1=(s,t,e)=>(r1(s,typeof t!="symbol"?t+"":t,e),e),Rh=(s,t,e)=>{if(!t.has(s))throw TypeError("Cannot "+e)},O=(s,t,e)=>(Rh(s,t,"read from private field"),e?e.call(s):t.get(s)),ve=(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)},se=(s,t,e,r)=>(Rh(s,t,"write to private field"),r?r.call(s,e):t.set(s,e),e),Ee=(s,t,e)=>(Rh(s,t,"access private method"),e),Gd={},n1={get exports(){return Gd},set exports(s){Gd=s}},Mn=typeof Reflect=="object"?Reflect:null,zf=Mn&&typeof Mn.apply=="function"?Mn.apply:function(s,t,e){return Function.prototype.apply.call(s,t,e)},Wd;Mn&&typeof Mn.ownKeys=="function"?Wd=Mn.ownKeys:Object.getOwnPropertySymbols?Wd=function(s){return Object.getOwnPropertyNames(s).concat(Object.getOwnPropertySymbols(s))}:Wd=function(s){return Object.getOwnPropertyNames(s)};function a1(s){console&&console.warn&&console.warn(s)}var Yf=Number.isNaN||function(s){return s!==s};function oe(){oe.init.call(this)}n1.exports=oe,Gd.once=l1,oe.EventEmitter=oe,oe.prototype._events=void 0,oe.prototype._eventsCount=0,oe.prototype._maxListeners=void 0;var Qf=10;function Jd(s){if(typeof s!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof s)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return Qf},set:function(s){if(typeof s!="number"||s<0||Yf(s))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+s+".");Qf=s}}),oe.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},oe.prototype.setMaxListeners=function(s){if(typeof s!="number"||s<0||Yf(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 Xf(s){return s._maxListeners===void 0?oe.defaultMaxListeners:s._maxListeners}oe.prototype.getMaxListeners=function(){return Xf(this)},oe.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")zf(c,this,t);else for(var d=c.length,l=rS(c,d),e=0;e<d;++e)zf(l[e],this,t);return!0};function Zf(s,t,e,r){var i,n,o;if(Jd(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=Xf(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,a1(c)}return s}oe.prototype.addListener=function(s,t){return Zf(this,s,t,!1)},oe.prototype.on=oe.prototype.addListener,oe.prototype.prependListener=function(s,t){return Zf(this,s,t,!0)};function o1(){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 eS(s,t,e){var r={fired:!1,wrapFn:void 0,target:s,type:t,listener:e},i=o1.bind(r);return i.listener=e,r.wrapFn=i,i}oe.prototype.once=function(s,t){return Jd(t),this.on(s,eS(this,s,t)),this},oe.prototype.prependOnceListener=function(s,t){return Jd(t),this.prependListener(s,eS(this,s,t)),this},oe.prototype.removeListener=function(s,t){var e,r,i,n,o;if(Jd(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},oe.prototype.off=oe.prototype.removeListener,oe.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 tS(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?d1(i):rS(i,i.length)}oe.prototype.listeners=function(s){return tS(this,s,!0)},oe.prototype.rawListeners=function(s){return tS(this,s,!1)},oe.listenerCount=function(s,t){return typeof s.listenerCount=="function"?s.listenerCount(t):sS.call(s,t)},oe.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}oe.prototype.eventNames=function(){return this._eventsCount>0?Wd(this._events):[]};function rS(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 d1(s){for(var t=new Array(s.length),e=0;e<t.length;++e)t[e]=s[e].listener||s[e];return t}function l1(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))}iS(s,t,n,{once:!0}),t!=="error"&&u1(s,i,{once:!0})})}function u1(s,t,e){typeof s.on=="function"&&iS(s,"error",t,e)}function iS(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 h1 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 nS=new h1;class aS{static encode(t){return nS.toBinary(t)}static decode(t){return nS.fromBinary(new Uint8Array(t))}}function p1(s,t){return Math.floor(Math.random()*(t-s+1)+s)}var Nr;class m1{constructor(t={}){i1(this,"opts"),ve(this,Nr,void 0),this.opts={initialTimeout:t.initialTimeout||1e3,maxTimeout:t.maxTimeout||1e4,factor:t.factor||2},se(this,Nr,0)}async wait(){se(this,Nr,O(this,Nr)+1);const t=p1(0,Math.min(this.opts.maxTimeout,this.opts.initialTimeout*2**O(this,Nr)));await new Promise(e=>{setTimeout(e,t)})}getAttempts(){return O(this,Nr)}reset(){se(this,Nr,0)}}Nr=new WeakMap;const Vr={debug:0,info:1,warn:2,error:3};var Ei,wi;class g1{constructor(t){ve(this,Ei,void 0),ve(this,wi,void 0),se(this,Ei,console),se(this,wi,t)}debug(...t){Vr[O(this,wi)]>Vr.debug||O(this,Ei).debug("[Sockrates]:",...t)}info(...t){Vr[O(this,wi)]>Vr.info||O(this,Ei).info("[Sockrates]:",...t)}warn(...t){Vr[O(this,wi)]>Vr.warn||O(this,Ei).warn("[Sockrates]:",...t)}error(...t){Vr[O(this,wi)]>Vr.error||O(this,Ei).error("[Sockrates]:",...t)}}Ei=new WeakMap,wi=new WeakMap;var oS=(s=>(s[s.CONNECTING=0]="CONNECTING",s[s.OPEN=1]="OPEN",s[s.CLOSING=2]="CLOSING",s[s.CLOSED=3]="CLOSED",s))(oS||{});const f1="2",S1="3";var Ae,On,we,Le,Lr,Je,tr,xr,ms,Dn,sr,Ih,cS,uo,Kd,Ah,dS,Mh,lS,zd,Oh,Dh,uS,ho,Yd,po,Qd,Xd,Nh,Nn,mo,go,Zd;class v1{constructor(t,e){var m,S,y,w,b,R,N,U,L,F;ve(this,Ih),ve(this,uo),ve(this,Ah),ve(this,Mh),ve(this,zd),ve(this,Dh),ve(this,ho),ve(this,po),ve(this,Xd),ve(this,Nn),ve(this,go),ve(this,Ae,void 0),ve(this,On,void 0),ve(this,we,void 0),ve(this,Le,void 0),ve(this,Lr,void 0),ve(this,Je,void 0),ve(this,tr,void 0),ve(this,xr,void 0),ve(this,ms,void 0),ve(this,Dn,void 0),ve(this,sr,void 0);var r,i,n,o,c,d,l,u,h;se(this,On,t),se(this,Lr,[]),se(this,Je,new Gd),se(this,tr,!0),se(this,ms,!1),se(this,we,e!=null?e:{}),(m=(r=O(this,we)).autoReconnect)!=null||(r.autoReconnect=!0),(S=(i=O(this,we)).retryConnectionInterval)!=null||(i.retryConnectionInterval=1e3),(y=(n=O(this,we)).pingTimeout)!=null||(n.pingTimeout=3e4),(w=(o=O(this,we)).connectionTimeout)!=null||(o.connectionTimeout=5e3),(b=(c=O(this,we)).debug)!=null||(c.debug=!0),(R=(d=O(this,we)).maxReconnectionAttempts)!=null||(d.maxReconnectionAttempts=10),(N=(l=O(this,we)).disconnectOnPingTimeout)!=null||(l.disconnectOnPingTimeout=!0),(U=(u=O(this,we)).queueOnDisconnect)!=null||(u.queueOnDisconnect=!1),(L=(h=O(this,we)).flushOnReconnect)!=null||(h.flushOnReconnect=!1),se(this,xr,{code:void 0,reason:void 0}),se(this,Le,(F=O(this,we).logger)!=null?F:new g1(O(this,we).debug?"debug":"info")),se(this,sr,new m1)}get readyState(){var t;return(t=O(this,Ae))==null?void 0:t.readyState}get url(){return O(this,On)}updateURL(t){se(this,On,t),Ee(this,Dh,uS).call(this)}get config(){return O(this,we)}get sendQueue(){return O(this,Lr)}flush(){if(!O(this,we).queueOnDisconnect)return!1;const t=[];return O(this,Lr).forEach(e=>{this.send(e.event,e.id,e.payload,e.metadata)||t.push(e)}),se(this,Lr,t),O(this,Lr)}async connect(t=!1){if(!t&&[0,1].includes(this.readyState)){O(this,Le).debug("Websocket was already connecting or connected.");return}if(O(this,tr)!==!1)return new Promise((e,r)=>{Ee(this,Nn,mo).call(this),Ee(this,go,Zd).call(this);try{se(this,Ae,new WebSocket(Ee(this,Ih,cS).call(this,O(this,On)))),O(this,Ae).binaryType="arraybuffer",O(this,Le).debug("Connecting");const i=setTimeout(()=>{O(this,Le).debug("Connection timeout. Closing socket"),se(this,tr,!0),Ee(this,go,Zd).call(this),O(this,Ae).close(3001,"Connection Timeout"),O(this,we).autoReconnect&&!O(this,ms)&&(O(this,Je).emit("reconnecting"),Ee(this,ho,Yd).call(this)),r(new Error("Connection timed out!"))},O(this,we).connectionTimeout);O(this,Ae).onopen=()=>{O(this,Le).debug(`Ready State: ${oS[O(this,Ae).readyState]}`),i&&clearTimeout(i),Ee(this,Xd,Nh).call(this),se(this,xr,{code:void 0,reason:void 0}),O(this,Je).emit("connected"),O(this,we).flushOnReconnect&&this.flush(),e()},O(this,Ae).onclose=n=>{try{i&&clearTimeout(i);const{code:o,reason:c}=n;r(c),O(this,Le).debug("Socket closed. Close event:",{event:n}),O(this,Le).debug(`Connection closed code: ${o}`),O(this,Le).debug(`Connection closed reason: ${c}`),O(this,ms)||Ee(this,zd,Oh).call(this,o,c)}catch(o){Ee(this,uo,Kd).call(this,o)}},O(this,Ae).onerror=n=>{Ee(this,uo,Kd).call(this,n)},O(this,Ae).onmessage=n=>Ee(this,Ah,dS).call(this,n)}catch(i){Ee(this,uo,Kd).call(this,i,r)}})}send(t,e,r,i){const n={event:t,id:e,payload:r,metadata:i};if(O(this,we).queueOnDisconnect&&(!O(this,Ae)||O(this,Ae).readyState!==1))return O(this,Le).debug("Queuing message since socket is not connected!",n),O(this,Lr).push(n),!1;const o=aS.encode(n);return Ee(this,po,Qd).call(this,o)}emit(t,e,r,i){return this.send(t,e,r,i)}sendRaw(t){return Ee(this,po,Qd).call(this,t)}receive(t,e){return O(this,Je).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")){O(this,Je).on(t,e);return}this.receive(t,e)}removeAllListeners(){O(this,Je).removeAllListeners()}removeReceiver(t,e){this.removeListener(t,e)}removeListener(t,e){O(this,Je).removeListener(t.toString(),e)}removeReceivers(t){this.removeListeners(t)}removeListeners(t){O(this,Je).listeners(t.toString()).map(e=>this.removeListener(t,e))}disconnect(){se(this,tr,!1),Ee(this,Nn,mo).call(this),this.removeAllListeners(),se(this,xr,{code:1e3,reason:"Sockrates disconnect method called"}),O(this,Ae).close(1e3,"Sockrates disconnect method called.")}}Ae=new WeakMap,On=new WeakMap,we=new WeakMap,Le=new WeakMap,Lr=new WeakMap,Je=new WeakMap,tr=new WeakMap,xr=new WeakMap,ms=new WeakMap,Dn=new WeakMap,sr=new WeakMap,Ih=new WeakSet,cS=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)://.")},uo=new WeakSet,Kd=function(s,t){O(this,Le).error("Error:",{error:s}),O(this,Je).emit("errored",{error:s}),t==null||t(s)},Ah=new WeakSet,dS=function(s){if(Ee(this,Xd,Nh).call(this),s.data===f1){O(this,Le).debug("Received ping from server"),Ee(this,po,Qd).call(this,S1);return}const t=aS.decode(s.data),{id:e,payload:r}=t;O(this,Le).debug("Received message",{event:t.event,messageID:e}),O(this,Je).emit(t.event.toString(),{id:e,payload:r})},Mh=new WeakSet,lS=function(){return O(this,Ae).readyState===1},zd=new WeakSet,Oh=function(s,t){se(this,xr,{reason:t,code:s}),O(this,Je).emit("disconnected",{code:s,reason:t})},Dh=new WeakSet,uS=function(){const{reason:s,code:t}=O(this,xr);t&&t!==1e3&&O(this,tr)&&O(this,we).autoReconnect&&!O(this,ms)&&(O(this,Le).debug(`Triggering reconnection due to ${s}.`),O(this,Je).emit("reconnecting"),Ee(this,ho,Yd).call(this))},ho=new WeakSet,Yd=async function(s=!0){if(s&&O(this,ms)){O(this,Le).debug("Reconnect called when already in a reconnect loop. Ignoring.");return}if(O(this,ms)||O(this,sr).reset(),O(this,we).maxReconnectionAttempts!==null&&O(this,sr).getAttempts()>=O(this,we).maxReconnectionAttempts){O(this,Je).emit("failed"),se(this,ms,!1);return}se(this,ms,!0),Ee(this,go,Zd).call(this),Ee(this,Nn,mo).call(this);try{if(await O(this,sr).wait(),O(this,tr)===!1)return;if(O(this,Le).debug(`Reconnection attempt ${O(this,sr).getAttempts()}`),O(this,Je).emit("reconnectAttempt",{attempt:O(this,sr).getAttempts()}),await this.connect(),!Ee(this,Mh,lS).call(this))throw Error("Reconnect Failed");se(this,ms,!1),se(this,xr,{code:void 0,reason:void 0}),O(this,Je).emit("reconnected")}catch(t){O(this,Le).debug("Failed to reconnect."),O(this,Je).emit("reconnectFailure",{attempt:O(this,sr).getAttempts()}),Ee(this,ho,Yd).call(this,!1)}},po=new WeakSet,Qd=function(s){try{return O(this,Ae).send(s),!0}catch(t){return O(this,Le).error(t.message),!1}},Xd=new WeakSet,Nh=function(){this.config.disconnectOnPingTimeout&&(O(this,Le).debug("Resetting ping timeout"),Ee(this,Nn,mo).call(this),se(this,Dn,setTimeout(()=>{var s;O(this,Le).debug("Disconnecting the socket due to ping timeout"),se(this,tr,!0);const t=3002,e="Ping timeout";(s=O(this,Ae))==null||s.close(t,e),Ee(this,zd,Oh).call(this,t,e)},O(this,we).pingTimeout)))},Nn=new WeakSet,mo=function(){O(this,Dn)&&(clearTimeout(O(this,Dn)),se(this,Dn,void 0))},go=new WeakSet,Zd=function(){O(this,Ae)&&(O(this,Ae).onopen=void 0,O(this,Ae).onerror=void 0,O(this,Ae).onmessage=void 0,O(this,Ae).onclose=void 0)};var T1=Object.defineProperty,y1=Object.getOwnPropertyDescriptor,el=(s,t,e,r)=>{for(var i=r>1?void 0:r?y1(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&&T1(t,e,i),i};const hS=65535,E1=3e3,pS=(VS=class{constructor(s,{peerId:t,meetingId:e,authToken:r,capabilities:i}){g(this,Re);g(this,yc);g(this,Ec);g(this,si,void 0);g(this,ke,void 0);p(this,"roomName");p(this,"authToken");p(this,"capabilities");g(this,ns,void 0);g(this,et,void 0);var n;if(!t||!e||!r)throw new C("peerId, meetingId, or authToken can not be empty","0404");f(this,ns,void 0),f(this,et,s),this.capabilities=i,this.roomName=e,this.authToken=r,f(this,si,$(this,yc,tp).call(this,t)),f(this,ke,new v1(a(this,si),{autoReconnect:!0,disconnectOnPingTimeout:(n=i.includes("PING"))!=null?n:!1,queueOnDisconnect:!0,flushOnReconnect:!1,logger:this.logger})),this.handleSocketConnectionEvents()}get joinAttempted(){return a(this,Re,Fe).socketJoinAttempted}set joinAttempted(s){a(this,Re,Fe).socketJoinAttempted=s}get telemetry(){return a(this,et).getValue("telemetry")}get logger(){return a(this,et).getValue("logger")}get peerId(){return a(this,et).getValue("peerId")}updateURL(s){s!==this.peerId&&(f(this,si,$(this,yc,tp).call(this,s)),this.logger.debug("SocketService:: Connection URL updated.")),a(this,ke).updateURL(a(this,si))}static getSocketEdgeDomain(s){return En({servicePrefix:"socket-edge",baseURI:s})}get url(){return a(this,si)}async connect(){a(this,Re,Fe).socketJoinAttempted=!0,await a(this,ke).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,ke).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,ke).readyState===1}catch(s){return!1}}sendMessage(s,t,e){const r={};return a(this,et).getValue("telemetry").injectContext(r),a(this,ke).send(s,e!=null?e:$(this,Ec,sp).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,ke).removeListener(n,y),a(this,ke).removeListener(hS,w),a(this,ke).removeListener(kr.errorResponse,w),a(this,ke).removeListener(us.errorResponse,w)},l=r!=null?r:$(this,Ec,sp).call(this),u={};a(this,et).getValue("telemetry").injectContext(u);const m=({id:y,payload:w})=>{if(l===y){let b;try{const R=Ck.fromBinary(w);b=new Error(R.errorMessage)}catch(R){b=new Error("failed to parse error message",{cause:R});try{const N=kR.fromBinary(w);b=new Error(N.message)}catch(N){b=new Error("failed to parse error message",{cause:N})}}c(b),d(S,m)}},S=({id:y,payload:w})=>{l===y&&(o({id:y,payload:w}),d(S,m))};a(this,ke).on(n,S),a(this,ke).on(hS,m),a(this,ke).on(kr.errorResponse,m),a(this,ke).on(us.errorResponse,m),setTimeout(()=>{d(S,m),c(new Error(`request timeout for callback eventId:${s}`))},t),a(this,ke).send(s,l,e,new TextEncoder().encode(JSON.stringify(u)))})}on(s,t){a(this,ke).on(s,t)}onStateEvent(s,t){a(this,ke).on(s,t)}removeListener(s,t){a(this,ke).removeListener(s,t)}removeListeners(s){a(this,ke).removeListeners(s)}flush(){return a(this,ke).flush()}handleSocketConnectionEvents(){this.onStateEvent("connected",async()=>{this.logger.info("SocketService::Connected to socket-edge"),a(this,ns)&&(clearTimeout(a(this,ns)),f(this,ns,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)!==An.CONNECTED||r!=null&&r.state&&(r==null?void 0:r.state)!==An.CONNECTED?a(this,et).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Re,Fe).joinAttempted}):f(this,ns,setTimeout(()=>{a(this,et).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_DISCONNECTED,{joinAttempted:a(this,Re,Fe).joinAttempted}),f(this,ns,void 0)},E1)),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,ns)&&(clearTimeout(a(this,ns)),f(this,ns,void 0)),a(this,et).getValue("peerSessionStore").emit(_.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,et).getValue("peerSessionStore").emit(_.SOCKET_SERVICE_FAILED),a(this,Re,Fe).updateSocketConnectionState("failed")})}},si=new WeakMap,ke=new WeakMap,Re=new WeakSet,Fe=function(){return a(this,et).getValue("connectionHandler")},ns=new WeakMap,et=new WeakMap,yc=new WeakSet,tp=function(s){const t=a(this,et).getValue("socketBaseURI")||a(this,et).getValue("baseURI");let e=pS.getSocketEdgeDomain(t);typeof yn(a(this,et),"socket_server_base")=="string"&&(e=yn(a(this,et),"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=>bd[c]).join(" "),joinWithDetails:!0,useCfWorker:!0,useStartSession:!0};return Object.entries(o).forEach(([c,d])=>{i.searchParams.append(c,d.toString())}),i.href},Ec=new WeakSet,sp=function(){return`${this.peerId}-${(Math.random()+1).toString(36).substring(7)}`},VS);let fo=pS;el([E.trace("SocketService.connect")],fo.prototype,"connect",1),el([E.trace("SocketService.disconnect")],fo.prototype,"disconnect",1),el([E.trace("SocketService.sendMessagePromise")],fo.prototype,"sendMessagePromise",1),el([E.trace("SocketService.sendMessagePromiseWithTimeout")],fo.prototype,"sendMessagePromiseWithTimeout",1);class w1{constructor(t){p(this,"socketService");this.socketService=t}handleConnectedRoomsDumpRaw({payload:t}){var n;const e=e0.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=C0.fromBinary(t);return{authToken:e.authToken,meetingId:e.meetingId}}handleMovedPeerRaw({payload:t}){const e=Gg.fromBinary(t);return{meetingId:e.meetingId,customParticipantId:e.customParticipantId}}handleConnectedRoomsUpdatedRaw({payload:t}){return jg.fromBinary(t).payloads.map(r=>({id:r.id,title:r.title}))}handleConnectedRoomsDeletedRaw({payload:t}){return f0.fromBinary(t).payloads}async getConnectedRoomsDump(){const t=await this.socketService.sendMessagePromise(x.getConnectedRoomsDump);return this.handleConnectedRoomsDumpRaw(t)}async createConnectedRooms(t){const{payload:e}=await this.socketService.sendMessagePromise(x.createConnectedRooms,i0.toBinary({payloads:t}));return jg.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(x.deleteConnectedRooms,m0.toBinary({payloads:e}));return this.handleConnectedRoomsDeletedRaw(r)}async movePeersBetweenRooms(t){try{const e=await this.socketService.sendMessagePromise(x.movePeers,w0.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,P1=Object.getOwnPropertyDescriptor,_1=(s,t,e,r)=>{for(var i=r>1?void 0:r?P1(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,bs,void 0);f(this,bs,e)}get supportsConnectedMeetings(){return a(this,bs).getValue("self").id!==""}get isActive(){return this.meetings.length!==0}validateConnectedMeetingsAction(){if(!this.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
18
|
+
Please connect with our support team to enable connected meetings.`)}async getConnectedMeetings(){this.validateConnectedMeetingsAction(),this.logger.info("Getting connected meetings dump");const e=await a(this,bs).getValue("connectedMeetingsSocketHandler").getConnectedRoomsDump();return this.logger.info("Got connected meetings dump"),e}async createMeetings(e){this.validateConnectedMeetingsAction(),this.logger.info(`Creating connected meetings ${JSON.stringify(e)}`);const r=await a(this,bs).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.validateConnectedMeetingsAction(),this.logger.info(`Updating connected meetings ${JSON.stringify(e)}`),await a(this,bs).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.validateConnectedMeetingsAction(),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,bs).getValue("connectedMeetingsSocketHandler").disableConnectedRooms(e);return this.logger.info(`Deleted connected meetings ${JSON.stringify(e)}`),i}async moveParticipants(e,r,i){this.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,bs).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.validateConnectedMeetingsAction(),this.logger.info(`Moving connected meetings participants (custom preset) ${JSON.stringify(i)} from ${e} to ${r}`);const n=await a(this,bs).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})}}bs=new WeakMap,_1([Nt({maxInvocations:60,period:60})],mS.prototype,"getConnectedMeetings",1);var C1=Object.defineProperty,k1=Object.getOwnPropertyDescriptor,Vh=(s,t,e,r)=>{for(var i=r>1?void 0:r?k1(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&&C1(t,e,i),i};const gS=(LS=class{constructor(s){p(this,"connectedMeetings");g(this,me,void 0);f(this,me,s),this.connectedMeetings=new mS(s)}get telemetry(){return a(this,me).getValue("telemetry")}get logger(){return a(this,me).getValue("logger")}static init(s){const t=new gS(s);return t.connectedMeetings.supportsConnectedMeetings&&(t.setupEvents(),s.getValue("self").once("roomJoined",()=>t.getConnectedMeetings())),t}getConnectedMeetings(){this.connectedMeetings.getConnectedMeetings()}setupEvents(){a(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(x.getConnectedRoomsDump,this.handleConnectedRoomsDump.bind(this)),a(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(x.transferPeer,this.handleTransferPeer.bind(this)),a(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(x.movedPeer,this.handleMovedPeer.bind(this)),a(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsUpdated,this.handleConnectedRoomsUpdated.bind(this)),a(this,me).getValue("connectedMeetingsSocketHandler").socketService.on(x.connectedRoomsDeleted,this.handleConnectedRoomsDeleted.bind(this))}handleTransferPeer(s){this.logger.info("Received backend request to switch connected meetings");const t=a(this,me).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;if(!this.connectedMeetings.supportsConnectedMeetings)throw new Error(`You are not allowed to perform this action.
|
|
19
|
+
Please connect with our support team to enable connected meetings.`);this.logger.info("ConnectedMeetingsController::switchMeeting:: asking ui-kit to show switching breakout UI"),this.connectedMeetings.emit("changingMeeting",t);const e={video:a(this,me).getValue("self").videoEnabled,audio:a(this,me).getValue("self").audioEnabled};try{a(this,me).getValue("self").cleanupEvents(),await a(this,me).getValue("meeting").leave("connected-meeting")}catch(d){this.logger.error(`ConnectedMeetingsController:: switchMeeting:: issues in leaving previous meeting. Meeting Id: ${(n=(i=a(this,me).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 SS.init({...a(this,me).getValue("options"),cachedUserDetails:null,defaults:{...a(this,me).getValue("options").defaults,...e,mediaHandler:a(this,me).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,me).getValue("self");r.self.setName(a(this,me).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,me).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,me).getValue("connectedMeetingsSocketHandler").handleMovedPeerRaw(s)}handleConnectedRoomsUpdated(s){const t=a(this,me).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,me).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})}},me=new WeakMap,LS);let tl=gS;Vh([E.trace("ConnectedMeetingsController.getConnectedMeetings")],tl.prototype,"getConnectedMeetings",1),Vh([E.trace("ConnectedMeetingsController.setupEvents")],tl.prototype,"setupEvents",1),Vh([E.trace("ConnectedMeetingsController.switchMeeting")],tl.prototype,"switchMeeting",1);var R1=Object.defineProperty,I1=Object.getOwnPropertyDescriptor,Lh=(s,t,e,r)=>{for(var i=r>1?void 0:r?I1(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&&R1(t,e,i),i};const So=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 U,L,F;const{peerId:t,apiBase:e,authToken:r,meetingId:i,organizationId:n,cachedUserDetails:o,logger:c}=s.getAllValues();if(jD(s),ge.isSupported()===!1)throw new C("Browser not supported","0010",c,!0);const d=EM(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 rO(s);s.setValue("connectionHandler",l);let u="",h="",m=null;c.info("CF SFU is being used.");try{m=await d.getUserDetails(),u=((U=m.meeting)==null?void 0:U.title)||"",h=((L=m.socket)==null?void 0:L.baseUri)||s.getValue("baseURI"),s.setValue("presetName",m.preset.name),s.setValue("socketBaseURI",h),c.info(`Socket Base URI ${h} is being used`)}catch(H){throw c.error("Failed to get user details",{error:H}),H instanceof th?H.status===401?new C("Unauthorized. The auth token may be invalid or expired. (401)","0004"):H.status===403?new C("Access denied. Insufficient permissions to join the meeting. (403)","0004"):H.status===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"):H.status>=500?new C(`The server encountered an error. Try again. (${H.status})`,"0001"):H.isHttpError?new C(`Request rejected by the server. (${H.status})`,"0001"):H.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((H==null?void 0:H.message)||"Failed to initialize.","0001")}const S=So.createSocketService(s),y=S.connect();try{await y}catch(H){c.error("[Controller]: Failed to connect to socket server:",{error:H})}const w=mh.init(m.preset,!s.getValue("modules").theme);s.setValue("theme",w);const b=fh.init(s,w.viewType,m.preset.permissions),R=So.setupControllers(S,s,m,u,w,b);GM(w)&&((F=So.createRoomNodeClient(s,S).initializeConnection(m.participant.name,i,!1,b))==null||F.catch(ie=>{c.error("[Controller]: Failed to queue partial media room promise:",{error:ie})}));const{controllers:N}=await R;return N_(),new So(e,N,s)}static async setupControllers(s,t,e,r,i,n){var De,V,k;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:(De=h.enableHighBitrate)!=null?De:!1,enableStereo:(V=h.enableStereo)!=null?V:!1}},...d}),t.setValue("maxPreferredStreams",ge.isMobile()?i.maxVideoStreams.mobile:i.maxVideoStreams.desktop);let m,S,y,w,b,R,N,U,L;const F=new KD(t,s),H=new w1(s);t.setValue("connectedMeetingsSocketHandler",H);const ie=new jd(t,s),ut=new Ys(t,s),Us=new e1(s),Ps=new Kf(t,s),un=new t1(t,s),I=new JD(s),T=await Dr.init(t,Ps,c,n,i);t.setValue("selfController",T);const P=await pf.init(t,T.self,Ps,F,r);o.participant&&(U=new er(t,T.self,Ps)),(k=o.e2ee)!=null&&k.enabled&&o.e2ee.manager.init(l,t.getValue("peerSessionStore")),o.chat&&(S=await _n.init(t,ut,T.self,U.participants)),o.internals&&(b=await dh.init(t)),o.livestream&&i.viewType===qs.Livestream&&(N=new Nf(t,T.self,I)),o.poll&&(m=await df.init(t,T.self,ie)),o.recording&&(R=new Tf(t,T.self,Ps)),o.stage&&(y=new mf(t,Us,Ps,T.self,U.participants));const B=new tD(t,un);if(o.plugin){if(!U)throw new C("The plugin module cannot be initialized without the `participant` module","0102");const Be=d.plugins||[],hn=await B.create(Zm,!0);w=await vf.init(t,Be,hn,T.self,B)}if(o.connectedMeetings&&(L=await tl.init(t)),o.pip){const Be=await Mu._init(t,T.self);t.setValue("pip",Be)}return{theme:i,permissions:n,controllers:{storesManager:B,pollController:m,selfController:T,metaController:P,chatController:S,stageController:y,pluginController:w,recordingController:R,internalsController:b,livestreamController:N,participantController:U,connectedMeetingsController:L}}}static createRoomNodeClient(s,t){const{peerId:e}=s.getAllValues();return Wf(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 fo(s,{peerId:t,meetingId:e,authToken:r,capabilities:o})}};let sl=So;Lh([E.trace("Controller.init")],sl,"init",1),Lh([E.trace("Controller.createRoomNodeClient")],sl,"createRoomNodeClient",1),Lh([E.trace("Controller.createSocketService")],sl,"createSocketService",1);class A1{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 fS=new A1;function M1(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=li.baseURI.prod;t&&(n=t);const o=`https://${En({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 O1{constructor(){g(this,Yl);g(this,ri,new Audio);g(this,on,new MediaStream);g(this,cn,new Map);g(this,wc,void 0);a(this,ri).srcObject=a(this,on),a(this,ri).autoplay=!0}async playTracks(t){return t.forEach(e=>{a(this,cn).has(e.id)||(a(this,on).addTrack(e),a(this,cn).set(e.id,e))}),this.play()}setSpeakerDevice(t){typeof HTMLAudioElement.prototype.setSinkId=="function"&&a(this,ri).setSinkId(t)}removeTrack(t){const e=a(this,cn).get(t);e&&(a(this,on).removeTrack(e),a(this,cn).delete(t))}async play(){return a(this,ri).srcObject=a(this,on),a(this,ri).play().catch(t=>{$(this,Yl,Tv).call(this,t)})}onError(t){f(this,wc,t)}}ri=new WeakMap,on=new WeakMap,cn=new WeakMap,wc=new WeakMap,Yl=new WeakSet,Tv=function(t){var e;(e=a(this,wc))==null||e.call(this,t)};class D1 extends O1{constructor(){super();g(this,dn,void 0);f(this,dn,new Map)}addParticipantTrack(e,r){a(this,dn).set(e,r.id),this.playTracks([r])}removeParticipantTrack(e){const r=a(this,dn).get(e);r&&this.removeTrack(r),a(this,dn).delete(e)}}dn=new WeakMap;var N1=Object.defineProperty,V1=Object.getOwnPropertyDescriptor,rl=(s,t,e,r)=>{for(var i=r>1?void 0:r?V1(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&&N1(t,e,i),i};let Ur=(xS=class{constructor(t,e){g(this,qe,void 0);g(this,ln,void 0);f(this,ln,t),f(this,qe,e)}get peerId(){return a(this,ln).getValue("peerId")}static async initMedia(t={},e=!1,r=void 0){var d;const i=(d=r==null?void 0:r.peerId)!=null?d:mn(),n=Pr.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,b,R,N,U,L;ge.init();const e=(S=(m=t==null?void 0:t.cachedUserDetails)==null?void 0:m.peerId)!=null?S:mn(),{authToken:r,baseURI:i}=t,{meetingId:n,...o}=M1(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=Ur.setupContext(e,t,n,o),d=c.getValue("telemetry"),l=c.getValue("logger");bv(l),fS.init(l),d.init(c,{roomName:n,userId:o.participantId,organizationId:o.orgId,peerId:e},(b=(w=t.modules)==null?void 0:w.tracing)!=null?b:!0,(N=(R=t==null?void 0:t.modules)==null?void 0:R.devTools)==null?void 0:N.logLevel),l.init(c),l.info("Client::init::options",{clientInitOptions:{...t,authToken:`${(U=t.authToken)==null?void 0:U.slice(0,10)}...
|
|
20
|
+
${(L=t.authToken)==null?void 0:L.slice(-10)}`}});const u=await sl.init(c),h=new Ur(c,u);return c.setValue("meeting",h),h}static setupContext(t,e,r,i){var d,l;const n=Pr.createContext(t,e),o={...u_,...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",h_({baseURI:i.baseURI})),n.setValue("defaults",c),n.setValue("onError",e.onError||(()=>{})),n.setValue("cachedUserDetails",Is(e.cachedUserDetails)),n.setValue("sdkVersion","1.5.2-staging.2"),(l=e.modules)!=null&&l.experimentalAudioPlayback&&n.setValue("audioPlayback",new D1),n}async join(){const{selfController:t}=a(this,qe);return t.self.roomJoined?null:t.joinRoom()}async leave(t){fS.cleanup(),a(this,ln).getValue("peerSessionStore").reset();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,ln).getValue("audioPlayback")}get __internals__(){var t;return(t=a(this,qe).internalsController)==null?void 0:t.internals}async joinRoom(){return this.join()}async leaveRoom(t){return this.leave(t)}},qe=new WeakMap,ln=new WeakMap,xS);rl([nt("0002"),Xs.executeWithLock({methodName:"meeting.join",lockName:"Client.join",timeout:3e3})],Ur.prototype,"join",1),rl([nt("0003")],Ur.prototype,"leave",1),rl([nt("0001"),Xs.executeWithLock({methodName:"Client.init",lockName:"Client.init",timeout:3e3})],Ur,"init",1),Ur=rl([nt("0000")],Ur);const SS=Ur;return SS}();
|