UNPKG

agora-rtc-sdk-ng

Version:
7 lines 1.61 MB
/**
 * AgoraWebSDK_N-v4.24.8-0-gf100be755-dirty Copyright AgoraInc.
 */

function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}var t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function n(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var i=function(e){try{return!!e()}catch(e){return!0}},r=!i((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),o=r,s=Function.prototype,a=s.call,c=o&&s.bind.bind(a,a),d=o?c:function(e){return function(){return a.apply(e,arguments)}},l=d({}.isPrototypeOf),u=function(e){return e&&e.Math===Math&&e},h=u("object"==typeof globalThis&&globalThis)||u("object"==typeof window&&window)||u("object"==typeof self&&self)||u("object"==typeof t&&t)||u("object"==typeof t&&t)||function(){return this}()||Function("return this")(),p=r,_=Function.prototype,E=_.apply,m=_.call,f="object"==typeof Reflect&&Reflect.apply||(p?m.bind(E):function(){return m.apply(E,arguments)}),g=d,S=g({}.toString),T=g("".slice),R=function(e){return T(S(e),8,-1)},v=R,y=d,C=function(e){if("Function"===v(e))return y(e)},b="object"==typeof document&&document.all,I=void 0===b&&void 0!==b?function(e){return"function"==typeof e||e===b}:function(e){return"function"==typeof e},A={},w=!i((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),O=r,N=Function.prototype.call,D=O?N.bind(N):function(){return N.apply(N,arguments)},P={},L={}.propertyIsEnumerable,k=Object.getOwnPropertyDescriptor,M=k&&!L.call({1:2},1);P.f=M?function(e){var t=k(this,e);return!!t&&t.enumerable}:L;var U,V,x=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},F=i,B=R,j=Object,G=d("".split),W=F((function(){return!j("z").propertyIsEnumerable(0)}))?function(e){return"String"===B(e)?G(e,""):j(e)}:j,K=function(e){return null==e},H=K,Y=TypeError,X=function(e){if(H(e))throw new Y("Can't call method on "+e);return e},J=W,z=X,Z=function(e){return J(z(e))},q=I,Q=function(e){return"object"==typeof e?null!==e:q(e)},$={},ee=$,te=h,ne=I,ie=function(e){return ne(e)?e:void 0},re=function(e,t){return arguments.length<2?ie(ee[e])||ie(te[e]):ee[e]&&ee[e][t]||te[e]&&te[e][t]},oe=h.navigator,se=oe&&oe.userAgent,ae=se?String(se):"",ce=h,de=ae,le=ce.process,ue=ce.Deno,he=le&&le.versions||ue&&ue.version,pe=he&&he.v8;pe&&(V=(U=pe.split("."))[0]>0&&U[0]<4?1:+(U[0]+U[1])),!V&&de&&(!(U=de.match(/Edge\/(\d+)/))||U[1]>=74)&&(U=de.match(/Chrome\/(\d+)/))&&(V=+U[1]);var _e=V,Ee=_e,me=i,fe=h.String,ge=!!Object.getOwnPropertySymbols&&!me((function(){var e=Symbol("symbol detection");return!fe(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&Ee&&Ee<41})),Se=ge&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,Te=re,Re=I,ve=l,ye=Object,Ce=Se?function(e){return"symbol"==typeof e}:function(e){var t=Te("Symbol");return Re(t)&&ve(t.prototype,ye(e))},be=String,Ie=function(e){try{return be(e)}catch(e){return"Object"}},Ae=I,we=Ie,Oe=TypeError,Ne=function(e){if(Ae(e))return e;throw new Oe(we(e)+" is not a function")},De=Ne,Pe=K,Le=function(e,t){var n=e[t];return Pe(n)?void 0:De(n)},ke=D,Me=I,Ue=Q,Ve=TypeError,xe={exports:{}},Fe=h,Be=Object.defineProperty,je=h,Ge=function(e,t){try{Be(Fe,e,{value:t,configurable:!0,writable:!0})}catch(n){Fe[e]=t}return t},We="__core-js_shared__",Ke=xe.exports=je[We]||Ge(We,{});(Ke.versions||(Ke.versions=[])).push({version:"3.49.0",mode:"pure",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"});var He=xe.exports,Ye=He,Xe=function(e,t){return Ye[e]||(Ye[e]=t||{})},Je=X,ze=Object,Ze=function(e){return ze(Je(e))},qe=Ze,Qe=d({}.hasOwnProperty),$e=Object.hasOwn||function(e,t){return Qe(qe(e),t)},et=d,tt=0,nt=Math.random(),it=et(1.1.toString),rt=function(e){return"Symbol("+(void 0===e?"":e)+")_"+it(++tt+nt,36)},ot=Xe,st=$e,at=rt,ct=ge,dt=Se,lt=h.Symbol,ut=ot("wks"),ht=dt?lt.for||lt:lt&&lt.withoutSetter||at,pt=function(e){return st(ut,e)||(ut[e]=ct&&st(lt,e)?lt[e]:ht("Symbol."+e)),ut[e]},_t=D,Et=Q,mt=Ce,ft=Le,gt=function(e,t){var n,i;if("string"===t&&Me(n=e.toString)&&!Ue(i=ke(n,e)))return i;if(Me(n=e.valueOf)&&!Ue(i=ke(n,e)))return i;if("string"!==t&&Me(n=e.toString)&&!Ue(i=ke(n,e)))return i;throw new Ve("Can't convert object to primitive value")},St=TypeError,Tt=pt("toPrimitive"),Rt=function(e,t){if(!Et(e)||mt(e))return e;var n,i=ft(e,Tt);if(i){if(void 0===t&&(t="default"),n=_t(i,e,t),!Et(n)||mt(n))return n;throw new St("Can't convert object to primitive value")}return void 0===t&&(t="number"),gt(e,t)},vt=Ce,yt=function(e){var t=Rt(e,"string");return vt(t)?t:t+""},Ct=Q,bt=h.document,It=Ct(bt)&&Ct(bt.createElement),At=function(e){return It?bt.createElement(e):{}},wt=At,Ot=!w&&!i((function(){return 7!==Object.defineProperty(wt("div"),"a",{get:function(){return 7}}).a})),Nt=w,Dt=D,Pt=P,Lt=x,kt=Z,Mt=yt,Ut=$e,Vt=Ot,xt=Object.getOwnPropertyDescriptor;A.f=Nt?xt:function(e,t){if(e=kt(e),t=Mt(t),Vt)try{return xt(e,t)}catch(e){}if(Ut(e,t))return Lt(!Dt(Pt.f,e,t),e[t])};var Ft=i,Bt=I,jt=/#|\.prototype\./,Gt=function(e,t){var n=Kt[Wt(e)];return n===Yt||n!==Ht&&(Bt(t)?Ft(t):!!t)},Wt=Gt.normalize=function(e){return String(e).replace(jt,".").toLowerCase()},Kt=Gt.data={},Ht=Gt.NATIVE="N",Yt=Gt.POLYFILL="P",Xt=Gt,Jt=Ne,zt=r,Zt=C(C.bind),qt=function(e,t){return Jt(e),void 0===t?e:zt?Zt(e,t):function(){return e.apply(t,arguments)}},Qt={},$t=w&&i((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),en=Q,tn=String,nn=TypeError,rn=function(e){if(en(e))return e;throw new nn(tn(e)+" is not an object")},on=w,sn=Ot,an=$t,cn=rn,dn=yt,ln=TypeError,un=Object.defineProperty,hn=Object.getOwnPropertyDescriptor,pn="enumerable",_n="configurable",En="writable";Qt.f=on?an?function(e,t,n){if(cn(e),t=dn(t),cn(n),"function"==typeof e&&"prototype"===t&&"value"in n&&En in n&&!n[En]){var i=hn(e,t);i&&i[En]&&(e[t]=n.value,n={configurable:_n in n?n[_n]:i[_n],enumerable:pn in n?n[pn]:i[pn],writable:!1})}return un(e,t,n)}:un:function(e,t,n){if(cn(e),t=dn(t),cn(n),sn)try{return un(e,t,n)}catch(e){}if("get"in n||"set"in n)throw new ln("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var mn=Qt,fn=x,gn=w?function(e,t,n){return mn.f(e,t,fn(1,n))}:function(e,t,n){return e[t]=n,e},Sn=h,Tn=f,Rn=C,vn=I,yn=A.f,Cn=Xt,bn=$,In=qt,An=gn,wn=$e,On=function(e){var t=function(n,i,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,i)}return new e(n,i,r)}return Tn(e,this,arguments)};return t.prototype=e.prototype,t},Nn=function(e,t){var n,i,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?Sn:p?Sn[u]:Sn[u]&&Sn[u].prototype,m=h?bn:bn[u]||An(bn,u,{})[u],f=m.prototype;for(o in t)i=!(n=Cn(h?o:u+(p?".":"#")+o,e.forced))&&E&&wn(E,o),a=m[o],i&&(c=e.dontCallGetSet?(l=yn(E,o))&&l.value:E[o]),s=i&&c?c:t[o],(n||_||typeof a!=typeof s)&&(d=e.bind&&i?In(s,Sn):e.wrap&&i?On(s):_&&vn(s)?Rn(s):s,(e.sham||s&&s.sham||a&&a.sham)&&An(d,"sham",!0),An(m,o,d),_&&(wn(bn,r=u+"Prototype")||An(bn,r,{}),An(bn[r],o,s),e.real&&f&&(n||!f[o])&&An(f,o,s)))},Dn=Math.ceil,Pn=Math.floor,Ln=Math.trunc||function(e){var t=+e;return(t>0?Pn:Dn)(t)},kn=Ln,Mn=function(e){var t=+e;return t!=t||0===t?0:kn(t)},Un=Mn,Vn=Math.max,xn=Math.min,Fn=function(e,t){var n=Un(e);return n<0?Vn(n+t,0):xn(n,t)},Bn=Mn,jn=Math.min,Gn=function(e){var t=Bn(e);return t>0?jn(t,9007199254740991):0},Wn=function(e){return Gn(e.length)},Kn=Z,Hn=Fn,Yn=Wn,Xn=function(e){return function(t,n,i){var r=Kn(t),o=Yn(r);if(0===o)return!e&&-1;var s,a=Hn(i,o);if(e&&n!=n){for(;o>a;)if((s=r[a++])!=s)return!0}else for(;o>a;a++)if((e||a in r)&&r[a]===n)return e||a||0;return!e&&-1}},Jn={includes:Xn(!0),indexOf:Xn(!1)},zn=Nn,Zn=Jn.includes,qn=i,Qn=qn((function(){return!Array(1).includes()})),$n=qn((function(){return[,1].includes(void 0,1)}));zn({target:"Array",proto:!0,forced:Qn||$n},{includes:function(e){return Zn(this,e,arguments.length>1?arguments[1]:void 0)}});var ei=h,ti=$,ni=function(e,t){var n=ti[e+"Prototype"],i=n&&n[t];if(i)return i;var r=ei[e],o=r&&r.prototype;return o&&o[t]},ii=ni("Array","includes"),ri=Q,oi=R,si=pt("match"),ai=function(e){var t;return ri(e)&&(void 0!==(t=e[si])?!!t:"RegExp"===oi(e))},ci=ai,di=TypeError,li={};li[pt("toStringTag")]="z";var ui="[object z]"===String(li),hi=ui,pi=I,_i=R,Ei=pt("toStringTag"),mi=Object,fi="Arguments"===_i(function(){return arguments}()),gi=hi?_i:function(e){var t,n,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=mi(e),Ei))?n:fi?_i(t):"Object"===(i=_i(t))&&pi(t.callee)?"Arguments":i},Si=gi,Ti=String,Ri=function(e){if("Symbol"===Si(e))throw new TypeError("Cannot convert a Symbol value to a string");return Ti(e)},vi=pt("match"),yi=Nn,Ci=function(e){if(ci(e))throw new di("The method doesn't accept regular expressions");return e},bi=X,Ii=Ri,Ai=function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[vi]=!1,"/./"[e](t)}catch(e){}}return!1},wi=d("".indexOf);yi({target:"String",proto:!0,forced:!Ai("includes")},{includes:function(e){return!!~wi(Ii(bi(this)),Ii(Ci(e)),arguments.length>1?arguments[1]:void 0)}});var Oi=ni("String","includes"),Ni=l,Di=ii,Pi=Oi,Li=Array.prototype,ki=String.prototype,Mi=function(e){var t=e.includes;return e===Li||Ni(Li,e)&&t===Li.includes?Di:"string"==typeof e||e===ki||Ni(ki,e)&&t===ki.includes?Pi:t},Ui=n(Mi),Vi=Ne,xi=Ze,Fi=W,Bi=Wn,ji=TypeError,Gi="Reduce of empty array with no initial value",Wi=function(e){return function(t,n,i,r){var o=xi(t),s=Fi(o),a=Bi(o);if(Vi(n),0===a&&i<2)throw new ji(Gi);var c=e?a-1:0,d=e?-1:1;if(i<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw new ji(Gi)}for(;e?c>=0:a>c;c+=d)c in s&&(r=n(r,s[c],c,o));return r}},Ki={left:Wi(!1),right:Wi(!0)},Hi=i,Yi=function(e,t){var n=[][e];return!!n&&Hi((function(){n.call(null,t||function(){return 1},1)}))},Xi=h,Ji=ae,zi=R,Zi=function(e){return Ji.slice(0,e.length)===e},qi=Zi("Bun/")?"BUN":Zi("Cloudflare-Workers")?"CLOUDFLARE":Zi("Deno/")?"DENO":Zi("Node.js/")?"NODE":Xi.Bun&&"string"==typeof Bun.version?"BUN":Xi.Deno&&"object"==typeof Deno.version?"DENO":"process"===zi(Xi.process)?"NODE":Xi.window&&Xi.document?"BROWSER":"REST",Qi="NODE"===qi,$i=Ki.left;Nn({target:"Array",proto:!0,forced:!Qi&&_e>79&&_e<83||!Yi("reduce")},{reduce:function(e){var t=arguments.length;return $i(this,e,t,t>1?arguments[1]:void 0)}});var er=ni("Array","reduce"),tr=l,nr=er,ir=Array.prototype,rr=function(e){var t=e.reduce;return e===ir||tr(ir,e)&&t===ir.reduce?nr:t},or=rr,sr=n(or),ar=R,cr=Array.isArray||function(e){return"Array"===ar(e)},dr=Nn,lr=cr,ur=d([].reverse),hr=[1,2];dr({target:"Array",proto:!0,forced:String(hr)===String(hr.reverse())},{reverse:function(){return lr(this)&&(this.length=this.length),ur(this)}});var pr=ni("Array","reverse"),_r=l,Er=pr,mr=Array.prototype,fr=function(e){var t=e.reverse;return e===mr||_r(mr,e)&&t===mr.reverse?Er:t},gr=fr,Sr=n(gr),Tr=rt,Rr=Xe("keys"),vr=function(e){return Rr[e]||(Rr[e]=Tr(e))},yr=!i((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),Cr=$e,br=I,Ir=Ze,Ar=yr,wr=vr("IE_PROTO"),Or=Object,Nr=Or.prototype,Dr=Ar?Or.getPrototypeOf:function(e){var t=Ir(e);if(Cr(t,wr))return t[wr];var n=t.constructor;return br(n)&&t instanceof n?n.prototype:t instanceof Or?Nr:null},Pr=d,Lr=Ne,kr=Q,Mr=function(e){return kr(e)||null===e},Ur=String,Vr=TypeError,xr=function(e,t,n){try{return Pr(Lr(Object.getOwnPropertyDescriptor(e,t)[n]))}catch(e){}},Fr=Q,Br=X,jr=function(e){if(Mr(e))return e;throw new Vr("Can't set "+Ur(e)+" as a prototype")},Gr=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,n={};try{(e=xr(Object.prototype,"__proto__","set"))(n,[]),t=n instanceof Array}catch(e){}return function(n,i){return Br(n),jr(i),Fr(n)?(t?e(n,i):n.__proto__=i,n):n}}():void 0),Wr={},Kr={},Hr=$e,Yr=Z,Xr=Jn.indexOf,Jr=Kr,zr=d([].push),Zr=function(e,t){var n,i=Yr(e),r=0,o=[];for(n in i)!Hr(Jr,n)&&Hr(i,n)&&zr(o,n);for(;t.length>r;)Hr(i,n=t[r++])&&(~Xr(o,n)||zr(o,n));return o},qr=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Qr=Zr,$r=qr.concat("length","prototype");Wr.f=Object.getOwnPropertyNames||function(e){return Qr(e,$r)};var eo={};eo.f=Object.getOwnPropertySymbols;var to=re,no=Wr,io=eo,ro=rn,oo=d([].concat),so=to("Reflect","ownKeys")||function(e){var t=no.f(ro(e)),n=io.f;return n?oo(t,n(e)):t},ao=$e,co=so,lo=A,uo=Qt,ho={},po=Zr,_o=qr,Eo=Object.keys||function(e){return po(e,_o)},mo=w,fo=$t,go=Qt,So=rn,To=Z,Ro=Eo;ho.f=mo&&!fo?Object.defineProperties:function(e,t){So(e);for(var n,i=To(t),r=Ro(t),o=r.length,s=0;o>s;)go.f(e,n=r[s++],i[n]);return e};var vo,yo=re("document","documentElement"),Co=rn,bo=ho,Io=qr,Ao=Kr,wo=yo,Oo=At,No="prototype",Do="script",Po=vr("IE_PROTO"),Lo=function(){},ko=function(e){return"<"+Do+">"+e+"</"+Do+">"},Mo=function(e){e.write(ko("")),e.close();var t=e.parentWindow.Object;return e=null,t},Uo=function(){try{vo=new ActiveXObject("htmlfile")}catch(e){}var e,t,n;Uo="undefined"!=typeof document?document.domain&&vo?Mo(vo):(t=Oo("iframe"),n="java"+Do+":",t.style.display="none",wo.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(ko("document.F=Object")),e.close(),e.F):Mo(vo);for(var i=Io.length;i--;)delete Uo[No][Io[i]];return Uo()};Ao[Po]=!0;var Vo=Object.create||function(e,t){var n;return null!==e?(Lo[No]=Co(e),n=new Lo,Lo[No]=null,n[Po]=e):n=Uo(),void 0===t?n:bo.f(n,t)},xo=Q,Fo=gn,Bo=Error,jo=d("".replace),Go=String(new Bo("zxcasd").stack),Wo=/\n\s*at [^:]*:[^\n]*/,Ko=Wo.test(Go),Ho=x,Yo=!i((function(){var e=new Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",Ho(1,7)),7!==e.stack)})),Xo=gn,Jo=function(e,t){if(Ko&&"string"==typeof e&&!Bo.prepareStackTrace)for(;t--;)e=jo(e,Wo,"");return e},zo=Yo,Zo=Error.captureStackTrace,qo={},Qo=qo,$o=pt("iterator"),es=Array.prototype,ts=function(e){return void 0!==e&&(Qo.Array===e||es[$o]===e)},ns=gi,is=Le,rs=K,os=qo,ss=pt("iterator"),as=function(e){if(!rs(e))return is(e,ss)||is(e,"@@iterator")||os[ns(e)]},cs=D,ds=Ne,ls=rn,us=Ie,hs=as,ps=TypeError,_s=function(e,t){var n=arguments.length<2?hs(e):t;if(ds(n))return ls(cs(n,e));throw new ps(us(e)+" is not iterable")},Es=D,ms=rn,fs=Le,gs=function(e,t,n){var i,r;ms(e);try{if(!(i=fs(e,"return"))){if("throw"===t)throw n;return n}i=Es(i,e)}catch(e){r=!0,i=e}if("throw"===t)throw n;if(r)throw i;return ms(i),n},Ss=qt,Ts=D,Rs=rn,vs=Ie,ys=ts,Cs=Wn,bs=l,Is=_s,As=as,ws=gs,Os=TypeError,Ns=function(e,t){this.stopped=e,this.result=t},Ds=Ns.prototype,Ps=function(e,t,n){var i,r,o,s,a,c,d,l=n&&n.that,u=!(!n||!n.AS_ENTRIES),h=!(!n||!n.IS_RECORD),p=!(!n||!n.IS_ITERATOR),_=!(!n||!n.INTERRUPTED),E=Ss(t,l),m=function(e){var t=i;return i=void 0,t&&ws(t,"normal"),new Ns(!0,e)},f=function(e){return u?(Rs(e),_?E(e[0],e[1],m):E(e[0],e[1])):_?E(e,m):E(e)};if(h)i=e.iterator;else if(p)i=e;else{if(!(r=As(e)))throw new Os(vs(e)+" is not iterable");if(ys(r)){for(o=0,s=Cs(e);s>o;o++)if((a=f(e[o]))&&bs(Ds,a))return a;return new Ns(!1)}i=Is(e,r)}for(c=h?e.next:i.next;!(d=Ts(c,i)).done;){var g=d.value;try{a=f(g)}catch(e){if(!i)throw e;ws(i,"throw",e)}if("object"==typeof a&&a&&bs(Ds,a))return a}return new Ns(!1)},Ls=Ri,ks=Nn,Ms=l,Us=Dr,Vs=Gr,xs=function(e,t,n){for(var i=co(t),r=uo.f,o=lo.f,s=0;s<i.length;s++){var a=i[s];ao(e,a)||n&&ao(n,a)||r(e,a,o(t,a))}},Fs=Vo,Bs=gn,js=x,Gs=function(e,t){xo(t)&&"cause"in t&&Fo(e,"cause",t.cause)},Ws=function(e,t,n,i){zo&&(Zo?Zo(e,t):Xo(e,"stack",Jo(n,i)))},Ks=Ps,Hs=function(e,t){return void 0===e?arguments.length<2?"":t:Ls(e)},Ys=pt("toStringTag"),Xs=Error,Js=[].push,zs=function(e,t){var n,i=Ms(Zs,this);Vs?n=Vs(new Xs,i?Us(this):Zs):(n=i?this:Fs(Zs),Bs(n,Ys,"Error")),void 0!==t&&Bs(n,"message",Hs(t)),Ws(n,zs,n.stack,1),arguments.length>2&&Gs(n,arguments[2]);var r=[];return Ks(e,Js,{that:r}),Bs(n,"errors",r),n};Vs?Vs(zs,Xs):xs(zs,Xs,{name:!0});var Zs=zs.prototype=Fs(Xs.prototype,{constructor:js(1,zs),message:js(1,""),name:js(1,"AggregateError")});ks({global:!0,constructor:!0,arity:2},{AggregateError:zs});var qs,Qs,$s,ea=I,ta=h.WeakMap,na=ea(ta)&&/native code/.test(String(ta)),ia=h,ra=Q,oa=gn,sa=$e,aa=He,ca=vr,da=Kr,la="Object already initialized",ua=ia.TypeError,ha=ia.WeakMap;if(na||aa.state){var pa=aa.state||(aa.state=new ha);pa.get=pa.get,pa.has=pa.has,pa.set=pa.set,qs=function(e,t){if(pa.has(e))throw new ua(la);return t.facade=e,pa.set(e,t),t},Qs=function(e){return pa.get(e)||{}},$s=function(e){return pa.has(e)}}else{var _a=ca("state");da[_a]=!0,qs=function(e,t){if(sa(e,_a))throw new ua(la);return t.facade=e,oa(e,_a,t),t},Qs=function(e){return sa(e,_a)?e[_a]:{}},$s=function(e){return sa(e,_a)}}var Ea,ma,fa,ga={set:qs,get:Qs,has:$s,enforce:function(e){return $s(e)?Qs(e):qs(e,{})},getterFor:function(e){return function(t){var n;if(!ra(t)||(n=Qs(t)).type!==e)throw new ua("Incompatible receiver, "+e+" required");return n}}},Sa=w,Ta=$e,Ra=Function.prototype,va=Sa&&Object.getOwnPropertyDescriptor,ya=Ta(Ra,"name"),Ca={EXISTS:ya,PROPER:ya&&"something"===function(){}.name,CONFIGURABLE:ya&&(!Sa||Sa&&va(Ra,"name").configurable)},ba=gn,Ia=function(e,t,n,i){return i&&i.enumerable?e[t]=n:ba(e,t,n),e},Aa=i,wa=I,Oa=Q,Na=Vo,Da=Dr,Pa=Ia,La=pt("iterator"),ka=!1;[].keys&&("next"in(fa=[].keys())?(ma=Da(Da(fa)))!==Object.prototype&&(Ea=ma):ka=!0);var Ma=!Oa(Ea)||Aa((function(){var e={};return Ea[La].call(e)!==e}));wa((Ea=Ma?{}:Na(Ea))[La])||Pa(Ea,La,(function(){return this}));var Ua={IteratorPrototype:Ea,BUGGY_SAFARI_ITERATORS:ka},Va=gi,xa=ui?{}.toString:function(){return"[object "+Va(this)+"]"},Fa=ui,Ba=Qt.f,ja=gn,Ga=$e,Wa=xa,Ka=pt("toStringTag"),Ha=function(e,t,n,i){var r=n?e:e&&e.prototype;r&&(Ga(r,Ka)||Ba(r,Ka,{configurable:!0,value:t}),i&&!Fa&&ja(r,"toString",Wa))},Ya=Ua.IteratorPrototype,Xa=Vo,Ja=x,za=Ha,Za=qo,qa=function(){return this},Qa=function(e,t,n,i){var r=t+" Iterator";return e.prototype=Xa(Ya,{next:Ja(+!i,n)}),za(e,r,!1,!0),Za[r]=qa,e},$a=Nn,ec=D,tc=Ca,nc=Qa,ic=Dr,rc=Ha,oc=Ia,sc=qo,ac=Ua,cc=tc.PROPER,dc=ac.BUGGY_SAFARI_ITERATORS,lc=pt("iterator"),uc="keys",hc="values",pc="entries",_c=function(){return this},Ec=function(e,t,n,i,r,o,s){nc(n,t,i);var a,c,d,l=function(e){if(e===r&&E)return E;if(!dc&&e&&e in p)return p[e];switch(e){case uc:case hc:case pc:return function(){return new n(this,e)}}return function(){return new n(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[lc]||p["@@iterator"]||r&&p[r],E=!dc&&_||l(r),m="Array"===t&&p.entries||_;if(m&&(a=ic(m.call(new e)))!==Object.prototype&&a.next&&(rc(a,u,!0,!0),sc[u]=_c),cc&&r===hc&&_&&_.name!==hc&&(h=!0,E=function(){return ec(_,this)}),r)if(c={values:l(hc),keys:o?E:l(uc),entries:l(pc)},s)for(d in c)(dc||h||!(d in p))&&oc(p,d,c[d]);else $a({target:t,proto:!0,forced:dc||h},c);return s&&p[lc]!==E&&oc(p,lc,E,{name:r}),sc[t]=E,c},mc=function(e,t){return{value:e,done:t}},fc=Z,gc=qo,Sc=ga;Qt.f;var Tc=Ec,Rc=mc,vc="Array Iterator",yc=Sc.set,Cc=Sc.getterFor(vc);Tc(Array,"Array",(function(e,t){yc(this,{type:vc,target:fc(e),index:0,kind:t})}),(function(){var e=Cc(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,Rc(void 0,!0);switch(e.kind){case"keys":return Rc(n,!1);case"values":return Rc(t[n],!1)}return Rc([n,t[n]],!1)}),"values"),gc.Arguments=gc.Array;var bc=Qt,Ic=function(e,t,n){return bc.f(e,t,n)},Ac=re,wc=Ic,Oc=w,Nc=pt("species"),Dc=l,Pc=TypeError,Lc=function(e,t){if(Dc(t,e))return e;throw new Pc("Incorrect invocation")},kc=I,Mc=He,Uc=d(Function.toString);kc(Mc.inspectSource)||(Mc.inspectSource=function(e){return Uc(e)});var Vc=Mc.inspectSource,xc=d,Fc=i,Bc=I,jc=gi,Gc=Vc,Wc=function(){},Kc=re("Reflect","construct"),Hc=/^\s*(?:class|function)\b/,Yc=xc(Hc.exec),Xc=!Hc.test(Wc),Jc=function(e){if(!Bc(e))return!1;try{return Kc(Wc,[],e),!0}catch(e){return!1}},zc=function(e){if(!Bc(e))return!1;switch(jc(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Xc||!!Yc(Hc,Gc(e))}catch(e){return!0}};zc.sham=!0;var Zc,qc,Qc,$c,ed=!Kc||Fc((function(){var e;return Jc(Jc.call)||!Jc(Object)||!Jc((function(){e=!0}))||e}))?zc:Jc,td=ed,nd=Ie,id=TypeError,rd=rn,od=function(e){if(td(e))return e;throw new id(nd(e)+" is not a constructor")},sd=K,ad=pt("species"),cd=function(e,t){var n,i=rd(e).constructor;return void 0===i||sd(n=rd(i)[ad])?t:od(n)},dd=d([].slice),ld=TypeError,ud=function(e,t){if(e<t)throw new ld("Not enough arguments");return e},hd=ae,pd=/ipad|iphone|ipod/i.test(hd)&&/applewebkit/i.test(hd),_d=h,Ed=f,md=qt,fd=I,gd=$e,Sd=i,Td=yo,Rd=dd,vd=At,yd=ud,Cd=pd,bd=Qi,Id=_d.setImmediate,Ad=_d.clearImmediate,wd=_d.process,Od=_d.Dispatch,Nd=_d.Function,Dd=_d.MessageChannel,Pd=_d.String,Ld=0,kd={},Md="onreadystatechange";Sd((function(){Zc=_d.location}));var Ud=function(e){if(gd(kd,e)){var t=kd[e];delete kd[e],t()}},Vd=function(e){return function(){Ud(e)}},xd=function(e){Ud(e.data)},Fd=function(e){_d.postMessage(Pd(e),Zc.protocol+"//"+Zc.host)};Id&&Ad||(Id=function(e){yd(arguments.length,1);var t=fd(e)?e:Nd(e),n=Rd(arguments,1);return kd[++Ld]=function(){Ed(t,void 0,n)},qc(Ld),Ld},Ad=function(e){delete kd[e]},bd?qc=function(e){wd.nextTick(Vd(e))}:Od&&Od.now?qc=function(e){Od.now(Vd(e))}:Dd&&!Cd?($c=(Qc=new Dd).port2,Qc.port1.onmessage=xd,qc=md($c.postMessage,$c)):_d.addEventListener&&fd(_d.postMessage)&&!_d.importScripts&&Zc&&"file:"!==Zc.protocol&&!Sd(Fd)?(qc=Fd,_d.addEventListener("message",xd,!1)):qc=Md in vd("script")?function(e){Td.appendChild(vd("script"))[Md]=function(){Td.removeChild(this),Ud(e)}}:function(e){setTimeout(Vd(e),0)});var Bd={set:Id,clear:Ad},jd=h,Gd=w,Wd=Object.getOwnPropertyDescriptor,Kd=function(e){if(!Gd)return jd[e];var t=Wd(jd,e);return t&&t.value},Hd=function(){this.head=null,this.tail=null};Hd.prototype={add:function(e){var t={item:e,next:null},n=this.tail;n?n.next=t:this.head=t,this.tail=t},get:function(){var e=this.head;if(e)return null===(this.head=e.next)&&(this.tail=null),e.item}};var Yd,Xd,Jd,zd,Zd,qd=Hd,Qd=/ipad|iphone|ipod/i.test(ae)&&"undefined"!=typeof Pebble,$d=/web0s(?!.*chrome)/i.test(ae),el=h,tl=Kd,nl=qt,il=Bd.set,rl=qd,ol=pd,sl=Qd,al=$d,cl=Qi,dl=el.MutationObserver||el.WebKitMutationObserver,ll=el.document,ul=el.process,hl=el.Promise,pl=tl("queueMicrotask");if(!pl){var _l=new rl,El=function(){var e,t;for(cl&&(e=ul.domain)&&e.exit();t=_l.get();)try{t()}catch(e){throw _l.head&&Yd(),e}e&&e.enter()};ol||cl||al||!dl||!ll?!sl&&hl&&hl.resolve?((zd=hl.resolve(void 0)).constructor=hl,Zd=nl(zd.then,zd),Yd=function(){Zd(El)}):cl?Yd=function(){ul.nextTick(El)}:(il=nl(il,el),Yd=function(){il(El)}):(Xd=!0,Jd=ll.createTextNode(""),new dl(El).observe(Jd,{characterData:!0}),Yd=function(){Jd.data=Xd=!Xd}),pl=function(e){_l.head||Yd(),_l.add(e)}}var ml=pl,fl=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},gl=h.Promise,Sl=h,Tl=gl,Rl=I,vl=Xt,yl=Vc,Cl=pt,bl=qi,Il=_e,Al=Tl&&Tl.prototype,wl=Cl("species"),Ol=!1,Nl=Rl(Sl.PromiseRejectionEvent),Dl=vl("Promise",(function(){var e=yl(Tl),t=e!==String(Tl);if(!t&&66===Il)return!0;if(!Al.catch||!Al.finally)return!0;if(!Il||Il<51||!/native code/.test(e)){var n=new Tl((function(e){e(1)})),i=function(e){e((function(){}),(function(){}))};if((n.constructor={})[wl]=i,!(Ol=n.then((function(){}))instanceof i))return!0}return!(t||"BROWSER"!==bl&&"DENO"!==bl||Nl)})),Pl={CONSTRUCTOR:Dl,REJECTION_EVENT:Nl,SUBCLASSING:Ol},Ll={},kl=Ne,Ml=TypeError,Ul=function(e){var t,n;this.promise=new e((function(e,i){if(void 0!==t||void 0!==n)throw new Ml("Bad Promise constructor");t=e,n=i})),this.resolve=kl(t),this.reject=kl(n)};Ll.f=function(e){return new Ul(e)};var Vl,xl,Fl,Bl=Nn,jl=Qi,Gl=h,Wl=$,Kl=D,Hl=Ia,Yl=Ha,Xl=function(e){var t=Ac(e);Oc&&t&&!t[Nc]&&wc(t,Nc,{configurable:!0,get:function(){return this}})},Jl=Ne,zl=I,Zl=Q,ql=Lc,Ql=cd,$l=Bd.set,eu=ml,tu=function(e,t){try{1===arguments.length?console.error(e):console.error(e,t)}catch(e){}},nu=fl,iu=qd,ru=ga,ou=gl,su=Pl,au=Ll,cu="Promise",du=su.CONSTRUCTOR,lu=su.REJECTION_EVENT,uu=ru.getterFor(cu),hu=ru.set,pu=ou&&ou.prototype,_u=ou,Eu=pu,mu=Gl.TypeError,fu=Gl.document,gu=Gl.process,Su=au.f,Tu=Su,Ru=!!(fu&&fu.createEvent&&Gl.dispatchEvent),vu="unhandledrejection",yu=function(e){var t;return!(!Zl(e)||!zl(t=e.then))&&t},Cu=function(e,t){var n,i,r,o=t.value,s=1===t.state,a=s?e.ok:e.fail,c=e.resolve,d=e.reject,l=e.domain;try{a?(s||(2===t.rejection&&Ou(t),t.rejection=1),!0===a?n=o:(l&&l.enter(),n=a(o),l&&(l.exit(),r=!0)),n===e.promise?d(new mu("Promise-chain cycle")):(i=yu(n))?Kl(i,n,c,d):c(n)):d(o)}catch(e){l&&!r&&l.exit(),d(e)}},bu=function(e,t){e.notified||(e.notified=!0,eu((function(){for(var n,i=e.reactions;n=i.get();)Cu(n,e);e.notified=!1,t&&!e.rejection&&Au(e)})))},Iu=function(e,t,n){var i,r;Ru?((i=fu.createEvent("Event")).promise=t,i.reason=n,i.initEvent(e,!1,!0),Gl.dispatchEvent(i)):i={promise:t,reason:n},!lu&&(r=Gl["on"+e])?r(i):e===vu&&tu("Unhandled promise rejection",n)},Au=function(e){Kl($l,Gl,(function(){var t,n=e.facade,i=e.value;if(wu(e)&&(t=nu((function(){jl?gu.emit("unhandledRejection",i,n):Iu(vu,n,i)})),e.rejection=jl||wu(e)?2:1,t.error))throw t.value}))},wu=function(e){return 1!==e.rejection&&!e.parent},Ou=function(e){Kl($l,Gl,(function(){var t=e.facade;jl?gu.emit("rejectionHandled",t):Iu("rejectionhandled",t,e.value)}))},Nu=function(e,t,n){return function(i){e(t,i,n)}},Du=function(e,t,n){e.done||(e.done=!0,n&&(e=n),e.value=t,e.state=2,bu(e,!0))},Pu=function(e,t,n){if(!e.done){e.done=!0,n&&(e=n);try{if(e.facade===t)throw new mu("Promise can't be resolved itself");var i=yu(t);i?eu((function(){var n={done:!1};try{Kl(i,t,Nu(Pu,n,e),Nu(Du,n,e))}catch(t){Du(n,t,e)}})):(e.value=t,e.state=1,bu(e,!1))}catch(t){Du({done:!1},t,e)}}};du&&(Eu=(_u=function(e){ql(this,Eu),Jl(e),Kl(Vl,this);var t=uu(this);try{e(Nu(Pu,t),Nu(Du,t))}catch(e){Du(t,e)}}).prototype,(Vl=function(e){hu(this,{type:cu,done:!1,notified:!1,parent:!1,reactions:new iu,rejection:!1,state:0,value:null})}).prototype=Hl(Eu,"then",(function(e,t){var n=uu(this),i=Su(Ql(this,_u));return n.parent=!0,i.ok=!zl(e)||e,i.fail=zl(t)&&t,i.domain=jl?gu.domain:void 0,0===n.state?n.reactions.add(i):eu((function(){Cu(i,n)})),i.promise})),xl=function(){var e=new Vl,t=uu(e);this.promise=e,this.resolve=Nu(Pu,t),this.reject=Nu(Du,t)},au.f=Su=function(e){return e===_u||e===Fl?new xl(e):Tu(e)}),Bl({global:!0,constructor:!0,wrap:!0,forced:du},{Promise:_u}),Fl=Wl.Promise,Yl(_u,cu,!1,!0),Xl(cu);var Lu=pt("iterator"),ku=!1;try{var Mu=0,Uu={next:function(){return{done:!!Mu++}},return:function(){ku=!0}};Uu[Lu]=function(){return this},Array.from(Uu,(function(){throw 2}))}catch(e){}var Vu=function(e,t){try{if(!t&&!ku)return!1}catch(e){return!1}var n=!1;try{var i={};i[Lu]=function(){return{next:function(){return{done:n=!0}}}},e(i)}catch(e){}return n},xu=gl,Fu=Pl.CONSTRUCTOR||!Vu((function(e){xu.all(e).then(void 0,(function(){}))})),Bu=D,ju=Ne,Gu=Ll,Wu=fl,Ku=Ps;Nn({target:"Promise",stat:!0,forced:Fu},{all:function(e){var t=this,n=Gu.f(t),i=n.resolve,r=n.reject,o=Wu((function(){var n=ju(t.resolve),o=[],s=0,a=1;Ku(e,(function(e){var c=s++,d=!1;a++,Bu(n,t,e).then((function(e){d||(d=!0,o[c]=e,--a||i(o))}),r)})),--a||i(o)}));return o.error&&r(o.value),n.promise}});var Hu=Nn,Yu=Pl.CONSTRUCTOR;gl&&gl.prototype,Hu({target:"Promise",proto:!0,forced:Yu,real:!0},{catch:function(e){return this.then(void 0,e)}});var Xu=D,Ju=Ne,zu=Ll,Zu=fl,qu=Ps;Nn({target:"Promise",stat:!0,forced:Fu},{race:function(e){var t=this,n=zu.f(t),i=n.reject,r=Zu((function(){var r=Ju(t.resolve);qu(e,(function(e){Xu(r,t,e).then(n.resolve,i)}))}));return r.error&&i(r.value),n.promise}});var Qu=Ll;Nn({target:"Promise",stat:!0,forced:Pl.CONSTRUCTOR},{reject:function(e){var t=Qu.f(this);return(0,t.reject)(e),t.promise}});var $u=rn,eh=Q,th=Ll,nh=function(e,t){if($u(e),eh(t)&&t.constructor===e)return t;var n=th.f(e);return(0,n.resolve)(t),n.promise},ih=Nn,rh=gl,oh=Pl.CONSTRUCTOR,sh=nh,ah=re("Promise"),ch=!oh;ih({target:"Promise",stat:!0,forced:true},{resolve:function(e){return sh(ch&&this===ah?rh:this,e)}});var dh=D,lh=Ne,uh=Ll,hh=fl,ph=Ps;Nn({target:"Promise",stat:!0,forced:Fu},{allSettled:function(e){var t=this,n=uh.f(t),i=n.resolve,r=n.reject,o=hh((function(){var n=lh(t.resolve),r=[],o=0,s=1;ph(e,(function(e){var a=o++,c=!1;s++,dh(n,t,e).then((function(e){c||(c=!0,r[a]={status:"fulfilled",value:e},--s||i(r))}),(function(e){c||(c=!0,r[a]={status:"rejected",reason:e},--s||i(r))}))})),--s||i(r)}));return o.error&&r(o.value),n.promise}});var _h=D,Eh=Ne,mh=re,fh=Ll,gh=fl,Sh=Ps,Th="No one promise resolved";Nn({target:"Promise",stat:!0,forced:Fu},{any:function(e){var t=this,n=mh("AggregateError"),i=fh.f(t),r=i.resolve,o=i.reject,s=gh((function(){var i=Eh(t.resolve),s=[],a=0,c=1,d=!1;Sh(e,(function(e){var l=a++,u=!1;c++,_h(i,t,e).then((function(e){u||d||(d=!0,r(e))}),(function(e){u||d||(u=!0,s[l]=e,--c||o(new n(s,Th)))}))})),--c||o(new n(s,Th))}));return s.error&&o(s.value),i.promise}});var Rh=Nn,vh=f,yh=dd,Ch=Ll,bh=Ne,Ih=fl,Ah=h.Promise,wh=!1;Rh({target:"Promise",stat:!0,forced:!Ah||!Ah.try||Ih((function(){Ah.try((function(e){wh=8===e}),8)})).error||!wh},{try:function(e){var t=arguments.length>1?yh(arguments,1):[],n=Ch.f(this),i=Ih((function(){return vh(bh(e),void 0,t)}));return(i.error?n.reject:n.resolve)(i.value),n.promise}});var Oh=Ll;Nn({target:"Promise",stat:!0},{withResolvers:function(){var e=Oh.f(this);return{promise:e.promise,resolve:e.resolve,reject:e.reject}}});var Nh=Nn,Dh=gl,Ph=i,Lh=re,kh=I,Mh=cd,Uh=nh,Vh=Dh&&Dh.prototype;Nh({target:"Promise",proto:!0,real:!0,forced:!!Dh&&Ph((function(){Vh.finally.call({then:function(){}},(function(){}))}))},{finally:function(e){var t=Mh(this,Lh("Promise")),n=kh(e);return this.then(n?function(n){return Uh(t,e()).then((function(){return n}))}:e,n?function(n){return Uh(t,e()).then((function(){throw n}))}:e)}});var xh=d,Fh=Mn,Bh=Ri,jh=X,Gh=xh("".charAt),Wh=xh("".charCodeAt),Kh=xh("".slice),Hh=function(e){return function(t,n){var i,r,o=Bh(jh(t)),s=Fh(n),a=o.length;return s<0||s>=a?e?"":void 0:(i=Wh(o,s))<55296||i>56319||s+1===a||(r=Wh(o,s+1))<56320||r>57343?e?Gh(o,s):i:e?Kh(o,s,s+2):r-56320+(i-55296<<10)+65536}},Yh={codeAt:Hh(!1),charAt:Hh(!0)},Xh=Yh.charAt,Jh=Ri,zh=ga,Zh=Ec,qh=mc,Qh="String Iterator",$h=zh.set,ep=zh.getterFor(Qh);Zh(String,"String",(function(e){$h(this,{type:Qh,string:Jh(e),index:0})}),(function(){var e,t=ep(this),n=t.string,i=t.index;return i>=n.length?qh(void 0,!0):(e=Xh(n,i),t.index+=e.length,qh(e,!1))}));var tp=$.Promise,np={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},ip=h,rp=Ha,op=qo;for(var sp in np)rp(ip[sp],sp),op[sp]=op.Array;var ap=tp,cp=n(ap),dp=ni("Array","values"),lp=gi,up=$e,hp=l,pp=dp,_p=Array.prototype,Ep={DOMTokenList:!0,NodeList:!0},mp=function(e){var t=e.values;return e===_p||hp(_p,e)&&t===_p.values||up(Ep,lp(e))?pp:t},fp=n(mp),gp=Ie,Sp=TypeError,Tp=dd,Rp=Math.floor,vp=function(e,t){var n=e.length;if(n<8)for(var i,r,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}else for(var s=Rp(n/2),a=vp(Tp(e,0,s),t),c=vp(Tp(e,s),t),d=a.length,l=c.length,u=0,h=0;u<d||h<l;)e[u+h]=u<d&&h<l?t(a[u],c[h])<=0?a[u++]:c[h++]:u<d?a[u++]:c[h++];return e},yp=vp,Cp=ae.match(/firefox\/(\d+)/i),bp=!!Cp&&+Cp[1],Ip=/MSIE|Trident/.test(ae),Ap=ae.match(/AppleWebKit\/(\d+)\./),wp=!!Ap&&+Ap[1],Op=Nn,Np=d,Dp=Ne,Pp=Ze,Lp=Wn,kp=function(e,t){if(!delete e[t])throw new Sp("Cannot delete property "+gp(t)+" of "+gp(e))},Mp=Ri,Up=i,Vp=yp,xp=Yi,Fp=bp,Bp=Ip,jp=_e,Gp=wp,Wp=[],Kp=Np(Wp.sort),Hp=Np(Wp.push),Yp=Up((function(){Wp.sort(void 0)})),Xp=Up((function(){Wp.sort(null)})),Jp=xp("sort"),zp=!Up((function(){if(jp)return jp<70;if(!(Fp&&Fp>3)){if(Bp)return!0;if(Gp)return Gp<603;var e,t,n,i,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)Wp.push({k:t+i,v:n})}for(Wp.sort((function(e,t){return t.v-e.v})),i=0;i<Wp.length;i++)t=Wp[i].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));Op({target:"Array",proto:!0,forced:Yp||!Xp||!Jp||!zp},{sort:function(e){void 0!==e&&Dp(e);var t=Pp(this);if(zp)return void 0===e?Kp(t):Kp(t,e);var n,i,r=[],o=Lp(t);for(i=0;i<o;i++)i in t&&Hp(r,t[i]);for(Vp(r,function(e){return function(t,n){if(void 0===n)return-1;if(void 0===t)return 1;if(void 0!==e)return+e(t,n)||0;var i=Mp(t),r=Mp(n);return i===r?0:i>r?1:-1}}(e)),n=Lp(r),i=0;i<n;)t[i]=r[i++];for(;i<o;)kp(t,i++);return t}});var Zp=ni("Array","sort"),qp=l,Qp=Zp,$p=Array.prototype,e_=function(e){var t=e.sort;return e===$p||qp($p,e)&&t===$p.sort?Qp:t},t_=n(e_),n_=Nn,i_=d,r_=Fn,o_=RangeError,s_=String.fromCharCode,a_=String.fromCodePoint,c_=i_([].join);n_({target:"String",stat:!0,arity:1,forced:!!a_&&1!==a_.length},{fromCodePoint:function(e){for(var t,n=[],i=arguments.length,r=0;i>r;){if(r_(t=+arguments[r],1114111)!==t)throw new o_(t+" is not a valid code point");n[r++]=t<65536?s_(t):s_(55296+((t-=65536)>>10),t%1024+56320)}return c_(n,"")}});var d_=i,l_=pt("iterator"),u_=!d_((function(){var e=new URL("b?a=1&b=2&c=3","https://a"),t=e.searchParams,n=new URLSearchParams("a=1&a=2&b=3"),i="";return e.pathname="c%20d",t.forEach((function(e,n){t.delete("b"),i+=n+e})),n.delete("a",2),n.delete("b",void 0),!e.toJSON||!n.has("a",1)||n.has("a",2)||!n.has("a",void 0)||n.has("b")||!t.size&&true||!t.sort||"https://a/c%20d?a=1&c=3"!==e.href||"3"!==t.get("c")||"a=1"!==String(new URLSearchParams("?a=1"))||!t[l_]||"a"!==new URL("https://a@b").username||"b"!==new URLSearchParams(new URLSearchParams("a=b")).get("a")||"xn--e1aybc"!==new URL("https://тест").host||"#%D0%B1"!==new URL("https://a#б").hash||"a1c3"!==i||"x"!==new URL("https://x",void 0).host})),h_=Ia,p_=Nn,__=h,E_=Kd,m_=re,f_=D,g_=d,S_=w,T_=u_,R_=Ia,v_=Ic,y_=function(e,t,n){for(var i in t)n&&n.unsafe&&e[i]?e[i]=t[i]:h_(e,i,t[i],n);return e},C_=Ha,b_=Qa,I_=ga,A_=Lc,w_=I,O_=$e,N_=qt,D_=gi,P_=rn,L_=Q,k_=Ri,M_=Vo,U_=x,V_=_s,x_=as,F_=mc,B_=ud,j_=yp,G_=pt("iterator"),W_="URLSearchParams",K_=W_+"Iterator",H_=I_.set,Y_=I_.getterFor(W_),X_=I_.getterFor(K_),J_=E_("fetch"),z_=E_("Request"),Z_=E_("Headers"),q_=z_&&z_.prototype,Q_=Z_&&Z_.prototype,$_=__.TypeError,eE=__.encodeURIComponent,tE=String.fromCharCode,nE=m_("String","fromCodePoint"),iE=parseInt,rE=g_("".charAt),oE=g_([].join),sE=g_([].push),aE=g_("".replace),cE=g_([].shift),dE=g_([].splice),lE=g_("".split),uE=g_("".slice),hE=g_(/./.exec),pE=/\+/g,_E=/^[0-9a-f]+$/i,EE=function(e,t){var n=uE(e,t,t+2);return hE(_E,n)?iE(n,16):NaN},mE=function(e){for(var t=0,n=128;n>0&&0!=(e&n);n>>=1)t++;return t},fE=function(e){var t=null,n=e.length;switch(n){case 1:t=e[0];break;case 2:t=(31&e[0])<<6|63&e[1];break;case 3:t=(15&e[0])<<12|(63&e[1])<<6|63&e[2];break;case 4:t=(7&e[0])<<18|(63&e[1])<<12|(63&e[2])<<6|63&e[3]}return null===t||t>1114111||t>=55296&&t<=57343||t<(n>3?65536:n>2?2048:n>1?128:0)?null:t},gE=function(e){for(var t=(e=aE(e,pE," ")).length,n="",i=0;i<t;){var r=rE(e,i);if("%"===r){if("%"===rE(e,i+1)||i+3>t){n+="%",i++;continue}var o=EE(e,i+1);if(o!=o){n+=r,i++;continue}i+=2;var s=mE(o);if(0===s)r=tE(o);else{if(1===s||s>4){n+="�",i++;continue}for(var a=[o],c=1;c<s&&!(++i+3>t||"%"!==rE(e,i));){var d=EE(e,i+1);if(d!=d||d>191||d<128)break;if(1===c){if(224===o&&d<160)break;if(237===o&&d>159)break;if(240===o&&d<144)break;if(244===o&&d>143)break}sE(a,d),i+=2,c++}if(a.length!==s){n+="�";continue}var l=fE(a);if(null===l){for(var u=0;u<s;u++)n+="�";i++;continue}r=nE(l)}}n+=r,i++}return n},SE=/[!'()~]|%20/g,TE={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},RE=function(e){return TE[e]},vE=function(e){return aE(eE(e),SE,RE)},yE=b_((function(e,t){H_(this,{type:K_,target:Y_(e).entries,index:0,kind:t})}),W_,(function(){var e=X_(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,F_(void 0,!0);var i=t[n];switch(e.kind){case"keys":return F_(i.key,!1);case"values":return F_(i.value,!1)}return F_([i.key,i.value],!1)}),!0),CE=function(e){this.entries=[],this.url=null,void 0!==e&&(L_(e)?this.parseObject(e):this.parseQuery("string"==typeof e?"?"===rE(e,0)?uE(e,1):e:k_(e)))};CE.prototype={type:W_,bindURL:function(e){this.url=e,this.update()},parseObject:function(e){var t,n,i,r,o,s,a,c=this.entries,d=x_(e);if(d)for(n=(t=V_(e,d)).next;!(i=f_(n,t)).done;){if(o=(r=V_(P_(i.value))).next,(s=f_(o,r)).done||(a=f_(o,r)).done||!f_(o,r).done)throw new $_("Expected sequence with length 2");sE(c,{key:k_(s.value),value:k_(a.value)})}else for(var l in e)O_(e,l)&&sE(c,{key:l,value:k_(e[l])})},parseQuery:function(e){if(e)for(var t,n,i=this.entries,r=lE(e,"&"),o=0;o<r.length;)(t=r[o++]).length&&(n=lE(t,"="),sE(i,{key:gE(cE(n)),value:gE(oE(n,"="))}))},serialize:function(){for(var e,t=this.entries,n=[],i=0;i<t.length;)e=t[i++],sE(n,vE(e.key)+"="+vE(e.value));return oE(n,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var bE=function(){A_(this,IE);var e=H_(this,new CE(arguments.length>0?arguments[0]:void 0));S_||(this.size=e.entries.length)},IE=bE.prototype;if(y_(IE,{append:function(e,t){var n=Y_(this);B_(arguments.length,2),sE(n.entries,{key:k_(e),value:k_(t)}),S_||this.size++,n.updateURL()},delete:function(e){for(var t=Y_(this),n=B_(arguments.length,1),i=t.entries,r=k_(e),o=n<2?void 0:arguments[1],s=void 0===o?o:k_(o),a=0;a<i.length;){var c=i[a];c.key!==r||void 0!==s&&c.value!==s?a++:dE(i,a,1)}S_||(this.size=i.length),t.updateURL()},get:function(e){var t=Y_(this).entries;B_(arguments.length,1);for(var n=k_(e),i=0;i<t.length;i++)if(t[i].key===n)return t[i].value;return null},getAll:function(e){var t=Y_(this).entries;B_(arguments.length,1);for(var n=k_(e),i=[],r=0;r<t.length;r++)t[r].key===n&&sE(i,t[r].value);return i},has:function(e){for(var t=Y_(this).entries,n=B_(arguments.length,1),i=k_(e),r=n<2?void 0:arguments[1],o=void 0===r?r:k_(r),s=0;s<t.length;){var a=t[s++];if(a.key===i&&(void 0===o||a.value===o))return!0}return!1},set:function(e,t){var n=Y_(this);B_(arguments.length,2);for(var i,r=n.entries,o=!1,s=k_(e),a=k_(t),c=0;c<r.length;c++)(i=r[c]).key===s&&(o?dE(r,c--,1):(o=!0,i.value=a));o||sE(r,{key:s,value:a}),S_||(this.size=r.length),n.updateURL()},sort:function(){var e=Y_(this);j_(e.entries,(function(e,t){return e.key>t.key?1:-1})),e.updateURL()},forEach:function(e){for(var t,n=Y_(this).entries,i=N_(e,arguments.length>1?arguments[1]:void 0),r=0;r<n.length;)i((t=n[r++]).value,t.key,this)},keys:function(){return new yE(this,"keys")},values:function(){return new yE(this,"values")},entries:function(){return new yE(this,"entries")}},{enumerable:!0}),R_(IE,G_,IE.entries,{name:"entries"}),R_(IE,"toString",(function(){return Y_(this).serialize()}),{enumerable:!0}),S_&&v_(IE,"size",{get:function(){return Y_(this).entries.length},configurable:!0,enumerable:!0}),C_(bE,W_),p_({global:!0,constructor:!0,forced:!T_},{URLSearchParams:bE}),!T_&&w_(Z_)){var AE=g_(Q_.has),wE=g_(Q_.set),OE=function(e){if(L_(e)){var t,n=e.body;if(D_(n)===W_)return t=e.headers?new Z_(e.headers):new Z_,AE(t,"content-type")||wE(t,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),M_(e,{body:U_(0,k_(n)),headers:U_(0,t)})}return e};if(w_(J_)&&p_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(e){return J_(e,arguments.length>1?OE(arguments[1]):{})}}),w_(z_)){var NE=function(e){return A_(this,q_),new z_(e,arguments.length>1?OE(arguments[1]):{})};q_.constructor=NE,NE.prototype=q_,p_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:NE})}}var DE,PE={URLSearchParams:bE,getState:Y_},LE=$.URLSearchParams,kE=w,ME=d,UE=D,VE=i,xE=Eo,FE=eo,BE=P,jE=Ze,GE=W,WE=Object.assign,KE=Object.defineProperty,HE=ME([].concat),YE=!WE||VE((function(){if(kE&&1!==WE({b:1},WE(KE({},"a",{enumerable:!0,get:function(){KE(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol("assign detection"),i="abcdefghijklmnopqrst";return e[n]=7,i.split("").forEach((function(e){t[e]=e})),7!==WE({},e)[n]||xE(WE({},t)).join("")!==i}))?function(e,t){for(var n=jE(e),i=arguments.length,r=1,o=FE.f,s=BE.f;i>r;)for(var a,c=GE(arguments[r++]),d=o?HE(xE(c),o(c)):xE(c),l=d.length,u=0;l>u;)a=d[u++],kE&&!UE(s,c,a)||(n[a]=c[a]);return n}:WE,XE=rn,JE=gs,zE=w,ZE=Qt,qE=x,QE=function(e,t,n){zE?ZE.f(e,t,qE(0,n)):e[t]=n},$E=w,em=cr,tm=TypeError,nm=Object.getOwnPropertyDescriptor,im=$E&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}()?function(e,t){if(em(e)&&!nm(e,"length").writable)throw new tm("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t},rm=qt,om=D,sm=Ze,am=function(e,t,n,i){try{return i?t(XE(n)[0],n[1]):t(n)}catch(t){JE(e,"throw",t)}},cm=ts,dm=ed,lm=Wn,um=QE,hm=im,pm=_s,_m=as,Em=gs,mm=Array,fm=function(e){var t=dm(this),n=arguments.length,i=n>1?arguments[1]:void 0,r=void 0!==i;r&&(i=rm(i,n>2?arguments[2]:void 0));var o,s,a,c,d,l,u=sm(e),h=_m(u),p=0;if(!h||this===mm&&cm(h))for(o=lm(u),s=t?new this(o):mm(o);o>p;p++)l=r?i(u[p],p):u[p],um(s,p,l);else for(s=t?new this:[],d=(c=pm(u,h)).next;!(a=om(d,c)).done;p++){l=r?am(c,i,[a.value,p],!0):a.value;try{um(s,p,l)}catch(e){Em(c,"throw",e)}}return hm(s,p),s},gm=d,Sm=2147483647,Tm=/[^\0-\u007E]/,Rm=/[.\u3002\uFF0E\uFF61]/g,vm="Overflow: input needs wider integers to process",ym=RangeError,Cm=gm(Rm.exec),bm=Math.floor,Im=String.fromCharCode,Am=gm("".charCodeAt),wm=gm([].join),Om=gm([].push),Nm=gm("".replace),Dm=gm("".split),Pm=gm("".toLowerCase),Lm=function(e){return e+22+75*(e<26)},km=function(e,t,n){var i=0;for(e=n?bm(e/700):e>>1,e+=bm(e/t);e>455;)e=bm(e/35),i+=36;return bm(i+36*e/(e+38))},Mm=function(e){var t=[];e=function(e){for(var t=[],n=0,i=e.length;n<i;){var r=Am(e,n++);if(r>=55296&&r<=56319&&n<i){var o=Am(e,n++);56320==(64512&o)?Om(t,((1023&r)<<10)+(1023&o)+65536):(Om(t,r),n--)}else Om(t,r)}return t}(e);var n,i,r=e.length,o=128,s=0,a=72;for(n=0;n<e.length;n++)(i=e[n])<128&&Om(t,Im(i));var c=t.length,d=c;for(c&&Om(t,"-");d<r;){var l=Sm;for(n=0;n<e.length;n++)(i=e[n])>=o&&i<l&&(l=i);var u=d+1;if(l-o>bm((Sm-s)/u))throw new ym(vm);for(s+=(l-o)*u,o=l,n=0;n<e.length;n++){if((i=e[n])<o&&++s>Sm)throw new ym(vm);if(i===o){for(var h=s,p=36;;){var _=p<=a?1:p>=a+26?26:p-a;if(h<_)break;var E=h-_,m=36-_;Om(t,Im(Lm(_+E%m))),h=bm(E/m),p+=36}Om(t,Im(Lm(h))),a=km(s,u,d===c),s=0,d++}}s++,o++}return wm(t,"")},Um=Nn,Vm=w,xm=u_,Fm=h,Bm=qt,jm=d,Gm=Ia,Wm=Ic,Km=Lc,Hm=$e,Ym=YE,Xm=fm,Jm=dd,zm=Yh.codeAt,Zm=function(e){var t,n,i=[],r=Dm(Nm(Pm(e),Rm,"."),".");for(t=0;t<r.length;t++)n=r[t],Om(i,Cm(Tm,n)?"xn--"+Mm(n):n);return wm(i,".")},qm=Ri,Qm=Ha,$m=ud,ef=PE,tf=ga,nf=tf.set,rf=tf.getterFor("URL"),of=ef.URLSearchParams,sf=ef.getState,af=Fm.URL,cf=Fm.TypeError,df=Fm.encodeURIComponent,lf=Fm.parseInt,uf=Math.floor,hf=Math.pow,pf=jm("".charAt),_f=jm(/./.exec),Ef=jm([].join),mf=jm(1.1.toString),ff=jm([].pop),gf=jm([].push),Sf=jm("".replace),Tf=jm([].shift),Rf=jm("".split),vf=jm("".slice),yf=jm("".toLowerCase),Cf=jm([].unshift),bf="Invalid scheme",If="Invalid host",Af="Invalid port",wf=/[a-z]/i,Of=/[\d+\-.a-z]/i,Nf=/\d/,Df=/^0x/i,Pf=/^[0-7]+$/,Lf=/^\d+$/,kf=/^[\da-f]+$/i,Mf=/[\0\t\n\r #%/:<>?@[\\\]^|]/,Uf=/[\0\t\n\r #/:<>?@[\\\]^|]/,Vf=/^[\u0000-\u0020]+/,xf=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,Ff=/[\t\n\r]/g,Bf=function(e){var t,n,i,r;if("number"==typeof e){for(t=[],n=0;n<4;n++)Cf(t,e%256),e=uf(e/256);return Ef(t,".")}if("object"==typeof e){for(t="",i=function(e){for(var t=null,n=1,i=null,r=0,o=0;o<8;o++)0!==e[o]?(r>n&&(t=i,n=r),i=null,r=0):(null===i&&(i=o),++r);return r>n?i:t}(e),n=0;n<8;n++)r&&0===e[n]||(r&&(r=!1),i===n?(t+=n?":":"::",r=!0):(t+=mf(e[n],16),n<7&&(t+=":")));return"["+t+"]"}return e},jf={},Gf=Ym({},jf,{" ":1,'"':1,"#":1,"<":1,">":1}),Wf=Ym({},Gf,{"'":1}),Kf=Ym({},jf,{" ":1,'"':1,"<":1,">":1,"`":1}),Hf=Ym({},Kf,{"#":1,"?":1,"{":1,"}":1,"^":1}),Yf=Ym({},Hf,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Xf=function(e,t){var n=zm(e,0);return n>=32&&n<127&&!Hm(t,e)?e:"'"===e&&Hm(t,e)?"%27":df(e)},Jf={ftp:21,file:null,http:80,https:443,ws:80,wss:443},zf=function(e,t){var n;return 2===e.length&&_f(wf,pf(e,0))&&(":"===(n=pf(e,1))||!t&&"|"===n)},Zf=function(e){var t;return e.length>1&&zf(vf(e,0,2))&&(2===e.length||"/"===(t=pf(e,2))||"\\"===t||"?"===t||"#"===t)},qf=function(e){return"."===e||"%2e"===yf(e)},Qf={},$f={},eg={},tg={},ng={},ig={},rg={},og={},sg={},ag={},cg={},dg={},lg={},ug={},hg={},pg={},_g={},Eg={},mg={},fg={},gg={},Sg=function(e,t,n){var i,r,o,s=qm(e);if(t){if(r=this.parse(s))throw new cf(r);this.searchParams=null}else{if(void 0!==n&&(i=new Sg(n,!0)),r=this.parse(s,null,i))throw new cf(r);(o=sf(new of)).bindURL(this),this.searchParams=o}};Sg.prototype={type:"URL",parse:function(e,t,n){var i,r,o,s,a,c=this,d=t||Qf,l=0,u="",h=!1,p=!1,_=!1;for(e=qm(e),t||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,e=Sf(e,Vf,""),e=Sf(e,xf,"$1")),e=Sf(e,Ff,""),i=Xm(e);l<=i.length;){switch(r=i[l],d){case Qf:if(!r||!_f(wf,r)){if(t)return bf;d=eg;continue}u+=yf(r),d=$f;break;case $f:if(r&&_f(Of,r))u+=yf(r);else{if(":"!==r){if(t)return bf;u="",d=eg,l=0;continue}if(t&&(c.isSpecial()!==Hm(Jf,u)||"file"===u&&(c.includesCredentials()||null!==c.port)||"file"===c.scheme&&""===c.host))return;if(c.scheme=u,t)return void(c.isSpecial()&&Jf[c.scheme]===c.port&&(c.port=null));u="","file"===c.scheme?d=ug:c.isSpecial()&&n&&n.scheme===c.scheme?d=tg:c.isSpecial()?d=og:"/"===i[l+1]?(d=ng,l++):(c.cannotBeABaseURL=!0,gf(c.path,""),d=mg)}break;case eg:if(!n||n.cannotBeABaseURL&&"#"!==r)return bf;if(n.cannotBeABaseURL&&"#"===r){c.scheme=n.scheme,c.path=Jm(n.path),c.query=n.query,c.fragment="",c.cannotBeABaseURL=!0,d=gg;break}d="file"===n.scheme?ug:ig;continue;case tg:if("/"!==r||"/"!==i[l+1]){d=ig;continue}d=sg,l++;break;case ng:if("/"===r){d=ag;break}d=Eg;continue;case ig:if(c.scheme=n.scheme,r===DE)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=Jm(n.path),c.query=n.query;else if("/"===r||"\\"===r&&c.isSpecial())d=rg;else if("?"===r)c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=Jm(n.path),c.query="",d=fg;else{if("#"!==r){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=Jm(n.path),c.path.length&&c.path.length--,d=Eg;continue}c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,c.path=Jm(n.path),c.query=n.query,c.fragment="",d=gg}break;case rg:if(!c.isSpecial()||"/"!==r&&"\\"!==r){if("/"!==r){c.username=n.username,c.password=n.password,c.host=n.host,c.port=n.port,d=Eg;continue}d=ag}else d=sg;break;case og:if(d=sg,"/"!==r||"/"!==i[l+1])continue;l++;break;case sg:if("/"!==r&&"\\"!==r){d=ag;continue}break;case ag:if("@"===r){h&&(u="%40"+u),h=!0,o=Xm(u);for(var E=0;E<o.length;E++){var m=o[E];if(":"!==m||_){var f=Xf(m,Yf);_?c.password+=f:c.username+=f}else _=!0}u=""}else if(r===DE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()){if(h&&""===u)return"Invalid authority";l-=Xm(u).length+1,u="",d=cg}else u+=r;break;case cg:case dg:if(t&&"file"===c.scheme){d=pg;continue}if(":"!==r||p){if(r===DE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()){if(c.isSpecial()&&""===u)return If;if(t&&""===u&&(c.includesCredentials()||null!==c.port))return;if(s=c.parseHost(u))return s;if(u="",d=_g,t)return;continue}"["===r?p=!0:"]"===r&&(p=!1),u+=r}else{if(""===u)return If;if(t===dg)return;if(s=c.parseHost(u))return s;u="",d=lg}break;case lg:if(!_f(Nf,r)){if(r===DE||"/"===r||"?"===r||"#"===r||"\\"===r&&c.isSpecial()||t){if(""!==u){var g=lf(u,10);if(g>65535)return Af;c.port=c.isSpecial()&&g===Jf[c.scheme]?null:g,u=""}if(t)return;d=_g;continue}return Af}u+=r;break;case ug:if(c.scheme="file",c.host="","/"===r||"\\"===r)d=hg;else{if(!n||"file"!==n.scheme){d=Eg;continue}switch(r){case DE:c.host=n.host,c.path=Jm(n.path),c.query=n.query;break;case"?":c.host=n.host,c.path=Jm(n.path),c.query="",d=fg;break;case"#":c.host=n.host,c.path=Jm(n.path),c.query=n.query,c.fragment="",d=gg;break;default:c.host=n.host,Zf(Ef(Jm(i,l),""))||(c.path=Jm(n.path),c.shortenPath()),d=Eg;continue}}break;case hg:if("/"===r||"\\"===r){d=pg;break}n&&"file"===n.scheme&&(c.host=n.host,!Zf(Ef(Jm(i,l),""))&&zf(n.path[0],!0)&&gf(c.path,n.path[0])),d=Eg;continue;case pg:if(r===DE||"/"===r||"\\"===r||"?"===r||"#"===r){if(!t&&zf(u))d=Eg;else if(""===u){if(c.host="",t)return;d=_g}else{if(s=c.parseHost(u))return s;if("localhost"===c.host&&(c.host=""),t)return;u="",d=_g}continue}u+=r;break;case _g:if(c.isSpecial()){if(d=Eg,"/"!==r&&"\\"!==r)continue}else if(t||"?"!==r)if(t||"#"!==r){if(r!==DE&&(d=Eg,"/"!==r))continue}else c.fragment="",d=gg;else c.query="",d=fg;break;case Eg:if(r===DE||"/"===r||"\\"===r&&c.isSpecial()||!t&&("?"===r||"#"===r)){if(".."===(a=yf(a=u))||"%2e."===a||".%2e"===a||"%2e%2e"===a?(c.shortenPath(),"/"===r||"\\"===r&&c.isSpecial()||gf(c.path,"")):qf(u)?"/"===r||"\\"===r&&c.isSpecial()||gf(c.path,""):("file"===c.scheme&&!c.path.length&&zf(u)&&(null!==c.host&&""!==c.host&&(c.host=""),u=pf(u,0)+":"),gf(c.path,u)),u="","file"===c.scheme&&(r===DE||"?"===r||"#"===r))for(;c.path.length>1&&""===c.path[0];)Tf(c.path);"?"===r?(c.query="",d=fg):"#"===r&&(c.fragment="",d=gg)}else u+=Xf(r,Hf);break;case mg:"?"===r?(c.query="",d=fg):"#"===r?(c.fragment="",d=gg):r!==DE&&(c.path[0]+=Xf(r,jf));break;case fg:t||"#"!==r?r!==DE&&(c.query+=Xf(r,c.isSpecial()?Wf:Gf)):(c.fragment="",d=gg);break;case gg:r!==DE&&(c.fragment+=Xf(r,Kf))}l++}},parseHost:function(e){var t,n,i;if("["===pf(e,0)){if("]"!==pf(e,e.length-1))return If;if(t=function(e){var t,n,i,r,o,s,a,c=[0,0,0,0,0,0,0,0],d=0,l=null,u=0,h=function(){return pf(e,u)};if(":"===h()){if(":"!==pf(e,1))return;u+=2,l=++d}for(;h();){if(8===d)return;if(":"!==h()){for(t=n=0;n<4&&_f(kf,h());)t=16*t+lf(h(),16),u++,n++;if("."===h()){if(0===n)return;if(u-=n,d>6)return;for(i=0;h();){if(r=null,i>0){if(!("."===h()&&i<4))return;u++}if(!_f(Nf,h()))return;for(;_f(Nf,h());){if(o=lf(h(),10),null===r)r=o;else{if(0===r)return;r=10*r+o}if(r>255)return;u++}c[d]=256*c[d]+r,2!=++i&&4!==i||d++}if(4!==i)return;break}if(":"===h()){if(u++,!h())return}else if(h())return;c[d++]=t}else{if(null!==l)return;u++,l=++d}}if(null!==l)for(s=d-l,d=7;0!==d&&s>0;)a=c[d],c[d--]=c[l+s-1],c[l+--s]=a;else if(8!==d)return;return c}(vf(e,1,-1)),!t)return If;this.host=t}else if(this.isSpecial()){if(e=Zm(e),_f(Mf,e))return If;if(function(e){var t,n,i=Rf(e,".");if(""===i[i.length-1]){if(1===i.length)return!1;i.length--}return t=i[i.length-1],!!_f(Lf,t)||!!_f(Df,t)&&(""===(n=vf(t,2))||!!_f(kf,n))}(e)){if(t=function(e){var t,n,i,r,o,s,a,c=Rf(e,".");if(c.length&&""===c[c.length-1]&&c.length--,(t=c.length)>4)return null;for(n=[],i=0;i<t;i++){if(""===(r=c[i]))return null;if(o=10,r.length>1&&"0"===pf(r,0)&&(o=_f(Df,r)?16:8,r=vf(r,8===o?1:2)),""===r)s=0;else{if(!_f(10===o?Lf:8===o?Pf:kf,r))return null;s=lf(r,o)}gf(n,s)}for(i=0;i<t;i++)if(s=n[i],i===t-1){if(s>=hf(256,5-t))return null}else if(s>255)return null;for(a=ff(n),i=0;i<n.length;i++)a+=n[i]*hf(256,3-i);return a}(e),null===t)return If;this.host=t}else this.host=e}else{if(_f(Uf,e))return If;for(t="",n=Xm(e),i=0;i<n.length;i++)t+=Xf(n[i],jf);this.host=t}},cannotHaveUsernamePasswordPort:function(){return null===this.host||""===this.host||this.cannotBeABaseURL||"file"===this.scheme},includesCredentials:function(){return""!==this.username||""!==this.password},isSpecial:function(){return Hm(Jf,this.scheme)},shortenPath:function(){var e=this.path,t=e.length;!t||"file"===this.scheme&&1===t&&zf(e[0],!0)||e.length--},serialize:function(){var e=this,t=e.scheme,n=e.username,i=e.password,r=e.host,o=e.port,s=e.path,a=e.query,c=e.fragment,d=t+":";return null!==r?(d+="//",e.includesCredentials()&&(d+=n+(i?":"+i:"")+"@"),d+=Bf(r),null!==o&&(d+=":"+o)):"file"===t&&(d+="//"),null===r&&!e.cannotBeABaseURL&&s.length>1&&""===s[0]&&(d+="/."),d+=e.cannotBeABaseURL?s[0]:s.length?"/"+Ef(s,"/"):"",null!==a&&(d+="?"+a),null!==c&&(d+="#"+c),d},setHref:function(e){var t=this.parse(e);if(t)throw new cf(t);this.searchParams.update()},getOrigin:function(){var e=this.scheme,t=this.port;if("blob"===e)try{return new Tg(this.path[0]).origin}catch(e){return"null"}return"file"!==e&&this.isSpecial()?e+"://"+Bf(this.host)+(null!==t?":"+t:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(e){this.parse(qm(e)+":",Qf)},getUsername:function(){return this.username},setUsername:function(e){var t=Xm(qm(e));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var n=0;n<t.length;n++)this.username+=Xf(t[n],Yf)}},getPassword:function(){return this.password},setPassword:function(e){var t=Xm(qm(e));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var n=0;n<t.length;n++)this.password+=Xf(t[n],Yf)}},getHost:function(){var e=this.host,t=this.port;return null===e?"":null===t?Bf(e):Bf(e)+":"+t},setHost:function(e){this.cannotBeABaseURL||this.parse(e,cg)},getHostname:function(){var e=this.host;return null===e?"":Bf(e)},setHostname:function(e){this.cannotBeABaseURL||this.parse(e,dg)},getPort:function(){var e=this.port;return null===e?"":qm(e)},setPort:function(e){this.cannotHaveUsernamePasswordPort()||(""===(e=qm(e))?this.port=null:this.parse(e,lg))},getPathname:function(){var e=this.path;return this.cannotBeABaseURL?e[0]:e.length?"/"+Ef(e,"/"):""},setPathname:function(e){this.cannotBeABaseURL||(this.path=[],this.parse(e,_g))},getSearch:function(){var e=this.query;return e?"?"+e:""},setSearch:function(e){""===(e=qm(e))?this.query=null:("?"===pf(e,0)&&(e=vf(e,1)),this.query="",this.parse(e,fg)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var e=this.fragment;return e?"#"+e:""},setHash:function(e){""!==(e=qm(e))?("#"===pf(e,0)&&(e=vf(e,1)),this.fragment="",this.parse(e,gg)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var Tg=function(e){var t=Km(this,Rg),n=$m(arguments.length,1)>1?arguments[1]:void 0,i=nf(t,new Sg(e,!1,n));Vm||(t.href=i.serialize(),t.origin=i.getOrigin(),t.protocol=i.getProtocol(),t.username=i.getUsername(),t.password=i.getPassword(),t.host=i.getHost(),t.hostname=i.getHostname(),t.port=i.getPort(),t.pathname=i.getPathname(),t.search=i.getSearch(),t.searchParams=i.getSearchParams(),t.hash=i.getHash())},Rg=Tg.prototype,vg=function(e,t){return{get:function(){return rf(this)[e]()},set:t&&function(e){return rf(this)[t](e)},configurable:!0,enumerable:!0}};if(Vm&&(Wm(Rg,"href",vg("serialize","setHref")),Wm(Rg,"origin",vg("getOrigin")),Wm(Rg,"protocol",vg("getProtocol","setProtocol")),Wm(Rg,"username",vg("getUsername","setUsername")),Wm(Rg,"password",vg("getPassword","setPassword")),Wm(Rg,"host",vg("getHost","setHost")),Wm(Rg,"hostname",vg("getHostname","setHostname")),Wm(Rg,"port",vg("getPort","setPort")),Wm(Rg,"pathname",vg("getPathname","setPathname")),Wm(Rg,"search",vg("getSearch","setSearch")),Wm(Rg,"searchParams",vg("getSearchParams")),Wm(Rg,"hash",vg("getHash","setHash"))),Gm(Rg,"toJSON",(function(){return rf(this).serialize()}),{enumerable:!0}),Gm(Rg,"toString",(function(){return rf(this).serialize()}),{enumerable:!0}),af){var yg=af.createObjectURL,Cg=af.revokeObjectURL;yg&&Gm(Tg,"createObjectURL",Bm(yg,af)),Cg&&Gm(Tg,"revokeObjectURL",Bm(Cg,af))}Qm(Tg,"URL"),Um({global:!0,constructor:!0,forced:!xm,sham:!Vm},{URL:Tg});var bg=Nn,Ig=i,Ag=ud,wg=Ri,Og=u_,Ng=re("URL"),Dg=Og&&Ig((function(){Ng.canParse()})),Pg=Ig((function(){return 1!==Ng.canParse.length}));bg({target:"URL",stat:!0,forced:!Dg||Pg},{canParse:function(e){var t=Ag(arguments.length,1),n=wg(e),i=t<2||void 0===arguments[1]?void 0:wg(arguments[1]);try{return!!new Ng(n,i)}catch(e){return!1}}});var Lg=Nn,kg=ud,Mg=Ri,Ug=u_,Vg=re("URL");Lg({target:"URL",stat:!0,forced:!Ug},{parse:function(e){var t=kg(arguments.length,1),n=Mg(e),i=t<2||void 0===arguments[1]?void 0:Mg(arguments[1]);try{return new Vg(n,i)}catch(e){return null}}});var xg=n($.URL);let Fg=!0,Bg=!0;function jg(e,t,n){const i=e.match(t);return i&&i.length>=n&&parseInt(i[n],10)}function Gg(e,t,n){if(!e.RTCPeerConnection)return;const i=e.RTCPeerConnection.prototype,r=i.addEventListener;i.addEventListener=function(e,i){if(e!==t)return r.apply(this,arguments);const o=e=>{const t=n(e);t&&(i.handleEvent?i.handleEvent(t):i(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(i,o),r.apply(this,[e,o])};const o=i.removeEventListener;i.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t])return o.apply(this,arguments);if(!this._eventMap[t].has(n))return o.apply(this,arguments);const i=this._eventMap[t].get(n);return this._eventMap[t].delete(n),0===this._eventMap[t].size&&delete this._eventMap[t],0===Object.keys(this._eventMap).length&&delete this._eventMap,o.apply(this,[e,i])},Object.defineProperty(i,"on"+t,{get(){return this["_on"+t]},set(e){this["_on"+t]&&(this.removeEventListener(t,this["_on"+t]),delete this["_on"+t]),e&&this.addEventListener(t,this["_on"+t]=e)},enumerable:!0,configurable:!0})}function Wg(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Fg=e,e?"adapter.js logging disabled":"adapter.js logging enabled")}function Kg(e){return"boolean"!=typeof e?new Error("Argument type: "+typeof e+". Please use a boolean."):(Bg=!e,"adapter.js deprecation warnings "+(e?"disabled":"enabled"))}function Hg(){if("object"==typeof window){if(Fg)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}}function Yg(e,t){Bg&&console.warn(e+" is deprecated, please use "+t+" instead.")}function Xg(e){return"[object Object]"===Object.prototype.toString.call(e)}function Jg(e){var t;return Xg(e)?sr(t=Object.keys(e)).call(t,(function(t,n){const i=Xg(e[n]),r=i?Jg(e[n]):e[n],o=i&&!Object.keys(r).length;return void 0===r||o?t:Object.assign(t,{[n]:r})}),{}):e}function zg(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach((i=>{i.endsWith("Id")?zg(e,e.get(t[i]),n):i.endsWith("Ids")&&t[i].forEach((t=>{zg(e,e.get(t),n)}))})))}function Zg(e,t,n){const i=n?"outbound-rtp":"inbound-rtp",r=new Map;if(null===t)return r;const o=[];return e.forEach((e=>{"track"===e.type&&e.trackIdentifier===t.id&&o.push(e)})),o.forEach((t=>{e.forEach((n=>{n.type===i&&n.trackId===t.id&&zg(e,n,r)}))})),r}const qg=Hg;function Qg(e,t){const n=e&&e.navigator;if(!n.mediaDevices)return;const i=function(e){if("object"!=typeof e||e.mandatory||e.optional)return e;const t={};return Object.keys(e).forEach((n=>{if("require"===n||"advanced"===n||"mediaSource"===n)return;const i="object"==typeof e[n]?e[n]:{ideal:e[n]};void 0!==i.exact&&"number"==typeof i.exact&&(i.min=i.max=i.exact);const r=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):"deviceId"===t?"sourceId":t};if(void 0!==i.ideal){t.optional=t.optional||[];let e={};"number"==typeof i.ideal?(e[r("min",n)]=i.ideal,t.optional.push(e),e={},e[r("max",n)]=i.ideal,t.optional.push(e)):(e[r("",n)]=i.ideal,t.optional.push(e))}void 0!==i.exact&&"number"!=typeof i.exact?(t.mandatory=t.mandatory||{},t.mandatory[r("",n)]=i.exact):["min","max"].forEach((e=>{void 0!==i[e]&&(t.mandatory=t.mandatory||{},t.mandatory[r(e,n)]=i[e])}))})),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},r=function(e,r){if(t.version>=61)return r(e);if((e=JSON.parse(JSON.stringify(e)))&&"object"==typeof e.audio){const t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};t((e=JSON.parse(JSON.stringify(e))).audio,"autoGainControl","googAutoGainControl"),t(e.audio,"noiseSuppression","googNoiseSuppression"),e.audio=i(e.audio)}if(e&&"object"==typeof e.video){let o=e.video.facingMode;o=o&&("object"==typeof o?o:{ideal:o});const s=t.version<66;if(o&&("user"===o.exact||"environment"===o.exact||"user"===o.ideal||"environment"===o.ideal)&&(!n.mediaDevices.getSupportedConstraints||!n.mediaDevices.getSupportedConstraints().facingMode||s)){let t;if(delete e.video.facingMode,"environment"===o.exact||"environment"===o.ideal?t=["back","rear"]:"user"!==o.exact&&"user"!==o.ideal||(t=["front"]),t)return n.mediaDevices.enumerateDevices().then((n=>{n=n.filter((e=>"videoinput"===e.kind));let s=n.find((e=>t.some((t=>{var n;return Ui(n=e.label.toLowerCase()).call(n,t)}))));return!s&&n.length&&Ui(t).call(t,"back")&&(s=n[n.length-1]),s&&(e.video.deviceId=o.exact?{exact:s.deviceId}:{ideal:s.deviceId}),e.video=i(e.video),qg("chrome: "+JSON.stringify(e)),r(e)}))}e.video=i(e.video)}return qg("chrome: "+JSON.stringify(e)),r(e)},o=function(e){return t.version>=64?e:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(n.getUserMedia=function(e,t,i){r(e,(e=>{n.webkitGetUserMedia(e,t,(e=>{i&&i(o(e))}))}))}.bind(n),n.mediaDevices.getUserMedia){const e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return r(t,(t=>e(t).then((e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach((e=>{e.stop()})),new DOMException("","NotFoundError");return e}),(e=>cp.reject(o(e))))))}}}function $g(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function eS(e){if("object"==typeof e&&e.RTCPeerConnection&&!("ontrack"in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=e)},enumerable:!0,configurable:!0});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener("addtrack",(n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.track.id)):{track:n.track};const r=new Event("track");r.track=n.track,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)})),t.stream.getTracks().forEach((n=>{let i;i=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find((e=>e.track&&e.track.id===n.id)):{track:n};const r=new Event("track");r.track=n,r.receiver=i,r.transceiver={receiver:i},r.streams=[t.stream],this.dispatchEvent(r)}))},this.addEventListener("addstream",this._ontrackpoly)),t.apply(this,arguments)}}else Gg(e,"track",(e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e)))}function tS(e){if("object"==typeof e&&e.RTCPeerConnection&&!("getSenders"in e.RTCPeerConnection.prototype)&&"createDTMFSender"in e.RTCPeerConnection.prototype){const t=function(e,t){return{track:t,get dtmf(){return void 0===this._dtmf&&("audio"===t.kind?this._dtmf=e.createDTMFSender(t):this._dtmf=null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,i){let r=n.apply(this,arguments);return r||(r=t(this,e),this._senders.push(r)),r};const i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){i.apply(this,arguments);const t=this._senders.indexOf(e);-1!==t&&this._senders.splice(t,1)}}const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach((e=>{this._senders.push(t(this,e))}))};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],i.apply(this,[e]),e.getTracks().forEach((e=>{const t=this._senders.find((t=>t.track===e));t&&this._senders.splice(this._senders.indexOf(t),1)}))}}else if("object"==typeof e&&e.RTCPeerConnection&&"getSenders"in e.RTCPeerConnection.prototype&&"createDTMFSender"in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!("dtmf"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return void 0===this._dtmf&&("audio"===this.track.kind?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function nS(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),n=e[0],i=e[1],r=e[2];if(arguments.length>0&&"function"==typeof n)return t.apply(this,arguments);if(0===t.length&&(0===arguments.length||"function"!=typeof n))return t.apply(this,[]);const o=function(e){const t={};return e.result().forEach((e=>{const n={id:e.id,timestamp:e.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[e.type]||e.type};e.names().forEach((t=>{n[t]=e.stat(t)})),t[n.id]=n})),t},s=function(e){return new Map(Object.keys(e).map((t=>[t,e[t]])))};if(arguments.length>=2){const e=function(e){i(s(o(e)))};return t.apply(this,[e,n])}return new cp(((e,n)=>{t.apply(this,[function(t){e(s(o(t)))},n])})).then(i,r)}}function iS(e){if(!("object"==typeof e&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!("getStats"in e.RTCRtpSender.prototype)){const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Zg(t,e.track,!0)))}}if(!("getStats"in e.RTCRtpReceiver.prototype)){const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Gg(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){const e=this;return this._pc.getStats().then((t=>Zg(t,e.track,!1)))}}if(!("getStats"in e.RTCRtpSender.prototype)||!("getStats"in e.RTCRtpReceiver.prototype))return;const t=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){const e=arguments[0];let t,n,i;return this.getSenders().forEach((n=>{n.track===e&&(t?i=!0:t=n)})),this.getReceivers().forEach((t=>(t.track===e&&(n?i=!0:n=t),t.track===e))),i||t&&n?cp.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):t?t.getStats():n?n.getStats():cp.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return t.apply(this,arguments)}}function rS(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map((e=>this._shimmedLocalStreams[e][0]))};const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const i=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?-1===this._shimmedLocalStreams[n.id].indexOf(i)&&this._shimmedLocalStreams[n.id].push(i):this._shimmedLocalStreams[n.id]=[n,i],i};const n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")}));const t=this.getSenders();n.apply(this,arguments);const i=this.getSenders().filter((e=>-1===t.indexOf(e)));this._shimmedLocalStreams[e.id]=[e].concat(i)};const i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],i.apply(this,arguments)};const r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach((t=>{const n=this._shimmedLocalStreams[t].indexOf(e);-1!==n&&this._shimmedLocalStreams[t].splice(n,1),1===this._shimmedLocalStreams[t].length&&delete this._shimmedLocalStreams[t]})),r.apply(this,arguments)}}function oS(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return rS(e);const n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){const e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map((e=>this._reverseStreams[e.id]))};const i=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach((e=>{const t=this.getSenders().find((t=>t.track===e));if(t)throw new DOMException("Track already exists.","InvalidAccessError")})),!this._reverseStreams[t.id]){const n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}i.apply(this,[t])};const r=e.RTCPeerConnection.prototype.removeStream;function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(r.id,"g"),i.id)})),new RTCSessionDescription({type:t.type,sdp:n})}e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const i=[].slice.call(arguments,1);if(1!==i.length||!i[0].getTracks().find((e=>e===t)))throw new DOMException("The adapter.js addTrack polyfill only supports a single  stream which is associated with the specified track.","NotSupportedError");const r=this.getSenders().find((e=>e.track===t));if(r)throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const o=this._streams[n.id];if(o)o.addTrack(t),cp.resolve().then((()=>{this.dispatchEvent(new Event("negotiationneeded"))}));else{const i=new e.MediaStream([t]);this._streams[n.id]=i,this._reverseStreams[i.id]=n,this.addStream(i)}return this.getSenders().find((e=>e.track===t))},["createOffer","createAnswer"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){const e=arguments;return arguments.length&&"function"==typeof arguments[0]?n.apply(this,[t=>{const n=o(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then((e=>o(this,e)))}};e.RTCPeerConnection.prototype[t]=i[t]}));const s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach((t=>{const i=e._reverseStreams[t],r=e._streams[i.id];n=n.replace(new RegExp(i.id,"g"),r.id)})),new RTCSessionDescription({type:t.type,sdp:n})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){const e=a.get.apply(this);return""===e.type?e:o(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if("closed"===this.signalingState)throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!e._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(!(e._pc===this))throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let t;this._streams=this._streams||{},Object.keys(this._streams).forEach((n=>{this._streams[n].getTracks().find((t=>e.track===t))&&(t=this._streams[n])})),t&&(1===t.getTracks().length?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event("negotiationneeded")))}}function sS(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}))}function aS(e,t){Gg(e,"negotiationneeded",(e=>{const n=e.target;if(!(t.version<72||n.getConfiguration&&"plan-b"===n.getConfiguration().sdpSemantics)||"stable"===n.signalingState)return e}))}var cS=Object.freeze({__proto__:null,fixNegotiationNeeded:aS,shimAddTrackRemoveTrack:oS,shimAddTrackRemoveTrackWithNative:rS,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&("function"==typeof t?e.navigator.mediaDevices.getDisplayMedia=function(n){return t(n).then((t=>{const i=n.video&&n.video.width,r=n.video&&n.video.height,o=n.video&&n.video.frameRate;return n.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxFrameRate:o||3}},i&&(n.video.mandatory.maxWidth=i),r&&(n.video.mandatory.maxHeight=r),e.navigator.mediaDevices.getUserMedia(n)}))}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:tS,shimGetStats:nS,shimGetUserMedia:Qg,shimMediaStream:$g,shimOnTrack:eS,shimPeerConnection:sS,shimSenderReceiverGetStats:iS});function dS(e,t){const n=e&&e.navigator,i=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,i){Yg("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),n.mediaDevices.getUserMedia(e).then(t,i)},!(t.version>55&&"autoGainControl"in n.mediaDevices.getSupportedConstraints())){const e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return"object"==typeof n&&"object"==typeof n.audio&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,"autoGainControl","mozAutoGainControl"),e(n.audio,"noiseSuppression","mozNoiseSuppression")),t(n)},i&&i.prototype.getSettings){const t=i.prototype.getSettings;i.prototype.getSettings=function(){const n=t.apply(this,arguments);return e(n,"mozAutoGainControl","autoGainControl"),e(n,"mozNoiseSuppression","noiseSuppression"),n}}if(i&&i.prototype.applyConstraints){const t=i.prototype.applyConstraints;i.prototype.applyConstraints=function(n){return"audio"===this.kind&&"object"==typeof n&&(n=JSON.parse(JSON.stringify(n)),e(n,"autoGainControl","mozAutoGainControl"),e(n,"noiseSuppression","mozNoiseSuppression")),t.apply(this,[n])}}}}function lS(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function uS(e,t){if("object"!=typeof e||!e.RTCPeerConnection&&!e.mozRTCPeerConnection)return;!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach((function(t){const n=e.RTCPeerConnection.prototype[t],i={[t](){return arguments[0]=new("addIceCandidate"===t?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=i[t]}));const n={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},i=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){const e=Array.prototype.slice.call(arguments),r=e[0],o=e[1],s=e[2];return i.apply(this,[r||null]).then((e=>{if(t.version<53&&!o)try{e.forEach((e=>{e.type=n[e.type]||e.type}))}catch(t){if("TypeError"!==t.name)throw t;e.forEach(((t,i)=>{e.set(i,Object.assign({},t,{type:n[t.type]||t.type}))}))}return e})).then(o,s)}}function hS(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpSender.prototype)return;const t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e});const n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){const e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):cp.resolve(new Map)}}function pS(e){if("object"!=typeof e||!e.RTCPeerConnection||!e.RTCRtpSender)return;if(e.RTCRtpSender&&"getStats"in e.RTCRtpReceiver.prototype)return;const t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){const e=t.apply(this,[]);return e.forEach((e=>e._pc=this)),e}),Gg(e,"track",(e=>(e.receiver._pc=e.srcElement,e))),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function _S(e){e.RTCPeerConnection&&!("removeStream"in e.RTCPeerConnection.prototype)&&(e.RTCPeerConnection.prototype.removeStream=function(e){Yg("removeStream","removeTrack"),this.getSenders().forEach((t=>{var n;t.track&&Ui(n=e.getTracks()).call(n,t.track)&&this.removeTrack(t)}))})}function ES(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function mS(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.addTransceiver;t&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;void 0===e&&(e=[]),e=[...e];const n=e.length>0;n&&e.forEach((e=>{if("rid"in e){if(!/^[a-z0-9]{0,16}$/i.test(e.rid))throw new TypeError("Invalid RID value provided.")}if("scaleResolutionDownBy"in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in e&&!(parseFloat(e.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")}));const i=t.apply(this,arguments);if(n){const t=i.sender,n=t.getParameters();(!("encodings"in n)||1===n.encodings.length&&0===Object.keys(n.encodings[0]).length)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then((()=>{delete t.sendEncodings})).catch((()=>{delete t.sendEncodings}))))}return i})}function fS(e){if("object"!=typeof e||!e.RTCRtpSender)return;const t=e.RTCRtpSender.prototype.getParameters;t&&(e.RTCRtpSender.prototype.getParameters=function(){const e=t.apply(this,arguments);return"encodings"in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function gS(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?cp.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}function SS(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?cp.all(this.setParametersPromises).then((()=>t.apply(this,arguments))).finally((()=>{this.setParametersPromises=[]})):t.apply(this,arguments)}}var TS=Object.freeze({__proto__:null,shimAddTransceiver:mS,shimCreateAnswer:SS,shimCreateOffer:gS,shimGetDisplayMedia:function(e,t){e.navigator.mediaDevices&&"getDisplayMedia"in e.navigator.mediaDevices||e.navigator.mediaDevices&&(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!n||!n.video){const e=new DOMException("getDisplayMedia without video constraints is undefined");return e.name="NotFoundError",e.code=8,cp.reject(e)}return!0===n.video?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)})},shimGetParameters:fS,shimGetUserMedia:dS,shimOnTrack:lS,shimPeerConnection:uS,shimRTCDataChannel:ES,shimReceiverGetStats:pS,shimRemoveStream:_S,shimSenderGetStats:hS});function RS(e){if("object"==typeof e&&e.RTCPeerConnection){if("getLocalStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in e.RTCPeerConnection.prototype)){const t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){var n;this._localStreams||(this._localStreams=[]),Ui(n=this._localStreams).call(n,e)||this._localStreams.push(e),e.getAudioTracks().forEach((n=>t.call(this,n,e))),e.getVideoTracks().forEach((n=>t.call(this,n,e)))},e.RTCPeerConnection.prototype.addTrack=function(e){for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i&&i.forEach((e=>{var t;this._localStreams?Ui(t=this._localStreams).call(t,e)||this._localStreams.push(e):this._localStreams=[e]})),t.apply(this,arguments)}}"removeStream"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const t=this._localStreams.indexOf(e);if(-1===t)return;this._localStreams.splice(t,1);const n=e.getTracks();this.getSenders().forEach((e=>{Ui(n).call(n,e.track)&&this.removeTrack(e)}))})}}function vS(e){if("object"==typeof e&&e.RTCPeerConnection&&("getRemoteStreams"in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=e),this.addEventListener("track",this._onaddstreampoly=e=>{e.streams.forEach((e=>{var t;if(this._remoteStreams||(this._remoteStreams=[]),Ui(t=this._remoteStreams).call(t,e))return;this._remoteStreams.push(e);const n=new Event("addstream");n.stream=e,this.dispatchEvent(n)}))})}});const t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){const e=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(t){t.streams.forEach((t=>{if(e._remoteStreams||(e._remoteStreams=[]),e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);const n=new Event("addstream");n.stream=t,e.dispatchEvent(n)}))}),t.apply(e,arguments)}}}function yS(e){if("object"!=typeof e||!e.RTCPeerConnection)return;const t=e.RTCPeerConnection.prototype,n=t.createOffer,i=t.createAnswer,r=t.setLocalDescription,o=t.setRemoteDescription,s=t.addIceCandidate;t.createOffer=function(e,t){const i=arguments.length>=2?arguments[2]:arguments[0],r=n.apply(this,[i]);return t?(r.then(e,t),cp.resolve()):r},t.createAnswer=function(e,t){const n=arguments.length>=2?arguments[2]:arguments[0],r=i.apply(this,[n]);return t?(r.then(e,t),cp.resolve()):r};let a=function(e,t,n){const i=r.apply(this,[e]);return n?(i.then(t,n),cp.resolve()):i};t.setLocalDescription=a,a=function(e,t,n){const i=o.apply(this,[e]);return n?(i.then(t,n),cp.resolve()):i},t.setRemoteDescription=a,a=function(e,t,n){const i=s.apply(this,[e]);return n?(i.then(t,n),cp.resolve()):i},t.addIceCandidate=a}function CS(e){const t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){const e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(bS(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,i){t.mediaDevices.getUserMedia(e).then(n,i)}.bind(t))}function bS(e){return e&&void 0!==e.video?Object.assign({},e,{video:Jg(e.video)}):e}function IS(e){if(!e.RTCPeerConnection)return;const t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){const t=[];for(let n=0;n<e.iceServers.length;n++){let i=e.iceServers[n];!i.hasOwnProperty("urls")&&i.hasOwnProperty("url")?(Yg("RTCIceServer.url","RTCIceServer.urls"),i=JSON.parse(JSON.stringify(i)),i.urls=i.url,delete i.url,t.push(i)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,"generateCertificate"in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get:()=>t.generateCertificate})}function AS(e){"object"==typeof e&&e.RTCTrackEvent&&"receiver"in e.RTCTrackEvent.prototype&&!("transceiver"in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function wS(e){const t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){void 0!==e.offerToReceiveAudio&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);const t=this.getTransceivers().find((e=>"audio"===e.receiver.track.kind));!1===e.offerToReceiveAudio&&t?"sendrecv"===t.direction?t.setDirection?t.setDirection("sendonly"):t.direction="sendonly":"recvonly"===t.direction&&(t.setDirection?t.setDirection("inactive"):t.direction="inactive"):!0!==e.offerToReceiveAudio||t||this.addTransceiver("audio",{direction:"recvonly"}),void 0!==e.offerToReceiveVideo&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);const n=this.getTransceivers().find((e=>"video"===e.receiver.track.kind));!1===e.offerToReceiveVideo&&n?"sendrecv"===n.direction?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":"recvonly"===n.direction&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):!0!==e.offerToReceiveVideo||n||this.addTransceiver("video",{direction:"recvonly"})}return t.apply(this,arguments)}}function OS(e){"object"!=typeof e||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var NS=Object.freeze({__proto__:null,shimAudioContext:OS,shimCallbacksAPI:yS,shimConstraints:bS,shimCreateOfferLegacy:wS,shimGetUserMedia:CS,shimLocalStreamsAPI:RS,shimRTCIceServerUrls:IS,shimRemoteStreamsAPI:vS,shimTrackEventTransceiver:AS}),DS="\t\n\v\f\r                 \u2028\u2029\ufeff",PS=X,LS=Ri,kS=DS,MS=d("".replace),US=RegExp("^["+kS+"]+"),VS=RegExp("(^|[^"+kS+"])["+kS+"]+$"),xS=function(e){return function(t){var n=LS(PS(t));return 1&e&&(n=MS(n,US,"")),2&e&&(n=MS(n,VS,"$1")),n}},FS={start:xS(1),end:xS(2),trim:xS(3)},BS=Ca.PROPER,jS=i,GS=DS,WS=FS.trim;Nn({target:"String",proto:!0,forced:function(e){return jS((function(){return!!GS[e]()||"​…᠎"!=="​…᠎"[e]()||BS&&GS[e].name!==e}))}("trim")},{trim:function(){return WS(this)}});var KS=ni("String","trim"),HS=l,YS=KS,XS=String.prototype,JS=function(e){var t=e.trim;return"string"==typeof e||e===XS||HS(XS,e)&&t===XS.trim?YS:t},zS=n(JS),ZS={exports:{}};!function(e){const t={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split("\n").map((e=>e.trim()))},t.splitSections=function(e){return e.split("\nm=").map(((e,t)=>(t>0?"m="+e:e).trim()+"\r\n"))},t.getDescription=function(e){const n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){const n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter((e=>0===e.indexOf(n)))},t.parseCandidate=function(e){let t;t=0===e.indexOf("a=candidate:")?e.substring(12).split(" "):e.substring(10).split(" ");const n={foundation:t[0],component:{1:"rtp",2:"rtcp"}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case"raddr":n.relatedAddress=t[e+1];break;case"rport":n.relatedPort=parseInt(t[e+1],10);break;case"tcptype":n.tcpType=t[e+1];break;case"ufrag":n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:void 0===n[t[e]]&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){const t=[];t.push(e.foundation);const n=e.component;"rtp"===n?t.push(1):"rtcp"===n?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);const i=e.type;return t.push("typ"),t.push(i),"host"!==i&&e.relatedAddress&&void 0!==e.relatedPort&&(t.push("raddr"),t.push(e.relatedAddress),t.push("rport"),t.push(e.relatedPort)),e.tcpType&&"tcp"===e.protocol.toLowerCase()&&(t.push("tcptype"),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push("ufrag"),t.push(e.usernameFragment||e.ufrag)),"candidate:"+t.join(" ")},t.parseIceOptions=function(e){return e.substring(14).split(" ")},t.parseRtpMap=function(e){let t=e.substring(9).split(" ");const n={payloadType:parseInt(t.shift(),10)};return t=t[0].split("/"),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=3===t.length?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;void 0!==e.preferredPayloadType&&(t=e.preferredPayloadType);const n=e.channels||e.numChannels||1;return"a=rtpmap:"+t+" "+e.name+"/"+e.clockRate+(1!==n?"/"+n:"")+"\r\n"},t.parseExtmap=function(e){const t=e.substring(9).split(" ");return{id:parseInt(t[0],10),direction:t[0].indexOf("/")>0?t[0].split("/")[1]:"sendrecv",uri:t[1],attributes:t.slice(2).join(" ")}},t.writeExtmap=function(e){return"a=extmap:"+(e.id||e.preferredId)+(e.direction&&"sendrecv"!==e.direction?"/"+e.direction:"")+" "+e.uri+(e.attributes?" "+e.attributes:"")+"\r\n"},t.parseFmtp=function(e){const t={};let n;const i=e.substring(e.indexOf(" ")+1).split(";");for(let e=0;e<i.length;e++)n=i[e].trim().split("="),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t="",n=e.payloadType;if(void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){const i=[];Object.keys(e.parameters).forEach((t=>{void 0!==e.parameters[t]?i.push(t+"="+e.parameters[t]):i.push(t)})),t+="a=fmtp:"+n+" "+i.join(";")+"\r\n"}return t},t.parseRtcpFb=function(e){const t=e.substring(e.indexOf(" ")+1).split(" ");return{type:t.shift(),parameter:t.join(" ")}},t.writeRtcpFb=function(e){let t="",n=e.payloadType;return void 0!==e.preferredPayloadType&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach((e=>{t+="a=rtcp-fb:"+n+" "+e.type+(e.parameter&&e.parameter.length?" "+e.parameter:"")+"\r\n"})),t},t.parseSsrcMedia=function(e){const t=e.indexOf(" "),n={ssrc:parseInt(e.substring(7,t),10)},i=e.indexOf(":",t);return i>-1?(n.attribute=e.substring(t+1,i),n.value=e.substring(i+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){const t=e.substring(13).split(" ");return{semantics:t.shift(),ssrcs:t.map((e=>parseInt(e,10)))}},t.getMid=function(e){const n=t.matchPrefix(e,"a=mid:")[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){const t=e.substring(14).split(" ");return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:"auto",fingerprints:t.matchPrefix(e+n,"a=fingerprint:").map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n="a=setup:"+t+"\r\n";return e.fingerprints.forEach((e=>{n+="a=fingerprint:"+e.algorithm+" "+e.value+"\r\n"})),n},t.parseCryptoLine=function(e){const t=e.substring(9).split(" ");return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return"a=crypto:"+e.tag+" "+e.cryptoSuite+" "+("object"==typeof e.keyParams?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?" "+e.sessionParams.join(" "):"")+"\r\n"},t.parseCryptoKeyParams=function(e){if(0!==e.indexOf("inline:"))return null;const t=e.substring(7).split("|");return{keyMethod:"inline",keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(":")[0]:void 0,mkiLength:t[2]?t[2].split(":")[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+":"+e.keySalt+(e.lifeTime?"|"+e.lifeTime:"")+(e.mkiValue&&e.mkiLength?"|"+e.mkiValue+":"+e.mkiLength:"")},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,"a=crypto:").map(t.parseCryptoLine)},t.getIceParameters=function(e,n){const i=t.matchPrefix(e+n,"a=ice-ufrag:")[0],r=t.matchPrefix(e+n,"a=ice-pwd:")[0];return i&&r?{usernameFragment:i.substring(12),password:r.substring(10)}:null},t.writeIceParameters=function(e){let t="a=ice-ufrag:"+e.usernameFragment+"\r\na=ice-pwd:"+e.password+"\r\n";return e.iceLite&&(t+="a=ice-lite\r\n"),t},t.parseRtpParameters=function(e){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},i=t.splitLines(e)[0].split(" ");n.profile=i[2];for(let r=3;r<i.length;r++){const o=i[r],s=t.matchPrefix(e,"a=rtpmap:"+o+" ")[0];if(s){const i=t.parseRtpMap(s),r=t.matchPrefix(e,"a=fmtp:"+o+" ");switch(i.parameters=r.length?t.parseFmtp(r[0]):{},i.rtcpFeedback=t.matchPrefix(e,"a=rtcp-fb:"+o+" ").map(t.parseRtcpFb),n.codecs.push(i),i.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(i.name.toUpperCase())}}}t.matchPrefix(e,"a=extmap:").forEach((e=>{n.headerExtensions.push(t.parseExtmap(e))}));const r=t.matchPrefix(e,"a=rtcp-fb:* ").map(t.parseRtcpFb);return n.codecs.forEach((e=>{r.forEach((t=>{e.rtcpFeedback.find((e=>e.type===t.type&&e.parameter===t.parameter))||e.rtcpFeedback.push(t)}))})),n},t.writeRtpDescription=function(e,n){let i="";i+="m="+e+" ",i+=n.codecs.length>0?"9":"0",i+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",i+=n.codecs.map((e=>void 0!==e.preferredPayloadType?e.preferredPayloadType:e.payloadType)).join(" ")+"\r\n",i+="c=IN IP4 0.0.0.0\r\n",i+="a=rtcp:9 IN IP4 0.0.0.0\r\n",n.codecs.forEach((e=>{i+=t.writeRtpMap(e),i+=t.writeFmtp(e),i+=t.writeRtcpFb(e)}));let r=0;return n.codecs.forEach((e=>{e.maxptime>r&&(r=e.maxptime)})),r>0&&(i+="a=maxptime:"+r+"\r\n"),n.headerExtensions&&n.headerExtensions.forEach((e=>{i+=t.writeExtmap(e)})),i},t.parseRtpEncodingParameters=function(e){const n=[],i=t.parseRtpParameters(e),r=-1!==i.fecMechanisms.indexOf("RED"),o=-1!==i.fecMechanisms.indexOf("ULPFEC"),s=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute)),a=s.length>0&&s[0].ssrc;let c;const d=t.matchPrefix(e,"a=ssrc-group:FID").map((e=>e.substring(17).split(" ").map((e=>parseInt(e,10)))));d.length>0&&d[0].length>1&&d[0][0]===a&&(c=d[0][1]),i.codecs.forEach((e=>{if("RTX"===e.name.toUpperCase()&&e.parameters.apt){let t={ssrc:a,codecPayloadType:parseInt(e.parameters.apt,10)};a&&c&&(t.rtx={ssrc:c}),n.push(t),r&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:a,mechanism:o?"red+ulpfec":"red"},n.push(t))}})),0===n.length&&a&&n.push({ssrc:a});let l=t.matchPrefix(e,"b=");return l.length&&(l=0===l[0].indexOf("b=TIAS:")?parseInt(l[0].substring(7),10):0===l[0].indexOf("b=AS:")?1e3*parseInt(l[0].substring(5),10)*.95-16e3:void 0,n.forEach((e=>{e.maxBitrate=l}))),n},t.parseRtcpParameters=function(e){const n={},i=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"cname"===e.attribute))[0];i&&(n.cname=i.value,n.ssrc=i.ssrc);const r=t.matchPrefix(e,"a=rtcp-rsize");n.reducedSize=r.length>0,n.compound=0===r.length;const o=t.matchPrefix(e,"a=rtcp-mux");return n.mux=o.length>0,n},t.writeRtcpParameters=function(e){let t="";return e.reducedSize&&(t+="a=rtcp-rsize\r\n"),e.mux&&(t+="a=rtcp-mux\r\n"),void 0!==e.ssrc&&e.cname&&(t+="a=ssrc:"+e.ssrc+" cname:"+e.cname+"\r\n"),t},t.parseMsid=function(e){let n;const i=t.matchPrefix(e,"a=msid:");if(1===i.length)return n=i[0].substring(7).split(" "),{stream:n[0],track:n[1]};const r=t.matchPrefix(e,"a=ssrc:").map((e=>t.parseSsrcMedia(e))).filter((e=>"msid"===e.attribute));return r.length>0?(n=r[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},t.parseSctpDescription=function(e){const n=t.parseMLine(e),i=t.matchPrefix(e,"a=max-message-size:");let r;i.length>0&&(r=parseInt(i[0].substring(19),10)),isNaN(r)&&(r=65536);const o=t.matchPrefix(e,"a=sctp-port:");if(o.length>0)return{port:parseInt(o[0].substring(12),10),protocol:n.fmt,maxMessageSize:r};const s=t.matchPrefix(e,"a=sctpmap:");if(s.length>0){const e=s[0].substring(10).split(" ");return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:r}}},t.writeSctpDescription=function(e,t){let n=[];return n="DTLS/SCTP"!==e.protocol?["m="+e.kind+" 9 "+e.protocol+" "+t.protocol+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctp-port:"+t.port+"\r\n"]:["m="+e.kind+" 9 "+e.protocol+" "+t.port+"\r\n","c=IN IP4 0.0.0.0\r\n","a=sctpmap:"+t.port+" "+t.protocol+" 65535\r\n"],void 0!==t.maxMessageSize&&n.push("a=max-message-size:"+t.maxMessageSize+"\r\n"),n.join("")},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,i){let r;const o=void 0!==n?n:2;r=e||t.generateSessionId();return"v=0\r\no="+(i||"thisisadapterortc")+" "+r+" "+o+" IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n"},t.getDirection=function(e,n){const i=t.splitLines(e);for(let e=0;e<i.length;e++)switch(i[e]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return i[e].substring(2)}return n?t.getDirection(n):"sendrecv"},t.getKind=function(e){return t.splitLines(e)[0].split(" ")[0].substring(2)},t.isRejected=function(e){return"0"===e.split(" ",2)[1]},t.parseMLine=function(e){const n=t.splitLines(e)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},t.parseOLine=function(e){const n=t.matchPrefix(e,"o=")[0].substring(2).split(" ");return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if("string"!=typeof e||0===e.length)return!1;const n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||"="!==n[e].charAt(1))return!1;return!0},e.exports=t}(ZS);var qS=ZS.exports,QS=n(qS),$S=e({__proto__:null,default:QS},[qS]);function eT(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&"foundation"in e.RTCIceCandidate.prototype)return;const t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if("object"==typeof e&&e.candidate&&0===e.candidate.indexOf("a=")&&((e=JSON.parse(JSON.stringify(e))).candidate=e.candidate.substr(2)),e.candidate&&e.candidate.length){const n=new t(e),i=QS.parseCandidate(e.candidate),r=Object.assign(n,i);return r.toJSON=function(){return{candidate:r.candidate,sdpMid:r.sdpMid,sdpMLineIndex:r.sdpMLineIndex,usernameFragment:r.usernameFragment}},r}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,Gg(e,"icecandidate",(t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:"false"}),t)))}function tT(e){!e.RTCIceCandidate||e.RTCIceCandidate&&"relayProtocol"in e.RTCIceCandidate.prototype||Gg(e,"icecandidate",(e=>{if(e.candidate){const t=QS.parseCandidate(e.candidate.candidate);"relay"===t.type&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[t.priority>>24])}return e}))}function nT(e,t){if(!e.RTCPeerConnection)return;"sctp"in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return void 0===this._sctp?null:this._sctp}});const n=function(e){if(!e||!e.sdp)return!1;const t=QS.splitSections(e.sdp);return t.shift(),t.some((e=>{const t=QS.parseMLine(e);return t&&"application"===t.kind&&-1!==t.protocol.indexOf("SCTP")}))},i=function(e){const t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(null===t||t.length<2)return-1;const n=parseInt(t[1],10);return n!=n?-1:n},r=function(e){let n=65536;return"firefox"===t.browser&&(n=t.version<57?-1===e?16384:2147483637:t.version<60?57===t.version?65535:65536:2147483637),n},o=function(e,n){let i=65536;"firefox"===t.browser&&57===t.version&&(i=65535);const r=QS.matchPrefix(e.sdp,"a=max-message-size:");return r.length>0?i=parseInt(r[0].substr(19),10):"firefox"===t.browser&&-1!==n&&(i=2147483637),i},s=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,"chrome"===t.browser&&t.version>=76){"plan-b"===this.getConfiguration().sdpSemantics&&Object.defineProperty(this,"sctp",{get(){return void 0===this._sctp?null:this._sctp},enumerable:!0,configurable:!0})}if(n(arguments[0])){const e=i(arguments[0]),t=r(e),n=o(arguments[0],e);let s;s=0===t&&0===n?Number.POSITIVE_INFINITY:0===t||0===n?Math.max(t,n):Math.min(t,n);const a={};Object.defineProperty(a,"maxMessageSize",{get:()=>s}),this._sctp=a}return s.apply(this,arguments)}}function iT(e){if(!e.RTCPeerConnection||!("createDataChannel"in e.RTCPeerConnection.prototype))return;function t(e,t){const n=e.send;e.send=function(){const i=arguments[0],r=i.length||i.size||i.byteLength;if("open"===e.readyState&&t.sctp&&r>t.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+t.sctp.maxMessageSize+" bytes)");return n.apply(e,arguments)}}const n=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){const e=n.apply(this,arguments);return t(e,this),e},Gg(e,"datachannel",(e=>(t(e.channel,e.target),e)))}function rT(e){if(!e.RTCPeerConnection||"connectionState"in e.RTCPeerConnection.prototype)return;const t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach((e=>{const n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{const t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;const n=new Event("connectionstatechange",e);t.dispatchEvent(n)}return e},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}}))}function oT(e,t){if(!e.RTCPeerConnection)return;if("chrome"===t.browser&&t.version>=71)return;if("safari"===t.browser&&t.version>=605)return;const n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&-1!==t.sdp.indexOf("\na=extmap-allow-mixed")){const n=t.sdp.split("\n").filter((e=>"a=extmap-allow-mixed"!==zS(e).call(e))).join("\n");e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function sT(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.addIceCandidate;n&&0!==n.length&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?("chrome"===t.browser&&t.version<78||"firefox"===t.browser&&t.version<68||"safari"===t.browser)&&arguments[0]&&""===arguments[0].candidate?cp.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),cp.resolve())})}function aT(e,t){if(!e.RTCPeerConnection||!e.RTCPeerConnection.prototype)return;const n=e.RTCPeerConnection.prototype.setLocalDescription;n&&0!==n.length&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if("object"!=typeof e||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":e.type="offer";break;default:e.type="answer"}if(e.sdp||"offer"!==e.type&&"answer"!==e.type)return n.apply(this,[e]);return("offer"===e.type?this.createOffer:this.createAnswer).apply(this).then((e=>n.apply(this,[e])))})}var cT=Object.freeze({__proto__:null,removeExtmapAllowMixed:oT,shimAddIceCandidateNullOrEmpty:sT,shimConnectionState:rT,shimMaxMessageSize:nT,shimParameterlessSetLocalDescription:aT,shimRTCIceCandidate:eT,shimRTCIceCandidateRelayProtocol:tT,shimSendThrowTypeError:iT});!function(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).window,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const n=Hg,i=function(e){const t={browser:null,version:null};if(void 0===e||!e.navigator)return t.browser="Not a browser.",t;const n=e.navigator;if(n.mozGetUserMedia)t.browser="firefox",t.version=jg(n.userAgent,/Firefox\/(\d+)\./,1);else if(n.webkitGetUserMedia||!1===e.isSecureContext&&e.webkitRTCPeerConnection)t.browser="chrome",t.version=jg(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!e.RTCPeerConnection||!n.userAgent.match(/AppleWebKit\/(\d+)\./))return t.browser="Not a supported browser.",t;t.browser="safari",t.version=jg(n.userAgent,/AppleWebKit\/(\d+)\./,1),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&"currentDirection"in e.RTCRtpTransceiver.prototype}return t}(e),r={browserDetails:i,commonShim:cT,extractVersion:jg,disableLog:Wg,disableWarnings:Kg,sdp:$S};switch(i.browser){case"chrome":if(!cS||!sS||!t.shimChrome)return n("Chrome shim is not included in this adapter release."),r;if(null===i.version)return n("Chrome shim can not determine version, not shimming."),r;n("adapter.js shimming chrome."),r.browserShim=cS,sT(e,i),aT(e),Qg(e,i),$g(e),sS(e,i),eS(e),oS(e,i),tS(e),nS(e),iS(e),aS(e,i),eT(e),tT(e),rT(e),nT(e,i),iT(e),oT(e,i);break;case"firefox":if(!TS||!uS||!t.shimFirefox)return n("Firefox shim is not included in this adapter release."),r;n("adapter.js shimming firefox."),r.browserShim=TS,sT(e,i),aT(e),dS(e,i),uS(e,i),lS(e),_S(e),hS(e),pS(e),ES(e),mS(e),fS(e),gS(e),SS(e),eT(e),rT(e),nT(e,i),iT(e);break;case"safari":if(!NS||!t.shimSafari)return n("Safari shim is not included in this adapter release."),r;n("adapter.js shimming safari."),r.browserShim=NS,sT(e,i),aT(e),IS(e),wS(e),yS(e),RS(e),vS(e),AS(e),CS(e),OS(e),eT(e),tT(e),nT(e,i),iT(e),oT(e,i);break;default:n("Unsupported browser!")}}({window:"undefined"==typeof window?void 0:window}),Nn({target:"Array",stat:!0},{isArray:cr});var dT=n($.Array.isArray);var lT=TypeError,uT=function(e){if(e>9007199254740991)throw new lT("Maximum allowed index exceeded");return e},hT=cr,pT=ed,_T=Q,ET=pt("species"),mT=Array,fT=function(e){var t;return hT(e)&&(t=e.constructor,(pT(t)&&(t===mT||hT(t.prototype))||_T(t)&&null===(t=t[ET]))&&(t=void 0)),void 0===t?mT:t},gT=function(e,t){return new(fT(e))(0===t?0:t)},ST=i,TT=_e,RT=pt("species"),vT=function(e){return TT>=51||!ST((function(){var t=[];return(t.constructor={})[RT]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},yT=Nn,CT=i,bT=cr,IT=Q,AT=Ze,wT=Wn,OT=uT,NT=QE,DT=im,PT=gT,LT=vT,kT=_e,MT=pt("isConcatSpreadable"),UT=kT>=51||!CT((function(){var e=[];return e[MT]=!1,e.concat()[0]!==e})),VT=function(e){if(!IT(e))return!1;var t=e[MT];return void 0!==t?!!t:bT(e)};yT({target:"Array",proto:!0,arity:1,forced:!UT||!LT("concat")},{concat:function(e){var t,n,i,r,o,s=AT(this),a=PT(s,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if(VT(o=-1===t?s:arguments[t]))for(r=wT(o),OT(c+r),n=0;n<r;n++,c++)n in o&&NT(a,c,o[n]);else OT(c+1),NT(a,c++,o);return DT(a,c),a}});var xT={},FT=R,BT=Z,jT=Wr.f,GT=dd,WT="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];xT.f=function(e){return WT&&"Window"===FT(e)?function(e){try{return jT(e)}catch(e){return GT(WT)}}(e):jT(BT(e))};var KT={},HT=pt;KT.f=HT;var YT=$,XT=$e,JT=KT,zT=Qt.f,ZT=function(e){var t=YT.Symbol||(YT.Symbol={});XT(t,e)||zT(t,e,{value:JT.f(e)})},qT=D,QT=re,$T=pt,eR=Ia,tR=function(){var e=QT("Symbol"),t=e&&e.prototype,n=t&&t.valueOf,i=$T("toPrimitive");t&&!t[i]&&eR(t,i,(function(e){return qT(n,this)}),{arity:1})},nR=qt,iR=W,rR=Ze,oR=Wn,sR=gT,aR=QE,cR=function(e){var t=1===e,n=2===e,i=3===e,r=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,d,l){for(var u,h,p=rR(c),_=iR(p),E=oR(_),m=nR(d,l),f=0,g=0,S=t?sR(c,E):n||s?sR(c,0):void 0;E>f;f++)if((a||f in _)&&(h=m(u=_[f],f,p),e))if(t)aR(S,f,h);else if(h)switch(e){case 3:return!0;case 5:return u;case 6:return f;case 2:aR(S,g++,u)}else switch(e){case 4:return!1;case 7:aR(S,g++,u)}return o?-1:i||r?r:S}},dR={forEach:cR(0),map:cR(1),filter:cR(2),some:cR(3),every:cR(4),find:cR(5),findIndex:cR(6),filterReject:cR(7)},lR=Nn,uR=h,hR=D,pR=d,_R=w,ER=ge,mR=i,fR=$e,gR=l,SR=rn,TR=Z,RR=yt,vR=Ri,yR=x,CR=Vo,bR=Eo,IR=Wr,AR=xT,wR=eo,OR=A,NR=Qt,DR=ho,PR=P,LR=Ia,kR=Ic,MR=Xe,UR=Kr,VR=rt,xR=pt,FR=KT,BR=ZT,jR=tR,GR=Ha,WR=ga,KR=dR.forEach,HR=vr("hidden"),YR="Symbol",XR="prototype",JR=WR.set,zR=WR.getterFor(YR),ZR=Object[XR],qR=uR.Symbol,QR=qR&&qR[XR],$R=uR.RangeError,ev=uR.TypeError,tv=uR.QObject,nv=OR.f,iv=NR.f,rv=AR.f,ov=PR.f,sv=pR([].push),av=MR("symbols"),cv=MR("op-symbols"),dv=MR("wks"),lv=!tv||!tv[XR]||!tv[XR].findChild,uv=function(e,t,n){var i=nv(ZR,t);return i&&delete ZR[t],iv(e,t,n),i&&e!==ZR&&iv(ZR,t,i),e},hv=_R&&mR((function(){return 7!==CR(iv({},"a",{get:function(){return iv(this,"a",{value:7}).a}})).a}))?uv:iv,pv=function(e,t){var n=av[e]=CR(QR);return JR(n,{type:YR,tag:e,description:t}),_R||(n.description=t),n},_v=function(e,t,n){e===ZR&&_v(cv,t,n),SR(e);var i=RR(t);return SR(n),fR(av,i)?(("enumerable"in n?!n.enumerable:!fR(e,i)||fR(e,HR)&&e[HR][i])?(fR(e,HR)||iv(e,HR,yR(1,CR(null))),e[HR][i]=!0):(fR(e,HR)&&e[HR][i]&&(e[HR][i]=!1),n=CR(n,{enumerable:yR(0,!1)})),hv(e,i,n)):iv(e,i,n)},Ev=function(e,t){SR(e);var n=TR(t),i=bR(n).concat(Sv(n));return KR(i,(function(t){_R&&!hR(mv,n,t)||_v(e,t,n[t])})),e},mv=function(e){var t=RR(e),n=hR(ov,this,t);return!(this===ZR&&fR(av,t)&&!fR(cv,t))&&(!(n||!fR(this,t)||!fR(av,t)||fR(this,HR)&&this[HR][t])||n)},fv=function(e,t){var n=TR(e),i=RR(t);if(n!==ZR||!fR(av,i)||fR(cv,i)){var r=nv(n,i);return!r||!fR(av,i)||fR(n,HR)&&n[HR][i]||(r.enumerable=!0),r}},gv=function(e){var t=rv(TR(e)),n=[];return KR(t,(function(e){fR(av,e)||fR(UR,e)||sv(n,e)})),n},Sv=function(e){var t=e===ZR,n=rv(t?cv:TR(e)),i=[];return KR(n,(function(e){!fR(av,e)||t&&!fR(ZR,e)||sv(i,av[e])})),i};ER||(LR(QR=(qR=function(){if(gR(QR,this))throw new ev("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?vR(arguments[0]):void 0,t=VR(e),n=function(e){var i=void 0===this?uR:this;i===ZR&&hR(n,cv,e),fR(i,HR)&&fR(i[HR],t)&&(i[HR][t]=!1);var r=yR(1,e);try{hv(i,t,r)}catch(e){if(!(e instanceof $R))throw e;uv(i,t,r)}};return _R&&lv&&hv(ZR,t,{configurable:!0,set:n}),pv(t,e)})[XR],"toString",(function(){return zR(this).tag})),LR(qR,"withoutSetter",(function(e){return pv(VR(e),e)})),PR.f=mv,NR.f=_v,DR.f=Ev,OR.f=fv,IR.f=AR.f=gv,wR.f=Sv,FR.f=function(e){return pv(xR(e),e)},_R&&kR(QR,"description",{configurable:!0,get:function(){return zR(this).description}})),lR({global:!0,constructor:!0,wrap:!0,forced:!ER,sham:!ER},{Symbol:qR}),KR(bR(dv),(function(e){BR(e)})),lR({target:YR,stat:!0,forced:!ER},{useSetter:function(){lv=!0},useSimple:function(){lv=!1}}),lR({target:"Object",stat:!0,forced:!ER,sham:!_R},{create:function(e,t){return void 0===t?CR(e):Ev(CR(e),t)},defineProperty:_v,defineProperties:Ev,getOwnPropertyDescriptor:fv}),lR({target:"Object",stat:!0,forced:!ER},{getOwnPropertyNames:gv}),jR(),GR(qR,YR),UR[HR]=!0;var Tv=ge&&!!Symbol.for&&!!Symbol.keyFor,Rv=Nn,vv=re,yv=$e,Cv=Ri,bv=Xe,Iv=Tv,Av=bv("string-to-symbol-registry"),wv=bv("symbol-to-string-registry");Rv({target:"Symbol",stat:!0,forced:!Iv},{for:function(e){var t=Cv(e);if(yv(Av,t))return Av[t];var n=vv("Symbol")(t);return Av[t]=n,wv[n]=t,n}});var Ov=Nn,Nv=$e,Dv=Ce,Pv=Ie,Lv=Tv,kv=Xe("symbol-to-string-registry");Ov({target:"Symbol",stat:!0,forced:!Lv},{keyFor:function(e){if(!Dv(e))throw new TypeError(Pv(e)+" is not a symbol");if(Nv(kv,e))return kv[e]}});var Mv=Q,Uv=ga.get,Vv=d,xv=$e,Fv=SyntaxError,Bv=parseInt,jv=String.fromCharCode,Gv=Vv("".charAt),Wv=Vv("".slice),Kv=Vv(/./.exec),Hv={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t"},Yv=/^[\da-f]{4}$/i,Xv=/^[\u0000-\u001F]$/,Jv=!i((function(){var e="9007199254740993",t=JSON.rawJSON(e);return!JSON.isRawJSON(t)||JSON.stringify(t)!==e})),zv=Nn,Zv=re,qv=f,Qv=D,$v=d,ey=i,ty=cr,ny=I,iy=function(e){if(!Mv(e))return!1;var t=Uv(e);return!!t&&"RawJSON"===t.type},ry=Ce,oy=R,sy=Ri,ay=dd,cy=function(e,t){for(var n=!0,i="";t<e.length;){var r=Gv(e,t);if("\\"===r){var o=Wv(e,t,t+2);if(xv(Hv,o))i+=Hv[o],t+=2;else{if("\\u"!==o)throw new Fv('Unknown escape sequence: "'+o+'"');var s=Wv(e,t+=2,t+4);if(!Kv(Yv,s))throw new Fv("Bad Unicode escape at: "+t);i+=jv(Bv(s,16)),t+=4}}else{if('"'===r){n=!1,t++;break}if(Kv(Xv,r))throw new Fv("Bad control character in string literal at: "+t);i+=r,t++}}if(n)throw new Fv("Unterminated string at: "+t);return{value:i,end:t}},dy=rt,ly=ge,uy=Jv,hy=String,py=Zv("JSON","stringify"),_y=$v(/./.exec),Ey=$v("".charAt),my=$v("".charCodeAt),fy=$v("".replace),gy=$v("".slice),Sy=$v([].push),Ty=$v(1.1.toString),Ry=/[\uD800-\uDFFF]/g,vy=/^[\uD800-\uDBFF]$/,yy=/^[\uDC00-\uDFFF]$/,Cy=dy(),by=Cy.length,Iy=!ly||ey((function(){var e=Zv("Symbol")("stringify detection");return"[null]"!==py([e])||"{}"!==py({a:e})||"{}"!==py(Object(e))})),Ay=ey((function(){return'"\\udf06\\ud834"'!==py("\udf06\ud834")||'"\\udead"'!==py("\udead")})),wy=Iy?function(e,t){var n=ay(arguments),i=Ny(t);if(ny(i)||void 0!==e&&!ry(e))return n[1]=function(e,t){if(ny(i)&&(t=Qv(i,this,hy(e),t)),!ry(t))return t},qv(py,null,n)}:py,Oy=function(e,t,n){var i=Ey(n,t-1),r=Ey(n,t+1);return _y(vy,e)&&!_y(yy,r)||_y(yy,e)&&!_y(vy,i)?"\\u"+Ty(my(e,0),16):e},Ny=function(e){if(ny(e))return e;if(ty(e)){for(var t=e.length,n=[],i=0;i<t;i++){var r=e[i];"string"==typeof r?Sy(n,r):"number"!=typeof r&&"Number"!==oy(r)&&"String"!==oy(r)||Sy(n,sy(r))}var o=n.length,s=!0;return function(e,t){if(s)return s=!1,t;if(ty(this))return t;for(var i=0;i<o;i++)if(n[i]===e)return t}}};py&&zv({target:"JSON",stat:!0,arity:3,forced:Iy||Ay||!uy},{stringify:function(e,t,n){var i=Ny(t),r=[],o=wy(e,(function(e,t){var n=ny(i)?Qv(i,this,hy(e),t):t;return!uy&&iy(n)?Cy+(Sy(r,n.rawJSON)-1):n}),n);if("string"!=typeof o)return o;if(Ay&&(o=fy(o,Ry,Oy)),uy)return o;for(var s="",a=o.length,c=0;c<a;c++){var d=Ey(o,c);if('"'===d){var l=cy(o,++c).end-1,u=gy(o,c,l);s+=gy(u,0,by)===Cy?r[gy(u,by)]:'"'+u+'"',c=l}else s+=d}return s}});var Dy=eo,Py=Ze;Nn({target:"Object",stat:!0,forced:!ge||i((function(){Dy.f(1)}))},{getOwnPropertySymbols:function(e){var t=Dy.f;return t?t(Py(e)):[]}}),ZT("asyncDispose"),ZT("asyncIterator"),ZT("dispose"),ZT("hasInstance"),ZT("isConcatSpreadable"),ZT("iterator"),ZT("match"),ZT("matchAll"),ZT("replace"),ZT("search"),ZT("species"),ZT("split");var Ly=tR;ZT("toPrimitive"),Ly();var ky=re,My=Ha;ZT("toStringTag"),My(ky("Symbol"),"Symbol"),ZT("unscopables"),Ha(h.JSON,"JSON",!0);var Uy=$.Symbol,Vy=pt,xy=Qt.f,Fy=Vy("metadata"),By=Function.prototype;void 0===By[Fy]&&xy(By,Fy,{value:null}),ZT("metadata");var jy=Uy,Gy=d,Wy=re("Symbol"),Ky=Wy.keyFor,Hy=Gy(Wy.prototype.valueOf),Yy=Wy.isRegisteredSymbol||function(e){try{return void 0!==Ky(Hy(e))}catch(e){return!1}};Nn({target:"Symbol",stat:!0},{isRegisteredSymbol:Yy});for(var Xy=Xe,Jy=re,zy=d,Zy=Ce,qy=pt,Qy=Jy("Symbol"),$y=Qy.isWellKnownSymbol,eC=Jy("Object","getOwnPropertyNames"),tC=zy(Qy.prototype.valueOf),nC=Xy("wks"),iC=0,rC=eC(Qy),oC=rC.length;iC<oC;iC++)try{var sC=rC[iC];Zy(Qy[sC])&&qy(sC)}catch(e){}var aC=function(e){if($y&&$y(e))return!0;try{for(var t=tC(e),n=0,i=eC(nC),r=i.length;n<r;n++)if(nC[i[n]]==t)return!0}catch(e){}return!1};Nn({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:aC}),ZT("customMatcher"),ZT("observable"),Nn({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:Yy}),Nn({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:aC}),ZT("matcher"),ZT("metadataKey"),ZT("patternMatch"),ZT("replaceAll");var cC=n(jy),dC=n(as),lC=Ze,uC=Wn,hC=im,pC=uT;Nn({target:"Array",proto:!0,arity:1,forced:i((function(){return 4294967297!==[].push.call({length:4294967296},1)}))||!function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(e){return e instanceof TypeError}}()},{push:function(e){var t=lC(this),n=uC(t),i=arguments.length;pC(n+i);for(var r=0;r<i;r++)t[n]=arguments[r],n++;return hC(t,n),n}});var _C=ni("Array","push"),EC=l,mC=_C,fC=Array.prototype,gC=function(e){var t=e.push;return e===fC||EC(fC,e)&&t===fC.push?mC:t},SC=n(gC);var TC=Nn,RC=cr,vC=ed,yC=Q,CC=Fn,bC=Wn,IC=Z,AC=QE,wC=im,OC=pt,NC=dd,DC=vT("slice"),PC=OC("species"),LC=Array,kC=Math.max;TC({target:"Array",proto:!0,forced:!DC},{slice:function(e,t){var n,i,r,o=IC(this),s=bC(o),a=CC(e,s),c=CC(void 0===t?s:t,s);if(RC(o)&&(n=o.constructor,(vC(n)&&(n===LC||RC(n.prototype))||yC(n)&&null===(n=n[PC]))&&(n=void 0),n===LC||void 0===n))return NC(o,a,c);for(i=new(void 0===n?LC:n)(kC(c-a,0)),r=0;a<c;a++,r++)a in o&&AC(i,r,o[a]);return wC(i,r),i}});var MC=ni("Array","slice"),UC=l,VC=MC,xC=Array.prototype,FC=function(e){var t=e.slice;return e===xC||UC(xC,e)&&t===xC.slice?VC:t},BC=n(FC),jC=fm;Nn({target:"Array",stat:!0,forced:!Vu((function(e){Array.from(e)}))},{from:jC});var GC=n($.Array.from);function WC(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}function KC(e,t){return function(e){if(dT(e))return e}(e)||function(e,t){var n=null==e?null:void 0!==cC&&dC(e)||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(SC(a).call(a,i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){var n;if(e){if("string"==typeof e)return WC(e,t);var i=BC(n=Object.prototype.toString.call(e)).call(n,8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?GC(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?WC(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var HC=i,YC=h.RegExp,XC=!HC((function(){var e=!0;try{YC(".","d")}catch(t){e=!1}var t={},n="",i=e?"dgimsy":"gimsy",r=function(e,i){Object.defineProperty(t,e,{get:function(){return n+=i,!0}})},o={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var s in e&&(o.hasIndices="d"),o)r(s,o[s]);return Object.getOwnPropertyDescriptor(YC.prototype,"flags").get.call(t)!==i||n!==i})),JC=rn,zC=D,ZC=$e,qC=l,QC={correct:XC},$C=function(){var e=JC(this),t="";return e.hasIndices&&(t+="d"),e.global&&(t+="g"),e.ignoreCase&&(t+="i"),e.multiline&&(t+="m"),e.dotAll&&(t+="s"),e.unicode&&(t+="u"),e.unicodeSets&&(t+="v"),e.sticky&&(t+="y"),t},eb=RegExp.prototype,tb=QC.correct?function(e){return e.flags}:function(e){return QC.correct||!qC(eb,e)||ZC(e,"flags")?e.flags:zC($C,e)},nb=d,ib=Ze,rb=Math.floor,ob=nb("".charAt),sb=nb("".replace),ab=nb("".slice),cb=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,db=/\$([$&'`]|\d{1,2})/g,lb=Nn,ub=D,hb=d,pb=X,_b=I,Eb=Q,mb=ai,fb=Ri,gb=Le,Sb=tb,Tb=function(e,t,n,i,r,o){var s=n+e.length,a=i.length,c=db;return void 0!==r&&(r=ib(r),c=cb),sb(o,c,(function(o,c){var d;switch(ob(c,0)){case"$":return"$";case"&":return e;case"`":return ab(t,0,n);case"'":return ab(t,s);case"<":d=r[ab(c,1,-1)];break;default:var l=+c;if(0===l)return o;if(l>a){var u=rb(l/10);return 0===u?o:u<=a?void 0===i[u-1]?ob(c,1):i[u-1]+ob(c,1):o}d=i[l-1]}return void 0===d?"":d}))},Rb=pt("replace"),vb=TypeError,yb=hb("".indexOf),Cb=hb("".replace),bb=hb("".slice),Ib=Math.max;lb({target:"String",proto:!0},{replaceAll:function(e,t){var n,i,r,o,s,a,c,d,l,u,h=pb(this),p=0,_="";if(Eb(e)){if((n=mb(e))&&(i=fb(pb(Sb(e))),!~yb(i,"g")))throw new vb("`.replaceAll` does not allow non-global regexes");if(r=gb(e,Rb))return ub(r,e,h,t);if(n)return Cb(fb(h),e,t)}for(o=fb(h),s=fb(e),(a=_b(t))||(t=fb(t)),c=s.length,d=Ib(1,c),l=yb(o,s);-1!==l;)u=a?fb(t(s,l,o)):Tb(s,o,l,[],void 0,t),_+=bb(o,p,l)+u,p=l+c,l=l+d>o.length?-1:yb(o,s,l+d);return p<o.length&&(_+=bb(o,p)),_}});var Ab=ni("String","replaceAll"),wb=l,Ob=Ab,Nb=String.prototype,Db=function(e){var t=e.replaceAll;return"string"==typeof e||e===Nb||wb(Nb,e)&&t===Nb.replaceAll?Ob:t},Pb=n(Db),Lb=h;Nn({global:!0,forced:Lb.globalThis!==Lb},{globalThis:Lb});var kb,Mb,Ub=n(h),Vb={exports:{}};kb=Vb,Mb=Vb.exports,function(e,t){var n="function",i="undefined",r="object",o="string",s="major",a="model",c="name",d="type",l="vendor",u="version",h="architecture",p="console",_="mobile",E="tablet",m="smarttv",f="wearable",g="embedded",S="Amazon",T="Apple",R="ASUS",v="BlackBerry",y="Browser",C="Chrome",b="Firefox",I="Google",A="Huawei",w="LG",O="Microsoft",N="Motorola",D="Opera",P="Samsung",L="Sharp",k="Sony",M="Xiaomi",U="Zebra",V="Facebook",x="Chromium OS",F="Mac OS",B=function(e){for(var t={},n=0;n<e.length;n++)t[e[n].toUpperCase()]=e[n];return t},j=function(e,t){return typeof e===o&&-1!==G(t).indexOf(G(e))},G=function(e){return e.toLowerCase()},W=function(e,t){if(typeof e===o)return e=e.replace(/^\s\s*/,""),typeof t===i?e:e.substring(0,350)},K=function(e,i){for(var o,s,a,c,d,l,u=0;u<i.length&&!d;){var h=i[u],p=i[u+1];for(o=s=0;o<h.length&&!d&&h[o];)if(d=h[o++].exec(e))for(a=0;a<p.length;a++)l=d[++s],typeof(c=p[a])===r&&c.length>0?2===c.length?typeof c[1]==n?this[c[0]]=c[1].call(this,l):this[c[0]]=c[1]:3===c.length?typeof c[1]!==n||c[1].exec&&c[1].test?this[c[0]]=l?l.replace(c[1],c[2]):t:this[c[0]]=l?c[1].call(this,l,c[2]):t:4===c.length&&(this[c[0]]=l?c[3].call(this,l.replace(c[1],c[2])):t):this[c]=l||t;u+=2}},H=function(e,n){for(var i in n)if(typeof n[i]===r&&n[i].length>0){for(var o=0;o<n[i].length;o++)if(j(n[i][o],e))return"?"===i?t:i}else if(j(n[i],e))return"?"===i?t:i;return e},Y={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2",8.1:"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},X={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[u,[c,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[u,[c,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[c,u],[/opios[\/ ]+([\w\.]+)/i],[u,[c,D+" Mini"]],[/\bopr\/([\w\.]+)/i],[u,[c,D]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/ ]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/ ]?([\w\.]*)/i,/(ba?idubrowser)[\/ ]?([\w\.]+)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|qq|duckduckgo)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[c,u],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[u,[c,"UC"+y]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i],[u,[c,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[u,[c,"WeChat"]],[/konqueror\/([\w\.]+)/i],[u,[c,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[u,[c,"IE"]],[/yabrowser\/([\w\.]+)/i],[u,[c,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[c,/(.+)/,"$1 Secure "+y],u],[/\bfocus\/([\w\.]+)/i],[u,[c,b+" Focus"]],[/\bopt\/([\w\.]+)/i],[u,[c,D+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[u,[c,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[u,[c,"Dolphin"]],[/coast\/([\w\.]+)/i],[u,[c,D+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[u,[c,"MIUI "+y]],[/fxios\/([-\w\.]+)/i],[u,[c,b]],[/\bqihu|(qi?ho?o?|360)browser/i],[[c,"360 "+y]],[/(oculus|samsung|sailfish|huawei)browser\/([\w\.]+)/i],[[c,/(.+)/,"$1 "+y],u],[/(comodo_dragon)\/([\w\.]+)/i],[[c,/_/g," "],u],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/ ]?([\w\.]+)/i],[c,u],[/(metasr)[\/ ]?([\w\.]+)/i,/(lbbrowser)/i,/\[(linkedin)app\]/i],[c],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[c,V],u],[/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/ ]([-\w\.]+)/i],[c,u],[/\bgsa\/([\w\.]+) .*safari\//i],[u,[c,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[u,[c,C+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[c,C+" WebView"],u],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[u,[c,"Android "+y]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[c,u],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[u,[c,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[u,c],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[c,[u,H,{"1.0":"/8",1.2:"/1",1.3:"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"}]],[/(webkit|khtml)\/([\w\.]+)/i],[c,u],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[c,"Netscape"],u],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[u,[c,b+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/ ]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i,/panasonic;(viera)/i],[c,u],[/(cobalt)\/([\w\.]+)/i],[c,[u,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[h,"amd64"]],[/(ia32(?=;))/i],[[h,G]],[/((?:i[346]|x)86)[;\)]/i],[[h,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[h,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[h,"armhf"]],[/windows (ce|mobile); ppc;/i],[[h,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[h,/ower/,"",G]],[/(sun4\w)[;\)]/i],[[h,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[h,G]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[a,[l,P],[d,E]],[/\b((?:s[cgp]h|gt|sm)-\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[a,[l,P],[d,_]],[/\((ip(?:hone|od)[\w ]*);/i],[a,[l,T],[d,_]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[a,[l,T],[d,E]],[/(macintosh);/i],[a,[l,T]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[a,[l,L],[d,_]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[a,[l,A],[d,E]],[/(?:huawei|honor)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[a,[l,A],[d,_]],[/\b(poco[\w ]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[a,/_/g," "],[l,M],[d,_]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[a,/_/g," "],[l,M],[d,E]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[a,[l,"OPPO"],[d,_]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[a,[l,"Vivo"],[d,_]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[a,[l,"Realme"],[d,_]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w ]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\) ]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[a,[l,N],[d,_]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[a,[l,N],[d,E]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[a,[l,w],[d,E]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[a,[l,w],[d,_]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[a,[l,"Lenovo"],[d,E]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[a,/_/g," "],[l,"Nokia"],[d,_]],[/(pixel c)\b/i],[a,[l,I],[d,E]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[a,[l,I],[d,_]],[/droid.+ (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[a,[l,k],[d,_]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[a,"Xperia Tablet"],[l,k],[d,E]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[a,[l,"OnePlus"],[d,_]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[a,[l,S],[d,E]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[a,/(.+)/g,"Fire Phone $1"],[l,S],[d,_]],[/(playbook);[-\w\),; ]+(rim)/i],[a,l,[d,E]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[a,[l,v],[d,_]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[a,[l,R],[d,E]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[a,[l,R],[d,_]],[/(nexus 9)/i],[a,[l,"HTC"],[d,E]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[l,[a,/_/g," "],[d,_]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[a,[l,"Acer"],[d,E]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[a,[l,"Meizu"],[d,_]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[l,a,[d,_]],[/(kobo)\s(ereader|touch)/i,/(archos) (gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w ]+build\/(\w+)/i,/(dell) (strea[kpr\d ]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone) ([\w ]+)(?:\)| bui)/i],[l,a,[d,E]],[/(surface duo)/i],[a,[l,O],[d,E]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[a,[l,"Fairphone"],[d,_]],[/(u304aa)/i],[a,[l,"AT&T"],[d,_]],[/\bsie-(\w*)/i],[a,[l,"Siemens"],[d,_]],[/\b(rct\w+) b/i],[a,[l,"RCA"],[d,E]],[/\b(venue[\d ]{2,7}) b/i],[a,[l,"Dell"],[d,E]],[/\b(q(?:mv|ta)\w+) b/i],[a,[l,"Verizon"],[d,E]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[a,[l,"Barnes & Noble"],[d,E]],[/\b(tm\d{3}\w+) b/i],[a,[l,"NuVision"],[d,E]],[/\b(k88) b/i],[a,[l,"ZTE"],[d,E]],[/\b(nx\d{3}j) b/i],[a,[l,"ZTE"],[d,_]],[/\b(gen\d{3}) b.+49h/i],[a,[l,"Swiss"],[d,_]],[/\b(zur\d{3}) b/i],[a,[l,"Swiss"],[d,E]],[/\b((zeki)?tb.*\b) b/i],[a,[l,"Zeki"],[d,E]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[l,"Dragon Touch"],a,[d,E]],[/\b(ns-?\w{0,9}) b/i],[a,[l,"Insignia"],[d,E]],[/\b((nxa|next)-?\w{0,9}) b/i],[a,[l,"NextBook"],[d,E]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[l,"Voice"],a,[d,_]],[/\b(lvtel\-)?(v1[12]) b/i],[[l,"LvTel"],a,[d,_]],[/\b(ph-1) /i],[a,[l,"Essential"],[d,_]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[a,[l,"Envizen"],[d,E]],[/\b(trio[-\w\. ]+) b/i],[a,[l,"MachSpeed"],[d,E]],[/\btu_(1491) b/i],[a,[l,"Rotor"],[d,E]],[/(shield[\w ]+) b/i],[a,[l,"Nvidia"],[d,E]],[/(sprint) (\w+)/i],[l,a,[d,_]],[/(kin\.[onetw]{3})/i],[[a,/\./g," "],[l,O],[d,_]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[a,[l,U],[d,E]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[a,[l,U],[d,_]],[/smart-tv.+(samsung)/i],[l,[d,m]],[/hbbtv.+maple;(\d+)/i],[[a,/^/,"SmartTV"],[l,P],[d,m]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[l,w],[d,m]],[/(apple) ?tv/i],[l,[a,T+" TV"],[d,m]],[/crkey/i],[[a,C+"cast"],[l,I],[d,m]],[/droid.+aft(\w)( bui|\))/i],[a,[l,S],[d,m]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[a,[l,L],[d,m]],[/(bravia[\w ]+)( bui|\))/i],[a,[l,k],[d,m]],[/(mitv-\w{5}) bui/i],[a,[l,M],[d,m]],[/Hbbtv.*(technisat) (.*);/i],[l,a,[d,m]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[l,W],[a,W],[d,m]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[d,m]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[l,a,[d,p]],[/droid.+; (shield) bui/i],[a,[l,"Nvidia"],[d,p]],[/(playstation [345portablevi]+)/i],[a,[l,k],[d,p]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[a,[l,O],[d,p]],[/((pebble))app/i],[l,a,[d,f]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[a,[l,T],[d,f]],[/droid.+; (glass) \d/i],[a,[l,I],[d,f]],[/droid.+; (wt63?0{2,3})\)/i],[a,[l,U],[d,f]],[/(quest( 2| pro)?)/i],[a,[l,V],[d,f]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[l,[d,g]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[a,[d,_]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[a,[d,E]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[d,E]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[d,_]],[/(android[-\w\. ]{0,9});.+buil/i],[a,[l,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[u,[c,"EdgeHTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[u,[c,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i],[c,u],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[u,c]],os:[[/microsoft (windows) (vista|xp)/i],[c,u],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i,/(windows)[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i],[c,[u,H,Y]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[c,"Windows"],[u,H,Y]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[u,/_/g,"."],[c,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[c,F],[u,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[u,c],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[c,u],[/\(bb(10);/i],[u,[c,v]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[u,[c,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[u,[c,b+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[u,[c,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[u,[c,"watchOS"]],[/crkey\/([\d\.]+)/i],[u,[c,C+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[c,x],u],[/panasonic;(viera)/i,/(netrange)mmh/i,/(nettv)\/(\d+\.[\w\.]+)/i,/(nintendo|playstation) ([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b ?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\) ]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/ ]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux) ?([\w\.]*)/i,/(gnu) ?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/ ]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku) (\w+)/i],[c,u],[/(sunos) ?([\w\.\d]*)/i],[[c,"Solaris"],u],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix) ?([\w\.]*)/i],[c,u]]},J=function(p,m){if(typeof p===r&&(m=p,p=t),!(this instanceof J))return new J(p,m).getResult();var f=typeof e!==i&&e.navigator?e.navigator:t,g=p||(f&&f.userAgent?f.userAgent:""),S=f&&f.userAgentData?f.userAgentData:t,T=m?function(e,t){var n={};for(var i in e)t[i]&&t[i].length%2==0?n[i]=t[i].concat(e[i]):n[i]=e[i];return n}(X,m):X;return this.getBrowser=function(){var e={};return e[c]=t,e[u]=t,K.call(e,g,T.browser),e[s]=function(e){return typeof e===o?e.replace(/[^\d\.]/g,"").split(".")[0]:t}(e[u]),f&&f.brave&&typeof f.brave.isBrave==n&&(e[c]="Brave"),e},this.getCPU=function(){var e={};return e[h]=t,K.call(e,g,T.cpu),e},this.getDevice=function(){var e={};return e[l]=t,e[a]=t,e[d]=t,K.call(e,g,T.device),!e[d]&&S&&S.mobile&&(e[d]=_),"Macintosh"==e[a]&&f&&typeof f.standalone!==i&&f.maxTouchPoints&&f.maxTouchPoints>2&&(e[a]="iPad",e[d]=E),e},this.getEngine=function(){var e={};return e[c]=t,e[u]=t,K.call(e,g,T.engine),e},this.getOS=function(){var e={};return e[c]=t,e[u]=t,K.call(e,g,T.os),!e[c]&&S&&"Unknown"!=S.platform&&(e[c]=S.platform.replace(/chrome os/i,x).replace(/macos/i,F)),e},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return g},this.setUA=function(e){return g=typeof e===o&&e.length>350?W(e,350):e,this},this.setUA(g),this};J.VERSION="0.7.34",J.BROWSER=B([c,u,s]),J.CPU=B([h]),J.DEVICE=B([a,l,d,p,_,m,E,f,g]),J.ENGINE=J.OS=B([c,u]),kb.exports&&(Mb=kb.exports=J),Mb.UAParser=J;var z=typeof e!==i&&(e.jQuery||e.Zepto);if(z&&!z.ua){var Z=new J;z.ua=Z.getResult(),z.ua.get=function(){return Z.getUA()},z.ua.set=function(e){Z.setUA(e);var t=Z.getResult();for(var n in t)z.ua[n]=t[n]}}}("object"==typeof window?window:t);var xb=n(Vb.exports),Fb=Bd.clear;Nn({global:!0,bind:!0,enumerable:!0,forced:h.clearImmediate!==Fb},{clearImmediate:Fb});var Bb=h,jb=f,Gb=I,Wb=qi,Kb=ae,Hb=dd,Yb=ud,Xb=Bb.Function,Jb=/MSIE .\./.test(Kb)||"BUN"===Wb&&function(){var e=Bb.Bun.version.split(".");return e.length<3||"0"===e[0]&&(e[1]<3||"3"===e[1]&&"0"===e[2])}(),zb=Nn,Zb=h,qb=Bd.set,Qb=function(e,t){var n=t?2:1;return Jb?function(i,r){var o=Yb(arguments.length,1)>n,s=Gb(i)?i:Xb(i),a=o?Hb(arguments,n):[],c=o?function(){jb(s,this,a)}:s;return t?e(c,r):e(c)}:e},$b=Zb.setImmediate?Qb(qb,!1):qb;zb({global:!0,bind:!0,enumerable:!0,forced:Zb.setImmediate!==$b},{setImmediate:$b});var eI=n($.setImmediate),tI=h,nI=ml,iI=Ne,rI=ud,oI=w;Nn({global:!0,enumerable:!0,dontCallGetSet:!0,forced:i((function(){return oI&&1!==Object.getOwnPropertyDescriptor(tI,"queueMicrotask").value.length}))},{queueMicrotask:function(e){rI(arguments.length,1),nI(iI(e))}});var sI=n($.queueMicrotask);function aI(e,t){return function(){return e.apply(t,arguments)}}const cI=Object.prototype.toString,dI=Object.getPrototypeOf,lI=Symbol.iterator,uI=Symbol.toStringTag,hI=(e=>{let t=Object.prototype.hasOwnProperty;return(e,n)=>t.call(e,n)})(),pI=(e,t)=>{let n=e;const i=[];for(;null!=n&&n!==Object.prototype;){if(-1!==i.indexOf(n))return!1;if(i.push(n),hI(n,t))return!0;n=dI(n)}return!1},_I=(EI=Object.create(null),e=>{const t=cI.call(e);return EI[t]||(EI[t]=t.slice(8,-1).toLowerCase())});var EI;const mI=e=>(e=e.toLowerCase(),t=>_I(t)===e),fI=e=>t=>typeof t===e,gI=Array.isArray,SI=fI("undefined");function TI(e){return null!==e&&!SI(e)&&null!==e.constructor&&!SI(e.constructor)&&yI(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const RI=mI("ArrayBuffer");const vI=fI("string"),yI=fI("function"),CI=fI("number"),bI=e=>null!==e&&"object"==typeof e,II=e=>{if(!bI(e))return!1;const t=dI(e);return!(null!==t&&t!==Object.prototype&&null!==dI(t)||pI(e,uI)||pI(e,lI))},AI=mI("Date"),wI=mI("File"),OI=mI("Blob"),NI=mI("FileList"),DI=mI("Set");const PI=void 0!==Ub?Ub:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},LI=void 0!==PI.FormData?PI.FormData:void 0,kI=mI("URLSearchParams"),MI=KC(["ReadableStream","Request","Response","Headers"].map(mI),4),UI=MI[0],VI=MI[1],xI=MI[2],FI=MI[3];function BI(e,t){let n,i,r=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).allOwnKeys,o=void 0!==r&&r;if(null!=e)if("object"!=typeof e&&(e=[e]),gI(e))for(n=0,i=e.length;n<i;n++)t.call(null,e[n],n,e);else{if(TI(e))return;const i=o?Object.getOwnPropertyNames(e):Object.keys(e),r=i.length;let s;for(n=0;n<r;n++)s=i[n],t.call(null,e[s],s,e)}}function jI(e,t){if(TI(e))return null;t=t.toLowerCase();const n=Object.keys(e);let i,r=n.length;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const GI=void 0!==Ub?Ub:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global,WI=e=>!SI(e)&&e!==GI;const KI=(HI="undefined"!=typeof Uint8Array&&dI(Uint8Array),e=>HI&&e instanceof HI);var HI;const YI=mI("HTMLFormElement"),XI=Object.prototype.propertyIsEnumerable,JI=mI("RegExp"),zI=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),i={};BI(n,((n,r)=>{let o;!1!==(o=t(n,r,e))&&(i[r]=o||n)})),Object.defineProperties(e,i)};const ZI=mI("AsyncFunction"),qI=(QI="function"==typeof eI,$I=yI(GI.postMessage),QI?eI:$I?(eA="axios@".concat(Math.random()),tA=[],GI.addEventListener("message",(e=>{let t=e.source,n=e.data;t===GI&&n===eA&&tA.length&&tA.shift()()}),!1),e=>{tA.push(e),GI.postMessage(eA,"*")}):e=>setTimeout(e));var QI,$I,eA,tA;const nA=void 0!==sI?sI.bind(GI):"undefined"!=typeof process&&process.nextTick||qI,iA=e=>null!=e&&yI(e[lI]);var rA={isArray:gI,isArrayBuffer:RI,isBuffer:TI,isFormData:e=>{if(!e)return!1;if(LI&&e instanceof LI)return!0;const t=dI(e);if(!t||t===Object.prototype)return!1;if(!yI(e.append))return!1;const n=_I(e);return"formdata"===n||"object"===n&&yI(e.toString)&&"[object FormData]"===e.toString()},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&RI(e.buffer),t},isString:vI,isNumber:CI,isBoolean:e=>!0===e||!1===e,isObject:bI,isPlainObject:II,isEmptyObject:e=>{if(!bI(e)||TI(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(e){return!1}},isReadableStream:UI,isRequest:VI,isResponse:xI,isHeaders:FI,isUndefined:SI,isDate:AI,isFile:wI,isReactNativeBlob:e=>!(!e||void 0===e.uri),isReactNative:e=>e&&void 0!==e.getParts,isBlob:OI,isRegExp:JI,isFunction:yI,isStream:e=>bI(e)&&yI(e.pipe),isURLSearchParams:kI,isTypedArray:KI,isFileList:NI,forEach:BI,merge:function e(){const t=WI(this)&&this||{},n=t.caseless,i=t.skipUndefined,r={},o=(t,o)=>{if("__proto__"===o||"constructor"===o||"prototype"===o)return;const s=n&&"string"==typeof o&&jI(r,o)||o,a=hI(r,s)?r[s]:void 0;II(a)&&II(t)?r[s]=e(a,t):II(t)?r[s]=e({},t):gI(t)?r[s]=t.slice():i&&SI(t)||(r[s]=t)};for(let e=0,t=arguments.length;e<t;e++){const t=e<0||arguments.length<=e?void 0:arguments[e];if(!t||TI(t))continue;if(BI(t,o),"object"!=typeof t||gI(t))continue;const n=Object.getOwnPropertySymbols(t);for(let e=0;e<n.length;e++){const i=n[e];XI.call(t,i)&&o(t[i],i)}}return r},extend:function(e,t,n){return BI(t,((t,i)=>{n&&yI(t)?Object.defineProperty(e,i,{__proto__:null,value:aI(t,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(e,i,{__proto__:null,value:t,writable:!0,enumerable:!0,configurable:!0})}),{allOwnKeys:(arguments.length>3&&void 0!==arguments[3]?arguments[3]:{}).allOwnKeys}),e},trim:e=>zS(e)?zS(e).call(e):e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,n,i)=>{e.prototype=Object.create(t.prototype,i),Object.defineProperty(e.prototype,"constructor",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(e,"super",{__proto__:null,value:t.prototype}),n&&Object.assign(e.prototype,n)},toFlatObject:(e,t,n,i)=>{let r,o,s;const a={};if(t=t||{},null==e)return t;do{for(r=Object.getOwnPropertyNames(e),o=r.length;o-- >0;)s=r[o],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==n&&dI(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},kindOf:_I,kindOfTest:mI,endsWith:(e,t,n)=>{e=String(e),(void 0===n||n>e.length)&&(n=e.length),n-=t.length;const i=e.indexOf(t,n);return-1!==i&&i===n},toArray:e=>{if(!e)return null;if(gI(e))return e;let t=e.length;if(!CI(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},forEachEntry:(e,t)=>{const n=(e&&e[lI]).call(e);let i;for(;(i=n.next())&&!i.done;){const n=i.value;t.call(e,n[0],n[1])}},matchAll:(e,t)=>{let n;const i=[];for(;null!==(n=e.exec(t));)i.push(n);return i},isHTMLForm:YI,hasOwnProperty:hI,hasOwnProp:hI,hasOwnInPrototypeChain:pI,getSafeProp:(e,t)=>null!=e&&pI(e,t)?e[t]:void 0,reduceDescriptors:zI,freezeMethods:e=>{zI(e,((t,n)=>{var i;if(yI(e)&&Ui(i=["arguments","caller","callee"]).call(i,n))return!1;const r=e[n];yI(r)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")}))}))},toObjectSet:(e,t)=>{const n={},i=e=>{e.forEach((e=>{n[e]=!0}))};return gI(e)?i(e):i(String(e).split(t)),n},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,n){return t.toUpperCase()+n})),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:jI,global:GI,isContextDefined:WI,isSpecCompliantForm:function(e){return!!(e&&yI(e.append)&&"FormData"===e[uI]&&e[lI])},toJSONObject:e=>{const t=new WeakSet,n=e=>{if(bI(e)){if(t.has(e))return;if(TI(e))return e;if(!("toJSON"in e)){let i;if(t.add(e),DI(e)){i=[];for(const t of e){const e=n(t);!SI(e)&&i.push(e)}}else i=gI(e)?[]:{},BI(e,((e,t)=>{const r=n(e);!SI(r)&&(i[t]=r)}));return t.delete(e),i}}return e};return n(e)},isAsyncFn:ZI,isThenable:e=>e&&(bI(e)||yI(e))&&yI(e.then)&&yI(e.catch),setImmediate:qI,asap:nA,isIterable:iA,isSafeIterable:e=>null!=e&&pI(e,lI)&&iA(e)};const oA=rA.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const sA=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),aA=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function cA(e,t){return rA.isArray(e)?e.map((e=>cA(e,t))):function(e){let t=0,n=e.length;for(;t<n;){const n=e.charCodeAt(t);if(9!==n&&32!==n)break;t+=1}for(;n>t;){const t=e.charCodeAt(n-1);if(9!==t&&32!==t)break;n-=1}return 0===t&&n===e.length?e:e.slice(t,n)}(String(e).replace(t,""))}const dA=e=>cA(e,sA),lA=e=>cA(e,aA);function uA(e){const t=Object.create(null);return rA.forEach(e.toJSON(),((e,n)=>{t[n]=lA(e)})),t}const hA=Symbol("internals");function pA(e){var t;return e&&zS(t=String(e)).call(t).toLowerCase()}function _A(e){return!1===e||null==e?e:rA.isArray(e)?e.map(_A):dA(String(e))}const EA=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function mA(e){let t=0,n=e.length;for(;t<n;){const n=e.charCodeAt(t);if(9!==n&&32!==n)break;t+=1}for(;n>t;){const t=e.charCodeAt(n-1);if(9!==t&&32!==t)break;n-=1}return 0===t&&n===e.length?e:e.slice(t,n)}function fA(e,t,n,i,r){return rA.isFunction(i)?i.call(this,t,n):(r&&(t=n),rA.isString(t)?rA.isString(i)?-1!==t.indexOf(i):rA.isRegExp(i)?i.test(t):void 0:void 0)}class gA{constructor(e){e&&this.set(e)}set(e,t,n){const i=this;function r(e,t,n){const r=pA(t);if(!r)return;const o=rA.findKey(i,r);(!o||void 0===i[o]||!0===n||void 0===n&&!1!==i[o])&&(i[o||t]=_A(e))}const o=(e,t)=>rA.forEach(e,((e,n)=>r(e,n,t)));if(rA.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(rA.isString(e)&&(e=zS(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(zS(s=e).call(s)))o((e=>{const t={};let n,i,r;return e&&e.split("\n").forEach((function(e){var o,s;r=e.indexOf(":"),n=zS(o=e.substring(0,r)).call(o).toLowerCase(),i=zS(s=e.substring(r+1)).call(s);const a=rA.hasOwnProp(t,n);!n||a&&rA.hasOwnProp(oA,n)||("set-cookie"===n?a?t[n].push(i):t[n]=[i]:t[n]=a?t[n]+", "+i:i)})),t})(e),t);else if(rA.isObject(e)&&rA.isSafeIterable(e)){let n,i,r=Object.create(null);for(const t of e){if(!rA.isArray(t))throw new TypeError("Object iterator must return a key-value pair");i=t[0],rA.hasOwnProp(r,i)?(n=r[i],r[i]=rA.isArray(n)?[...n,t[1]]:[n,t[1]]):r[i]=t[1]}o(r,t)}else null!=e&&r(t,e,n);var s;return this}get(e,t){if(e=pA(e)){const n=rA.findKey(this,e);if(n){const e=this[n];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=n.exec(e);)t[i[1]]=i[2];return t}(e);if(rA.isFunction(t))return t.call(this,e,n);if(rA.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=pA(e)){const n=rA.findKey(this,e);return!(!n||void 0===this[n]||t&&!fA(0,this[n],n,t))}return!1}delete(e,t){const n=this;let i=!1;function r(e){if(e=pA(e)){const r=rA.findKey(n,e);!r||t&&!fA(0,n[r],r,t)||(delete n[r],i=!0)}}return rA.isArray(e)?e.forEach(r):r(e),i}clear(e){const t=Object.keys(this);let n=t.length,i=!1;for(;n--;){const r=t[n];e&&!fA(0,this[r],r,e,!0)||(delete this[r],i=!0)}return i}normalize(e){const t=this,n={};return rA.forEach(this,((i,r)=>{var o;const s=rA.findKey(n,r);if(s)return t[s]=_A(i),void delete t[r];const a=e?function(e){return zS(e).call(e).toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,n)=>t.toUpperCase()+n))}(r):zS(o=String(r)).call(o);a!==r&&delete t[r],t[a]=_A(i),n[a]=!0})),this}concat(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.constructor.concat(this,...t)}toJSON(e){const t=Object.create(null);return rA.forEach(this,((n,i)=>{null!=n&&!1!==n&&(t[i]=e&&rA.isArray(n)?n.join(", "):n)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((e=>{let t=KC(e,2);return t[0]+": "+t[1]})).join("\n")}getSetCookie(){const e=this.get("set-cookie");return rA.isArray(e)?e:null==e||!1===e?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return function(e){const t=Object.create(null),n=String(e);let i=0,r=!1,o=!1;function s(e){const r=mA(n.slice(i,e)),o=r.indexOf("=");if(o<1)return;const s=mA(r.slice(0,o));if(!EA.test(s))return;const a=s.toLowerCase();if("__proto__"===a||"constructor"===a||"prototype"===a)return;const c=mA(r.slice(o+1));t[a]=function(e){const t=e.length-1;if(t<1||34!==e.charCodeAt(0)||34!==e.charCodeAt(t))return e;let n="";for(let i=1;i<t;i++){const r=e.charCodeAt(i);if(34===r)return e;if(92===r&&(i+=1,i>=t))return e;n+=e[i]}return n}(c)}for(let e=0;e<n.length;e++){const t=n.charCodeAt(e);r?o?o=!1:92===t?o=!0:34===t&&(r=!1):34===t?r=!0:44!==t&&59!==t||(s(e),i=e+1)}return s(n.length),t}(e)}static concat(e){const t=new this(e);for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];return i.forEach((e=>t.set(e))),t}static accessor(e){const t=(this[hA]=this[hA]={accessors:{}}).accessors,n=this.prototype;function i(e){const i=pA(e);t[i]||(!function(e,t){const n=rA.toCamelCase(" "+t);["get","set","has"].forEach((i=>{Object.defineProperty(e,i+n,{__proto__:null,value:function(e,n,r){return this[i].call(this,t,e,n,r)},configurable:!0})}))}(n,e),t[i]=!0)}return rA.isArray(e)?e.forEach(i):i(e),this}}gA.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),rA.reduceDescriptors(gA.prototype,((e,t)=>{let n=e.value,i=t[0].toUpperCase()+t.slice(1);return{get:()=>n,set(e){this[i]=e}}})),rA.freezeMethods(gA);var SA=gA;const TA="[REDACTED ****]";function RA(e,t){const n=new Set(t.map((e=>String(e).toLowerCase()))),i=[],r=e=>{if(null===e||"object"!=typeof e)return e;if(rA.isBuffer(e))return e;if(-1!==i.indexOf(e))return;let t;if(e instanceof SA&&(e=e.toJSON()),i.push(e),rA.isArray(e))t=[],e.forEach(((e,n)=>{const i=r(e);rA.isUndefined(i)||(t[n]=i)}));else{if(!rA.isPlainObject(e)&&function(e){if(rA.hasOwnProp(e,"toJSON"))return!0;let t=Object.getPrototypeOf(e);for(;t&&t!==Object.prototype;){if(rA.hasOwnProp(t,"toJSON"))return!0;t=Object.getPrototypeOf(t)}return!1}(e))return i.pop(),e;t=Object.create(null);for(const i of Object.entries(e)){var o=KC(i,2);const e=o[0],s=o[1],a=n.has(e.toLowerCase())?TA:r(s);rA.isUndefined(a)||(t[e]=a)}}return i.pop(),t};return r(e)}function vA(e){try{return String(e)}catch(e){return""}}class yA extends Error{static from(e,t,n,i,r,o){let s=e.message;!s&&rA.isArray(e.errors)&&e.errors.length&&(s=function(e){return e.errors.map((e=>{try{return e&&e.message?vA(e.message):vA(e)}catch(e){return""}})).filter(Boolean).join("; ")||e.name||"AggregateError"}(e));const a=new yA(s,t||e.code,n,i,r);return Object.defineProperty(a,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),a.name=e.name,null!=e.status&&null==a.status&&(a.status=e.status),o&&Object.assign(a,o),a}constructor(e,t,n,i,r){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,t&&(this.code=t),n&&(this.config=n),i&&(this.request=i),r&&(this.response=r,this.status=r.status)}toJSON(){const e=this.config,t=e&&rA.hasOwnProp(e,"redact")?e.redact:void 0,n=rA.isArray(t)&&t.length>0?RA(e,t):rA.toJSONObject(e);return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:n,code:this.code,status:this.status}}}yA.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",yA.ERR_BAD_OPTION="ERR_BAD_OPTION",yA.ECONNABORTED="ECONNABORTED",yA.ETIMEDOUT="ETIMEDOUT",yA.ECONNREFUSED="ECONNREFUSED",yA.ERR_NETWORK="ERR_NETWORK",yA.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",yA.ERR_DEPRECATED="ERR_DEPRECATED",yA.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",yA.ERR_BAD_REQUEST="ERR_BAD_REQUEST",yA.ERR_CANCELED="ERR_CANCELED",yA.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",yA.ERR_INVALID_URL="ERR_INVALID_URL",yA.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";var CA=yA;const bA=100;function IA(e){return rA.isPlainObject(e)||rA.isArray(e)}function AA(e){return rA.endsWith(e,"[]")?e.slice(0,-2):e}function wA(e,t,n){return e?e.concat(t).map((function(e,t){return e=AA(e),!n&&t?"["+e+"]":e})).join(n?".":""):t}const OA=rA.toFlatObject(rA,{},null,(function(e){return/^is[A-Z]/.test(e)}));function NA(e,t,n){if(!rA.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(n=rA.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!rA.isUndefined(t[e])}))).metaTokens,r=n.visitor||p,o=n.dots,s=n.indexes,a=n.Blob||"undefined"!=typeof Blob&&Blob,c=void 0===n.maxDepth?bA:n.maxDepth,d=a&&rA.isSpecCompliantForm(t),l=[];if(!rA.isFunction(r))throw new TypeError("visitor must be a function");function u(e){if(null===e)return"";if(rA.isDate(e))return e.toISOString();if(rA.isBoolean(e))return e.toString();if(!d&&rA.isBlob(e))throw new CA("Blob is not supported. Use a Buffer instead.");if(rA.isArrayBuffer(e)||rA.isTypedArray(e)){if(d&&"function"==typeof a)return new a([e]);throw new CA("Blob is not supported. Use a Buffer instead.",CA.ERR_NOT_SUPPORT)}return e}function h(e){if(e>c)throw new CA("Object is too deeply nested ("+e+" levels). Max depth: "+c,CA.ERR_FORM_DATA_DEPTH_EXCEEDED)}function p(e,n,r){let a=e;if(rA.isReactNative(t)&&rA.isReactNativeBlob(e))return t.append(wA(r,n,o),u(e)),!1;if(e&&!r&&"object"==typeof e)if(rA.endsWith(n,"{}"))n=i?n:n.slice(0,-2),e=function(e,t){if(c===1/0)return JSON.stringify(e);const n=[];return JSON.stringify(e,(function(e,i){if(!rA.isObject(i))return i;for(;n.length&&n[n.length-1]!==this;)n.pop();return n.push(i),h(t+n.length-1),i}))}(e,1);else if(rA.isArray(e)&&function(e){return rA.isArray(e)&&!e.some(IA)}(e)||(rA.isFileList(e)||rA.endsWith(n,"[]"))&&(a=rA.toArray(e)))return n=AA(n),a.forEach((function(e,i){!rA.isUndefined(e)&&null!==e&&t.append(!0===s?wA([n],i,o):null===s?n:n+"[]",u(e))})),!1;return!!IA(e)||(t.append(wA(r,n,o),u(e)),!1)}const _=Object.assign(OA,{defaultVisitor:p,convertValue:u,isVisitable:IA});if(!rA.isObject(e))throw new TypeError("data must be an object");return function e(n,i){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;if(!rA.isUndefined(n)){if(h(o),-1!==l.indexOf(n))throw new Error("Circular reference detected in "+i.join("."));l.push(n),rA.forEach(n,(function(n,s){!0===(!(rA.isUndefined(n)||null===n)&&r.call(t,n,rA.isString(s)?zS(s).call(s):s,i,_))&&e(n,i?i.concat(s):[s],o+1)})),l.pop()}}(e),t}function DA(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(e).replace(/[!'()~]|%20/g,(function(e){return t[e]}))}function PA(e,t){this._pairs=[],e&&NA(e,this,t)}const LA=PA.prototype;function kA(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function MA(e,t,n){if(!t)return e;e=e||"";const i=rA.isFunction(n)?{serialize:n}:n,r=rA.getSafeProp(i,"encode")||kA,o=rA.getSafeProp(i,"serialize");let s;if(s=o?o(t,i):rA.isURLSearchParams(t)?t.toString():new PA(t,i).toString(r),s){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+s}return e}LA.append=function(e,t){this._pairs.push([e,t])},LA.toString=function(e){const t=e?t=>e.call(this,t,DA):DA;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};var UA=class{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!n&&n.synchronous,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){rA.forEach(this.handlers,(function(t){null!==t&&e(t)}))}},VA={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},xA={exports:{}},FA=Nn,BA=w,jA=Qt.f;FA({target:"Object",stat:!0,forced:Object.defineProperty!==jA,sham:!BA},{defineProperty:jA});var GA=$.Object,WA=xA.exports=function(e,t,n){return GA.defineProperty(e,t,n)};GA.defineProperty.sham&&(WA.sham=!0);var KA=n(xA.exports),HA=n(KT.f("iterator"));function YA(e){return YA="function"==typeof cC&&"symbol"==typeof HA?function(e){return typeof e}:function(e){return e&&"function"==typeof cC&&e.constructor===cC&&e!==cC.prototype?"symbol":typeof e},YA(e)}var XA=n(KT.f("toPrimitive"));function JA(e){var t=function(e,t){if("object"!==YA(e)||null===e)return e;var n=e[XA];if(void 0!==n){var i=n.call(e,t||"default");if("object"!==YA(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"===YA(t)?t:String(t)}function zA(e,t,n){return(t=JA(t))in e?KA(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var ZA=n(LE),qA={isBrowser:!0,classes:{URLSearchParams:void 0!==ZA?ZA:PA,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]};const QA="undefined"!=typeof window&&"undefined"!=typeof document,$A="object"==typeof navigator&&navigator||void 0,ew=QA&&(!$A||["ReactNative","NativeScript","NS"].indexOf($A.product)<0),tw="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,nw=QA&&window.location.href||"http://localhost";function iw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function rw(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?iw(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):iw(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var ow=rw(rw({},Object.freeze({__proto__:null,hasBrowserEnv:QA,hasStandardBrowserEnv:ew,hasStandardBrowserWebWorkerEnv:tw,navigator:$A,origin:nw})),qA);function sw(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function aw(e,t){return NA(e,new ow.classes.URLSearchParams,function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?sw(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sw(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({visitor:function(e,t,n,i){return ow.isNode&&rA.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}const cw=bA;function dw(e){if(e>cw)throw new CA("FormData field is too deeply nested ("+e+" levels). Max depth: "+cw,CA.ERR_FORM_DATA_DEPTH_EXCEEDED)}function lw(e){function t(e,n,i,r){dw(r);let o=e[r++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=r>=e.length;if(o=!o&&rA.isArray(i)?i.length:o,a)return rA.hasOwnProp(i,o)?i[o]=rA.isArray(i[o])?i[o].concat(n):[i[o],n]:i[o]=n,!s;rA.hasOwnProp(i,o)&&rA.isObject(i[o])||(i[o]=[]);return t(e,n,i[o],r)&&rA.isArray(i[o])&&(i[o]=function(e){const t={},n=Object.keys(e);let i;const r=n.length;let o;for(i=0;i<r;i++)o=n[i],t[o]=e[o];return t}(i[o])),!s}if(rA.isFormData(e)&&rA.isFunction(e.entries)){const n={};return rA.forEachEntry(e,((e,i)=>{t(function(e){const t=[],n=/[^.[\]]+|\[([^.[\]]*)]/g;let i;for(;null!==(i=n.exec(e));)dw(t.length),t.push("[]"===i[0]?"":i[1]||i[0]);return t}(e),i,n,0)})),n}return null}const uw=(e,t)=>null!=e&&rA.hasOwnProp(e,t)?e[t]:void 0;const hw={transitional:VA,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",i=n.indexOf("application/json")>-1,r=rA.isObject(e);r&&rA.isHTMLForm(e)&&(e=new FormData(e));if(rA.isFormData(e))return i?JSON.stringify(lw(e)):e;if(rA.isArrayBuffer(e)||rA.isBuffer(e)||rA.isStream(e)||rA.isFile(e)||rA.isBlob(e)||rA.isReadableStream(e))return e;if(rA.isArrayBufferView(e))return e.buffer;if(rA.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(r){const t=uw(this,"formSerializer");if(n.indexOf("application/x-www-form-urlencoded")>-1)return aw(e,t).toString();if((o=rA.isFileList(e))||n.indexOf("multipart/form-data")>-1){const n=uw(this,"env"),i=n&&n.FormData;return NA(o?{"files[]":e}:e,i&&new i,t)}}return r||i?(t.setContentType("application/json",!1),function(e,t,n){if(rA.isString(e))try{return(t||JSON.parse)(e),zS(rA).call(rA,e)}catch(e){if("SyntaxError"!==e.name)throw e}return(n||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=uw(this,"transitional")||hw.transitional,n=t&&t.forcedJSONParsing,i=uw(this,"responseType"),r="json"===i;if(rA.isResponse(e)||rA.isReadableStream(e))return e;if(e&&rA.isString(e)&&(n&&!i||r)){const n=!(t&&t.silentJSONParsing)&&r;try{return JSON.parse(e,uw(this,"parseReviver"))}catch(e){if(n){if("SyntaxError"===e.name)throw CA.from(e,CA.ERR_BAD_RESPONSE,this,null,uw(this,"response"));throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ow.classes.FormData,Blob:ow.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};rA.forEach(["delete","get","head","post","put","patch","query"],(e=>{hw.headers[e]={}}));var pw=hw;function _w(e,t){const n=this||pw,i=t||n,r=SA.from(i.headers);let o=i.data;return rA.forEach(e,(function(e){o=e.call(n,o,r.normalize(),t?t.status:void 0)})),r.normalize(),o}function Ew(e){return!(!e||!e.__CANCEL__)}var mw=class extends CA{constructor(e,t,n){super(null==e?"canceled":e,CA.ERR_CANCELED,t,n),this.name="CanceledError",this.__CANCEL__=!0}};function fw(e,t,n){const i=n.config.validateStatus;n.status&&i&&!i(n.status)?t(new CA("Request failed with status code "+n.status,n.status>=400&&n.status<500?CA.ERR_BAD_REQUEST:CA.ERR_BAD_RESPONSE,n.config,n.request,n)):e(n)}const gw=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3,i=0;const r=function(e,t){e=e||10;const n=new Array(e),i=new Array(e);let r,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),d=i[s];r||(r=c),n[o]=a,i[o]=c;let l=s,u=0;for(;l!==o;)u+=n[l++],l%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-r<t)return;const h=d&&c-d;return h?Math.round(1e3*u/h):void 0}}(50,250);return function(e,t){let n,i,r=0,o=1e3/t;const s=function(t){let o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();r=o,n=null,i&&(clearTimeout(i),i=null),e(...t)};return[function(){const e=Date.now(),t=e-r;for(var a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];t>=o?s(c,e):(n=c,i||(i=setTimeout((()=>{i=null,s(n)}),o-t)))},()=>n&&s(n)]}((n=>{if(!n||"number"!=typeof n.loaded)return;const o=n.loaded,s=n.lengthComputable?n.total:void 0,a=Math.max(0,null!=s?Math.min(o,s):o),c=Math.max(0,a-i),d=r(c);i=Math.max(i,a);e({loaded:a,total:s,progress:s?a/s:void 0,bytes:c,rate:d||void 0,estimated:d&&s?(s-a)/d:void 0,event:n,lengthComputable:null!=s,[t?"download":"upload"]:!0})}),n)},Sw=(e,t)=>{const n=null!=e;return[i=>t[0]({lengthComputable:n,total:e,loaded:i}),t[1]]},Tw=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:rA.asap;return function(){for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];return t((()=>e(...i)))}};var Rw=ow.hasStandardBrowserEnv?((e,t)=>n=>(n=new xg(n,ow.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new xg(ow.origin),ow.navigator&&/(msie|trident)/i.test(ow.navigator.userAgent)):()=>!0,vw=ow.hasStandardBrowserEnv?{write(e,t,n,i,r,o,s){if("undefined"==typeof document)return;const a=["".concat(e,"=").concat(encodeURIComponent(t))];rA.isNumber(n)&&a.push("expires=".concat(new Date(n).toUTCString())),rA.isString(i)&&a.push("path=".concat(i)),rA.isString(r)&&a.push("domain=".concat(r)),!0===o&&a.push("secure"),rA.isString(s)&&a.push("SameSite=".concat(s)),document.cookie=a.join("; ")},read(e){if("undefined"==typeof document)return null;const t=document.cookie.split(";");for(let n=0;n<t.length;n++){const i=t[n].replace(/^\s+/,""),r=i.indexOf("=");if(-1!==r&&i.slice(0,r)===e)try{return decodeURIComponent(i.slice(r+1))}catch(e){return i.slice(r+1)}}return null},remove(e){this.write(e,"",Date.now()-864e5,"/")}}:{write(){},read:()=>null,remove(){}};const yw=/^https?:(?!\/\/)/i,Cw=/[\t\n\r]/g;function bw(e){const t=e.replace(/^(https?:\/{0,2})[^/?#]*@/i,"$1".concat(TA,"@")),n=t.indexOf("#"),i=(-1===n?t:t.slice(0,n)).replace(/([?&][^=&#]*=)[^&#]*/g,"$1".concat(TA));return-1===n?i:"".concat(i,"#").concat((r=t.slice(n+1))?r.replace(/(^|&)([^=&]*=)?[^&]+/g,(function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return"".concat(t).concat(n).concat(TA)})):r);var r}function Iw(e,t){if("string"==typeof e){const n=function(e){return function(e){let t=0;for(;t<e.length&&e.charCodeAt(t)<=32;)t++;return e.slice(t)}(e).replace(Cw,"")}(e);if(yw.test(n))throw new CA("Invalid URL ".concat(JSON.stringify(bw(n)),': missing "//" after protocol'),CA.ERR_INVALID_URL,t)}}function Aw(e,t,n,i){Iw(t,i);let r=!function(e){return"string"==typeof e&&/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t);return e&&(r||!1===n)?(Iw(e,i),function(e,t){if(!t)return e;let n=e.length;for(;n>0&&47===e.charCodeAt(n-1);)n--;return e.slice(0,n)+"/"+t.replace(/^\/+/,"")}(e,t)):t}function ww(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Ow(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ww(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ww(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const Nw=e=>e instanceof SA?Ow({},e):e,Dw=e=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(e).concat(Object.getOwnPropertySymbols(e).filter((t=>Object.getOwnPropertyDescriptor(e,t).enumerable))):Object.keys(e);function Pw(e,t){e=e||{},t=t||{};const n=Object.create(null);function i(e,t,n,i){return rA.isPlainObject(e)&&rA.isPlainObject(t)?rA.merge.call({caseless:i},e,t):rA.isPlainObject(t)?rA.merge({},t):rA.isArray(t)?t.slice():t}function r(e,t,n,r){return rA.isUndefined(t)?rA.isUndefined(e)?void 0:i(void 0,e,0,r):i(e,t,0,r)}function o(e,t){if(!rA.isUndefined(t))return i(void 0,t)}function s(e,t){return rA.isUndefined(t)?rA.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(n,r,o){return rA.hasOwnProp(t,o)?i(n,r):rA.hasOwnProp(e,o)?i(void 0,n):void 0}Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,allowedSocketPaths:s,responseEncoding:s,validateStatus:a,headers:(e,t,n)=>r(Nw(e),Nw(t),0,!0)};return rA.forEach(Dw(Ow(Ow({},e),t)),(function(i){if("__proto__"===i||"constructor"===i||"prototype"===i)return;const o=rA.hasOwnProp(c,i)?c[i]:r,s=o(rA.hasOwnProp(e,i)?e[i]:void 0,rA.hasOwnProp(t,i)?t[i]:void 0,i);rA.isUndefined(s)&&o!==a||(n[i]=s)})),rA.hasOwnProp(t,"validateStatus")&&rA.isUndefined(t.validateStatus)&&!1===function(n){const i=rA.hasOwnProp(t,"transitional")?t.transitional:void 0;if(!rA.isUndefined(i)){if(!rA.isPlainObject(i))return;if(rA.hasOwnProp(i,n))return i[n]}const r=rA.hasOwnProp(e,"transitional")?e.transitional:void 0;if(rA.isPlainObject(r)&&rA.hasOwnProp(r,n))return r[n]}("validateStatusUndefinedResolves")&&(rA.hasOwnProp(e,"validateStatus")?n.validateStatus=i(void 0,e.validateStatus):delete n.validateStatus),n}const Lw=["content-type","content-length"];const kw=e=>encodeURIComponent(e).replace(/%([0-9A-F]{2})/gi,((e,t)=>String.fromCharCode(parseInt(t,16))));function Mw(e){const t=Pw({},e),n=e=>rA.hasOwnProp(t,e)?t[e]:void 0,i=n("data");let r=n("withXSRFToken");const o=n("xsrfHeaderName"),s=n("xsrfCookieName");let a=n("headers");const c=n("auth"),d=n("baseURL"),l=n("allowAbsoluteUrls"),u=n("url");if(t.headers=a=SA.from(a),t.url=MA(Aw(d,u,l,t),n("params"),n("paramsSerializer")),c){const t=rA.getSafeProp(c,"username")||"",n=rA.getSafeProp(c,"password")||"";try{a.set("Authorization","Basic "+btoa(t+":"+(n?kw(n):"")))}catch(t){throw CA.from(t,CA.ERR_BAD_OPTION_VALUE,e)}}if(rA.isFormData(i)&&(ow.hasStandardBrowserEnv||ow.hasStandardBrowserWebWorkerEnv||rA.isReactNative(i)?a.setContentType(void 0):rA.isFunction(i.getHeaders)&&function(e,t,n){"content-only"===n?Object.entries(t||{}).forEach((t=>{let n=KC(t,2),i=n[0],r=n[1];Ui(Lw).call(Lw,i.toLowerCase())&&e.set(i,r)})):e.set(t)}(a,i.getHeaders(),n("formDataHeaderPolicy"))),ow.hasStandardBrowserEnv){rA.isFunction(r)&&(r=r(t));if(!0===r||null==r&&Rw(t.url)){const e=o&&s&&vw.read(s);e&&a.set(o,e)}}return t}var Uw="undefined"!=typeof XMLHttpRequest&&function(e){return new cp((function(t,n){var i;const r=Mw(e);let o=r.data;const s=SA.from(r.headers).normalize();let a,c,d,l,u,h=r.responseType,p=r.onUploadProgress,_=r.onDownloadProgress;function E(){l&&l(),u&&u(),r.cancelToken&&r.cancelToken.unsubscribe(a),r.signal&&r.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=SA.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());fw((function(e){t(e),E()}),(function(e){n(e),E()}),{data:h&&"text"!==h&&"json"!==h?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}if(m.open(r.method.toUpperCase(),r.url,!0),m.timeout=r.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&m.responseURL.startsWith("file:"))&&setTimeout(f)},m.onabort=function(){m&&(n(new CA("Request aborted",CA.ECONNABORTED,e,m)),E(),m=null)},m.onerror=function(t){const i=t&&t.message?t.message:"Network Error",r=new CA(i,CA.ERR_NETWORK,e,m);r.event=t||null,n(r),E(),m=null},m.ontimeout=function(){let t=r.timeout?"timeout of "+r.timeout+"ms exceeded":"timeout exceeded";const i=r.transitional||VA;r.timeoutErrorMessage&&(t=r.timeoutErrorMessage),n(new CA(t,i.clarifyTimeoutError?CA.ETIMEDOUT:CA.ECONNABORTED,e,m)),E(),m=null},void 0===o&&s.setContentType(null),"setRequestHeader"in m&&rA.forEach(uA(s),(function(e,t){m.setRequestHeader(t,e)})),rA.isUndefined(r.withCredentials)||(m.withCredentials=!!r.withCredentials),h&&"json"!==h&&(m.responseType=r.responseType),_){var g=KC(gw(_,!0),2);d=g[0],u=g[1],m.addEventListener("progress",d)}if(p&&m.upload){var S=KC(gw(p),2);c=S[0],l=S[1],m.upload.addEventListener("progress",c),m.upload.addEventListener("loadend",l)}(r.cancelToken||r.signal)&&(a=t=>{m&&(n(!t||t.type?new mw(null,e,m):t),m.abort(),E(),m=null)},r.cancelToken&&r.cancelToken.subscribe(a),r.signal&&(r.signal.aborted?a():r.signal.addEventListener("abort",a)));const T=function(e){const t=/^([-+\w]{1,25}):(?:\/\/)?/.exec(e);return t&&t[1]||""}(r.url);if(T&&!Ui(i=ow.protocols).call(i,T))return n(new CA("Unsupported protocol "+T+":",CA.ERR_BAD_REQUEST,e)),void E();m.send(o||null)}))};var Vw=(e,t)=>{if(e=e?e.filter(Boolean):[],!t&&!e.length)return;const n=new AbortController;let i=!1;const r=function(e){if(!i){i=!0,s();const t=e instanceof Error?e:this.reason;n.abort(t instanceof CA?t:new mw(t instanceof Error?t.message:t))}};let o=t&&setTimeout((()=>{o=null,r(new CA("timeout of ".concat(t,"ms exceeded"),CA.ETIMEDOUT))}),t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(r):e.removeEventListener("abort",r)})),e=null)};e.forEach((e=>{i||(e.aborted?r.call(e):e.addEventListener("abort",r,{once:!0}))}));const a=n.signal;return a.unsubscribe=()=>rA.asap(s),a},xw=n(ap),Fw=KT.f("asyncIterator"),Bw=n(Fw);function jw(e,t){this.v=e,this.k=t}function Gw(e){var t,n;function i(t,n){try{var o=e[t](n),s=o.value,a=s instanceof jw;xw.resolve(a?s.v:s).then((function(n){if(a){var c="return"===t?"return":"next";if(!s.k||n.done)return i(c,n);n=e[c](n).value}r(o.done?"return":"normal",n)}),(function(e){i("throw",e)}))}catch(e){r("throw",e)}}function r(e,r){switch(e){case"return":t.resolve({value:r,done:!0});break;case"throw":t.reject(r);break;default:t.resolve({value:r,done:!1})}(t=t.next)?i(t.key,t.arg):n=null}this._invoke=function(e,r){return new xw((function(o,s){var a={key:e,arg:r,resolve:o,reject:s,next:null};n?n=n.next=a:(t=n=a,i(e,r))}))},"function"!=typeof e.return&&(this.return=void 0)}function Ww(e){return function(){return new Gw(e.apply(this,arguments))}}function Kw(e){return new jw(e,0)}function Hw(e){var t={},n=!1;function i(t,i){return n=!0,{done:!1,value:new jw(i=new xw((function(n){n(e[t](i))})),1)}}return t[void 0!==cC&&HA||"@@iterator"]=function(){return this},t.next=function(e){return n?(n=!1,e):i("next",e)},"function"==typeof e.throw&&(t.throw=function(e){if(n)throw n=!1,e;return i("throw",e)}),"function"==typeof e.return&&(t.return=function(e){return n?(n=!1,e):i("return",e)}),t}Gw.prototype["function"==typeof cC&&Bw||"@@asyncIterator"]=function(){return this},Gw.prototype.next=function(e){return this._invoke("next",e)},Gw.prototype.throw=function(e){return this._invoke("throw",e)},Gw.prototype.return=function(e){return this._invoke("return",e)};var Yw=n(Fw);function Xw(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=Yw,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new Jw(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function Jw(e){function t(e){if(Object(e)!==e)return cp.reject(new TypeError(e+" is not an object."));var t=e.done;return cp.resolve(e.value).then((function(e){return{value:e,done:t}}))}return Jw=function(e){this.s=e,this.n=e.next},Jw.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?cp.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?cp.reject(e):t(n.apply(this.s,arguments))}},new Jw(e)}const zw=function*(e,t){let n=e.byteLength;if(!t||n<t)return void(yield e);let i,r=0;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},Zw=function(){var e=Ww((function*(e,t){var n,i=!1,r=!1;try{for(var o,s=Xw(qw(e));i=!(o=yield Kw(s.next())).done;i=!1){const e=o.value;yield*Hw(Xw(zw(e,t)))}}catch(e){r=!0,n=e}finally{try{i&&null!=s.return&&(yield Kw(s.return()))}finally{if(r)throw n}}}));return function(t,n){return e.apply(this,arguments)}}(),qw=function(){var e=Ww((function*(e){if(e[Yw])return void(yield*Hw(Xw(e)));const t=e.getReader();try{for(;;){const e=yield Kw(t.read()),n=e.done,i=e.value;if(n)break;yield i}}finally{yield Kw(t.cancel())}}));return function(t){return e.apply(this,arguments)}}(),Qw=(e,t,n,i)=>{const r=Zw(e,t);let o,s=0,a=e=>{o||(o=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const t=await r.next(),i=t.done,o=t.value;if(i)return a(),void e.close();let c=o.byteLength;if(n){let e=s+=c;n(e)}e.enqueue(new Uint8Array(o))}catch(e){throw a(e),e}},cancel:e=>(a(e),r.return())},{highWaterMark:2})},$w=e=>e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102,eO=(e,t,n)=>t+2<n&&$w(e.charCodeAt(t+1))&&$w(e.charCodeAt(t+2)),tO=e=>e<=57?e-48:(223&e)-55,nO=e=>e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||43===e||47===e||45===e||95===e,iO=e=>{const t=e.length;let n=0,i=0,r=!1;for(let s=0;s<t;s++){let a=e.charCodeAt(s);37===a&&eO(e,s,t)&&(a=16*tO(e.charCodeAt(s+1))+tO(e.charCodeAt(s+2)),s+=2),9!==(o=a)&&10!==o&&12!==o&&13!==o&&32!==o&&(61!==a?!nO(a)||i>0?r=!0:n++:i++)}var o;return r||i>2||i>0&&(n+i)%4!=0||n%4==1?(e=>{const t=e.length;let n=0;return t>0&&61===e.charCodeAt(t-1)&&(n++,t>1&&61===e.charCodeAt(t-2)&&n++),Math.floor(3*(t-n)/4)})(e):(e=>{const t=e%4;return 3*Math.floor(e/4)+(2===t?1:3===t?2:0)})(n)},rO=(e,t)=>{if(!e||"string"!=typeof e)return 0;if(!e.startsWith("data:"))return 0;const n=e.indexOf(",");if(n<0)return 0;const i=e.slice(5,n),r=e.slice(n+1);if(/;base64/i.test(i))return t(r);let o=0;for(let e=0,t=r.length;e<t;e++){const n=r.charCodeAt(e);if(37===n&&eO(r,e,t))o+=1,e+=2;else if(n<128)o+=1;else if(n<2048)o+=2;else if(n>=55296&&n<=56319&&e+1<t){const t=r.charCodeAt(e+1);t>=56320&&t<=57343?(o+=4,e++):o+=3}else o+=3}return o};const oO="1.19.0";function sO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function aO(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?sO(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sO(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const cO=rA.isFunction,dO=e=>{if(!rA.isString(e))return e;try{return decodeURIComponent(e)}catch(t){return e}},lO=function(e){try{for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return!!e(...n)}catch(e){return!1}},uO=e=>{const t=void 0!==rA.global&&null!==rA.global?rA.global:Ub,n=t.ReadableStream,i=t.TextEncoder,r=e=rA.merge.call({skipUndefined:!0},{Request:t.Request,Response:t.Response},e),o=r.fetch,s=r.Request,a=r.Response,c=o?cO(o):"function"==typeof fetch,d=cO(s),l=cO(a);if(!c)return!1;const u=c&&cO(n),h=c&&("function"==typeof i?(p=new i,e=>p.encode(e)):async e=>new Uint8Array(await new s(e).arrayBuffer()));var p;const _=d&&u&&lO((()=>{let e=!1;const t=new s(ow.origin,{body:new n,method:"POST",get duplex(){return e=!0,"half"}}),i=t.headers.has("Content-Type");return null!=t.body&&t.body.cancel(),e&&!i})),E=l&&u&&lO((()=>rA.isReadableStream(new a("").body))),m={stream:E&&(e=>e.body)};c&&["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!m[e]&&(m[e]=(t,n)=>{let i=t&&t[e];if(i)return i.call(t);throw new CA("Response type '".concat(e,"' is not supported"),CA.ERR_NOT_SUPPORT,n)})}));const f=async e=>{if(null==e)return 0;if(rA.isBlob(e))return e.size;if(rA.isSpecCompliantForm(e)){const t=new s(ow.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return rA.isArrayBufferView(e)||rA.isArrayBuffer(e)?e.byteLength:(rA.isURLSearchParams(e)&&(e+=""),rA.isString(e)?(await h(e)).byteLength:void 0)};return async e=>{let t=Mw(e),n=t.url,r=t.method,c=t.data,l=t.signal,h=t.cancelToken,p=t.timeout,g=t.onDownloadProgress,S=t.onUploadProgress,T=t.responseType,R=t.headers,v=t.withCredentials,y=void 0===v?"same-origin":v,C=t.fetchOptions,b=t.maxContentLength,I=t.maxBodyLength;const A=rA.isNumber(b)&&b>-1,w=rA.isNumber(I)&&I>-1;let O=o||fetch;T=T?(T+"").toLowerCase():"text";let N=Vw([l,h&&h.toAbortSignal()],p),D=null;const P=N&&N.unsubscribe&&(()=>{N.unsubscribe()});let L,k=null;const M=()=>new CA("Request body larger than maxBodyLength limit",CA.ERR_BAD_REQUEST,e,D);try{let t;const o=(V="auth",rA.hasOwnProp(e,V)?e[V]:void 0);if(o){const e=rA.getSafeProp(o,"username")||"";t={username:e,password:rA.getSafeProp(o,"password")||""}}if((e=>{const t=e.indexOf("://");let n=e;return-1!==t&&(n=n.slice(t+3)),Ui(n).call(n,"@")||Ui(n).call(n,":")})(n)){const e=new xg(n,ow.origin);if(!t&&(e.username||e.password)){const n=dO(e.username);t={username:n,password:dO(e.password)}}(e.username||e.password)&&(e.username="",e.password="",n=e.href)}if(t&&(R.delete("authorization"),R.set("Authorization","Basic "+btoa((U=(t.username||"")+":"+(t.password||""),encodeURIComponent(U).replace(/%([0-9A-F]{2})/gi,((e,t)=>String.fromCharCode(parseInt(t,16)))))))),A&&"string"==typeof n&&n.startsWith("data:")){const t=function(e){const t="string"==typeof e?e.indexOf("#"):-1;return rO(-1===t?e:e.slice(0,t),iO)}(n);if(t>b)throw new CA("maxContentLength size of "+b+" exceeded",CA.ERR_BAD_RESPONSE,e,D)}if(w&&"get"!==r&&"head"!==r){const e=await f(c);if("number"==typeof e&&isFinite(e)&&(L=e,e>I))throw M()}const l=w&&(rA.isReadableStream(c)||rA.isStream(c)),h=(e,t,n)=>Qw(e,65536,(e=>{if(w&&e>I)throw k=M();t&&t(e)}),n);if(_&&"get"!==r&&"head"!==r&&(S||l)){if(L=null==L?await(async(e,t)=>{const n=rA.toFiniteNumber(e.getContentLength());return null==n?f(t):n})(R,c):L,0!==L||l){let e,t=new s(n,{method:"POST",body:c,duplex:"half"});if(rA.isFormData(c)&&(e=t.headers.get("content-type"))&&R.setContentType(e),t.body){const e=KC(S&&Sw(L,gw(Tw(S)))||[],2),n=e[0],i=e[1];c=h(t.body,n,i)}}}else if(l&&!d&&u&&"get"!==r&&"head"!==r)c=h(c);else if(l&&d&&!_&&"get"!==r&&"head"!==r)throw new CA("Stream request bodies are not supported by the current fetch implementation",CA.ERR_NOT_SUPPORT,e,D);rA.isString(y)||(y=y?"include":"omit");const p=d&&"credentials"in s.prototype;if(rA.isFormData(c)){const e=R.getContentType();e&&/^multipart\/form-data/i.test(e)&&!/boundary=/i.test(e)&&R.delete("content-type")}R.set("User-Agent","axios/"+oO,!1);const v=aO(aO({},C),{},{signal:N,method:r.toUpperCase(),headers:uA(R.normalize()),body:c,duplex:"half",credentials:p?y:void 0});D=d&&new s(n,v);let x=await(d?O(D,C):O(n,v));const F=SA.from(x.headers);if(A){const t=rA.toFiniteNumber(F.getContentLength());if(null!=t&&t>b)throw new CA("maxContentLength size of "+b+" exceeded",CA.ERR_BAD_RESPONSE,e,D)}const B=E&&("stream"===T||"response"===T);if(E&&x.body&&(g||A||B&&P)){const t={};["status","statusText","headers"].forEach((e=>{t[e]=x[e]}));const n=rA.toFiniteNumber(F.getContentLength()),i=KC(g&&Sw(n,gw(Tw(g),!0))||[],2),r=i[0],o=i[1];let s=0;const c=t=>{if(A&&(s=t,s>b))throw new CA("maxContentLength size of "+b+" exceeded",CA.ERR_BAD_RESPONSE,e,D);r&&r(t)};x=new a(Qw(x.body,65536,c,(()=>{o&&o(),P&&P()})),t)}T=T||"text";let j=await m[rA.findKey(m,T)||"text"](x,e);if(A&&!E&&!B){let t;if(null!=j&&("number"==typeof j.byteLength?t=j.byteLength:"number"==typeof j.size?t=j.size:"string"==typeof j&&(t="function"==typeof i?(new i).encode(j).byteLength:j.length)),"number"==typeof t&&t>b)throw new CA("maxContentLength size of "+b+" exceeded",CA.ERR_BAD_RESPONSE,e,D)}return!B&&P&&P(),await new cp(((t,n)=>{fw(t,n,{data:j,headers:SA.from(x.headers),status:x.status,statusText:x.statusText,config:e,request:D})}))}catch(t){if(P&&P(),N&&N.aborted&&N.reason instanceof CA){const n=N.reason;throw n.config=e,D&&(n.request=D),t!==n&&Object.defineProperty(n,"cause",{__proto__:null,value:t,writable:!0,enumerable:!1,configurable:!0}),n}if(k)throw D&&!k.request&&(k.request=D),k;if(t instanceof CA)throw D&&!t.request&&(t.request=D),t;if(t&&"TypeError"===t.name&&/Load failed|fetch/i.test(t.message)){const n=new CA("Network Error",CA.ERR_NETWORK,e,D,t&&t.response);throw Object.defineProperty(n,"cause",{__proto__:null,value:t.cause||t,writable:!0,enumerable:!1,configurable:!0}),n}throw CA.from(t,t&&t.code,e,D,t&&t.response)}var U,V}},hO=new Map,pO=e=>{let t=e&&e.env||{};const n=t.fetch,i=[t.Request,t.Response,n];let r,o,s=i.length,a=hO;for(;s--;)r=i[s],o=a.get(r),void 0===o&&a.set(r,o=s?new Map:uO(t)),a=o;return o};pO();const _O={http:null,xhr:Uw,fetch:{get:pO}};rA.forEach(_O,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{__proto__:null,value:t})}catch(e){}Object.defineProperty(e,"adapterName",{__proto__:null,value:t})}}));const EO=e=>"- ".concat(e),mO=e=>rA.isFunction(e)||null===e||!1===e;var fO={getAdapter:function(e,t){const n=(e=rA.isArray(e)?e:[e]).length;let i,r;const o={};for(let s=0;s<n;s++){let n;if(i=e[s],r=i,!mO(i)&&(r=_O[(n=String(i)).toLowerCase()],void 0===r))throw new CA("Unknown adapter '".concat(n,"'"));if(r&&(rA.isFunction(r)||(r=r.get(t))))break;o[n||"#"+s]=r}if(!r){const e=Object.entries(o).map((e=>{let t=KC(e,2),n=t[0],i=t[1];return"adapter ".concat(n," ")+(!1===i?"is not supported by the environment":"is not available in the build")}));let t=n?e.length>1?"since :\n"+e.map(EO).join("\n"):" "+EO(e[0]):"as no adapter specified";throw new CA("There is no suitable adapter to dispatch the request "+t,CA.ERR_NOT_SUPPORT)}return r},adapters:_O};function gO(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new mw(null,e)}function SO(e){gO(e),e.headers=SA.from(e.headers),e.data=_w.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return fO.getAdapter(e.adapter||pw.adapter,e)(e).then((function(t){gO(e),e.response=t;try{t.data=_w.call(e,e.transformResponse,t)}finally{delete e.response}return t.headers=SA.from(t.headers),t}),(function(t){if(!Ew(t)&&(gO(e),t&&t.response)){e.response=t.response;try{t.response.data=_w.call(e,e.transformResponse,t.response)}finally{delete e.response}t.response.headers=SA.from(t.response.headers)}return cp.reject(t)}))}const TO={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{TO[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));const RO={};TO.transitional=function(e,t,n){function i(e,t){return"[Axios v"+oO+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return(n,r,o)=>{if(!1===e)throw new CA(i(r," has been removed"+(t?" in "+t:"")),CA.ERR_DEPRECATED);return t&&!RO[r]&&(RO[r]=!0,console.warn(i(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,o)}},TO.spelling=function(e){return(t,n)=>(console.warn("".concat(n," is likely a misspelling of ").concat(e)),!0)};var vO={assertOptions:function(e,t,n){if("object"!=typeof e||null===e)throw new CA("options must be an object",CA.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let r=i.length;for(;r-- >0;){const o=i[r],s=Object.prototype.hasOwnProperty.call(t,o)?t[o]:void 0;if(s){const t=e[o],n=void 0===t||s(t,o,e);if(!0!==n)throw new CA("option "+o+" must be "+n,CA.ERR_BAD_OPTION_VALUE)}else if(!0!==n)throw new CA("Unknown option "+o,CA.ERR_BAD_OPTION)}},validators:TO};const yO=vO.validators;let CO=class{constructor(e){this.defaults=e||{},this.interceptors={request:new UA,response:new UA}}async request(e,t){try{return await this._request(e,t)}catch(e){if(e instanceof Error){let t={};Error.captureStackTrace?Error.captureStackTrace(t):t=new Error;const n=(()=>{if(!t.stack)return"";const e=t.stack.indexOf("\n");return-1===e?"":t.stack.slice(e+1)})();try{if(e.stack){if(n){const t=n.indexOf("\n"),i=-1===t?-1:n.indexOf("\n",t+1),r=-1===i?"":n.slice(i+1);String(e.stack).endsWith(r)||(e.stack+="\n"+n)}}else e.stack=n}catch(e){}}throw e}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{};const n=t=Pw(this.defaults,t),i=n.transitional,r=n.paramsSerializer,o=n.headers;void 0!==i&&vO.assertOptions(i,{silentJSONParsing:yO.transitional(yO.boolean),forcedJSONParsing:yO.transitional(yO.boolean),clarifyTimeoutError:yO.transitional(yO.boolean),legacyInterceptorReqResOrdering:yO.transitional(yO.boolean),advertiseZstdAcceptEncoding:yO.transitional(yO.boolean),validateStatusUndefinedResolves:yO.transitional(yO.boolean)},!1),null!=r&&(rA.isFunction(r)?t.paramsSerializer={serialize:r}:vO.assertOptions(r,{encode:yO.function,serialize:yO.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),vO.assertOptions(t,{baseUrl:yO.spelling("baseURL"),withXsrfToken:yO.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let s=o&&rA.merge(o.common,o[t.method]);o&&rA.forEach(["delete","get","head","post","put","patch","query","common"],(e=>{delete o[e]})),t.headers=SA.concat(s,o);const a=[];let c=!0;this.interceptors.request.forEach((function(e){if("function"==typeof e.runWhen&&!1===e.runWhen(t))return;c=c&&e.synchronous;const n=t.transitional||VA;n&&n.legacyInterceptorReqResOrdering?a.unshift(e.fulfilled,e.rejected):a.push(e.fulfilled,e.rejected)}));const d=[];let l;this.interceptors.response.forEach((function(e){d.push(e.fulfilled,e.rejected)}));let u,h=0;if(!c){const e=[SO.bind(this),void 0];for(e.unshift(...a),e.push(...d),u=e.length,l=cp.resolve(t);h<u;)l=l.then(e[h++],e[h++]);return l}u=a.length;let p=t;for(;h<u;){const e=a[h++],t=a[h++];try{p=e?e(p):p}catch(e){if(!t){l=cp.reject(e);break}try{const n=t.call(this,e);rA.isThenable(n)&&(l=cp.resolve(n).then((()=>SO.call(this,p))))}catch(e){l=cp.reject(e)}break}}if(!l)try{l=SO.call(this,p)}catch(e){l=cp.reject(e)}for(h=0,u=d.length;h<u;)l=l.then(d[h++],d[h++]);return l}getUri(e){return MA(Aw((e=Pw(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls,e),e.params,e.paramsSerializer)}};rA.forEach(["delete","get","head","options"],(function(e){CO.prototype[e]=function(t,n){return this.request(Pw(n||{},{method:e,url:t,data:n&&rA.hasOwnProp(n,"data")?n.data:void 0}))}})),rA.forEach(["post","put","patch","query"],(function(e){function t(t){return function(n,i,r){return this.request(Pw(r||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:n,data:i}))}}CO.prototype[e]=t(),"query"!==e&&(CO.prototype[e+"Form"]=t(!0))}));var bO=CO;class IO{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new cp((function(e){t=e}));const n=this;this.promise.then((e=>{if(!n._listeners)return;let t=n._listeners.length;for(;t-- >0;)n._listeners[t](e);n._listeners=null})),this.promise.then=e=>{let t;const i=new cp((e=>{n.subscribe(e),t=e})).then(e);return i.cancel=function(){n.unsubscribe(t)},i},e((function(e,i,r){n.reason||(n.reason=new mw(e,i,r),t(n.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;const t=new IO((function(t){e=t}));return{token:t,cancel:e}}}var AO=IO;const wO={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(wO).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1];wO[i]=n}));var OO=wO;const NO=function e(t){const n=new bO(t),i=aI(bO.prototype.request,n);return rA.extend(i,bO.prototype,n,{allOwnKeys:!0}),rA.extend(i,n,null,{allOwnKeys:!0}),i.create=function(n){return e(Pw(t,n))},i}(pw);NO.Axios=bO,NO.CanceledError=mw,NO.CancelToken=AO,NO.isCancel=Ew,NO.VERSION=oO,NO.toFormData=NA,NO.AxiosError=CA,NO.Cancel=NO.CanceledError,NO.all=function(e){return cp.all(e)},NO.spread=function(e){return function(t){return e.apply(null,t)}},NO.isAxiosError=function(e){return rA.isObject(e)&&!0===e.isAxiosError},NO.mergeConfig=Pw,NO.AxiosHeaders=SA,NO.formToJSON=e=>lw(rA.isHTMLForm(e)?new FormData(e):e),NO.getAdapter=fO.getAdapter,NO.HttpStatusCode=OO,NO.default=NO;var DO=NO;DO.Axios,DO.AxiosError,DO.CanceledError,DO.isCancel,DO.CancelToken,DO.VERSION,DO.all,DO.Cancel,DO.isAxiosError,DO.spread,DO.toFormData,DO.AxiosHeaders,DO.HttpStatusCode,DO.formToJSON,DO.getAdapter,DO.mergeConfig,DO.create;const PO=()=>{};function LO(){const e={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:PO};return e.promise=new cp(((t,n)=>{e.resolve=n=>{e.isFinished||(e.isResolved=!0,e.isFinished=!0,t(n),e.value=n)},e.reject=t=>{e.isFinished||(e.isRejected=!0,e.isFinished=!0,n(t))}})),e}const kO=new Map,MO=new Map,UO=new Map;let VO=function(e){return e.WIN_10="Windows 10",e.WIN_81="Windows 8.1",e.WIN_8="Windows 8",e.WIN_7="Windows 7",e.WIN_VISTA="Windows Vista",e.WIN_SERVER_2003="Windows Server 2003",e.WIN_XP="Windows XP",e.WIN_2000="Windows 2000",e.ANDROID="Android",e.HARMONY_OS="HarmonyOS",e.OPEN_BSD="Open BSD",e.SUN_OS="Sun OS",e.LINUX="Linux",e.IOS="iOS",e.MAC_OS="Mac OS",e.CHROMIUM_OS="Chromium OS",e.QNX="QNX",e.UNIX="UNIX",e.BEOS="BeOS",e.OS_2="OS/2",e.SEARCH_BOT="Search Bot",e}({}),xO=function(e){return e.CHROME="Chrome",e.SAFARI="Safari",e.EDGE="Edge",e.FIREFOX="Firefox",e.OPERA="OPR",e.QQ="QQBrowser",e.WECHAT="MicroMessenger",e}({});const FO=new xb;let BO=FO.getResult(),jO=null;function GO(e){if(!jO){e&&FO.setUA(e),BO=FO.getResult();const t=function(e){if("Blink"===e.engine.name&&"WeChat"!==e.browser.name)return xO.CHROME;switch(e.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return xO.CHROME;case"Safari":case"Mobile Safari":return xO.SAFARI;case"Edge":return xO.EDGE;case"Firefox":return xO.FIREFOX;case"QQ":case"QQBrowser":return xO.QQ;case"Opera":return xO.OPERA;case"WeChat":return xO.WECHAT;default:return e.browser.name||""}}(BO),n=WO(BO),i=function(e){return"Windows"===e.os.name?e.os.version?e.os.name+" "+e.os.version:e.os.name:e.os.name||""}(BO),r=BO.os.version,o=WO(BO,!1),s=BO.device.type;if(!(t&&n&&i&&r))return{name:t,version:n,os:i,osVersion:r,browserVersion:o,deviceType:s};jO={name:t,version:n,os:i,osVersion:r,browserVersion:o,deviceType:s}}return jO}function WO(e){let t,n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return t="Blink"===e.engine.name?e.engine.version||"":e.browser.version||"",n?t.split(".")[0]:t}function KO(){return GO().os}function HO(){const e=GO();return"".concat(e.os," ").concat(e.osVersion)}function YO(){const e=GO();return!!("WebKit"===BO.engine.name&&e.os===VO.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&e.name!==xO.SAFARI||eN()&&e.name!==xO.SAFARI)}function XO(){return"WebKit"===BO.engine.name}function JO(){return GO().name===xO.CHROME}function zO(){return GO().name===xO.SAFARI}function ZO(){const e=GO();if(e.name!==xO.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>15||15===Number(t[0])&&Number(t[1])>=4}function qO(){const e=GO();if(e.name!==xO.SAFARI||!e.browserVersion)return!1;const t=e.browserVersion.split(".");return Number(t[0])>18||18===Number(t[0])&&Number(t[1])>=4}function QO(){return GO().name===xO.EDGE}function $O(){return GO().name===xO.FIREFOX}function eN(){return GO().os===VO.IOS}function tN(e){const t=GO();return!(t.name!==xO.CHROME||!t.osVersion)&&Number(t.version)>=e}function nN(e){const t=GO();return!(t.name!==xO.CHROME||!t.osVersion)&&Number(t.version)<e}function iN(e,t,n){const i=GO();return!(i.name!==e||!i.osVersion)&&(n?Number(i.version)>=t&&Number(i.version)<=n:Number(i.version)===t)}function rN(e){const t=GO();return!(t.name!==xO.EDGE||!t.osVersion)&&Number(t.version)>=e}function oN(e){const t=GO();return!(t.name!==xO.FIREFOX||!t.osVersion)&&Number(t.version)>=e}function sN(e){const t=GO();return!(t.name!==xO.SAFARI||!t.osVersion)&&Number(t.version)>=e}function aN(e,t,n){const i=GO();if(i.os!==VO.IOS||!i.osVersion)return!1;const r=i.osVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])>t||Number(r[0])>e:t?Number(r[0])===e&&Number(r[1])>=t||Number(r[0])>e:Number(r[0])>=e}function cN(e,t,n){const i=GO();if(i.os!==VO.IOS||!i.osVersion)return!1;const r=i.osVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function dN(e,t,n){const i=GO();if(i.name!==xO.SAFARI||!i.osVersion||!i.browserVersion)return!1;const r=i.browserVersion.split(".");return n?t&&Number(r[0])===e&&Number(r[1])<t||Number(r[0])<e:t?Number(r[0])===e&&Number(r[1])<=t||Number(r[0])<e:Number(r[0])<=e}function lN(e){const t=GO();return!(t.name!==xO.OPERA||!t.osVersion)&&Number(t.version)>=e}function uN(){const e=GO();if(e.os!==VO.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return Number(t[0])<14||14===Number(t[0])&&Number(t[1])<=6}function hN(){const e=GO();if(e.os!==VO.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])}function pN(){const e=GO();if(e.os!==VO.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 16===Number(t[0])}function _N(){const e=GO();if(e.os!==VO.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=1}function EN(){return zO()&&navigator.maxTouchPoints>0}function mN(){return GO().name===xO.WECHAT}function fN(){return window.navigator.appVersion&&null!==window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function gN(){const e=KO();return function(){const e=GO().deviceType;return"mobile"===e||"tablet"===e}()||e===VO.ANDROID||e===VO.IOS||e===VO.HARMONY_OS}function SN(){const e=GO();return e.name!==xO.EDGE&&e.name!==xO.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function TN(){return KO()===VO.ANDROID}function RN(){const e=GO();return TN()&&(e.name===xO.CHROME||e.name===xO.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function vN(){var e;return!!Ui(e=window.navigator.userAgent).call(e,"AgoraWebView")}function yN(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function CN(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function bN(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function IN(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?bN(Object(n),!0).forEach((function(t){CN(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):bN(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function AN(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return yN(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?yN(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}let wN=function(e){return e.UNEXPECTED_ERROR="UNEXPECTED_ERROR",e.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",e.PB_ERROR="PB_ERROR",e.TIMEOUT="TIMEOUT",e.INVALID_PARAMS="INVALID_PARAMS",e.NOT_READABLE="NOT_READABLE",e.NOT_SUPPORTED="NOT_SUPPORTED",e.INVALID_OPERATION="INVALID_OPERATION",e.OPERATION_ABORTED="OPERATION_ABORTED",e.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",e.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",e.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",e.DATACHANNEL_FAILED="DATACHANNEL_FAILED",e.NETWORK_ERROR="NETWORK_ERROR",e.NETWORK_TIMEOUT="NETWORK_TIMEOUT",e.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",e.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",e.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",e.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",e.ELECTRON_IS_NULL="ELECTRON_IS_NULL",e.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",e.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",e.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",e.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",e.TRACK_IS_DISABLED="TRACK_IS_DISABLED",e.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",e.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",e.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",e.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",e.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",e.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",e.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",e.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",e.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",e.UID_CONFLICT="UID_CONFLICT",e.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",e.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",e.INVALID_TRACK="INVALID_TRACK",e.SENDER_NOT_FOUND="SENDER_NOT_FOUND",e.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",e.SET_ANSWER_FAILED="SET_ANSWER_FAILED",e.ICE_FAILED="ICE_FAILED",e.PC_CLOSED="PC_CLOSED",e.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",e.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",e.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",e.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",e.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",e.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",e.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",e.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",e.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",e.INVALID_REMOTE_USER="INVALID_REMOTE_USER",e.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",e.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",e.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",e.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",e.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",e.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",e.WS_ABORT="WS_ABORT",e.WS_DISCONNECT="WS_DISCONNECT",e.WS_ERR="WS_ERR",e.EXTERNAL_SIGNAL_ABORT="EXTERNAL_SIGNAL_ABORT",e.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",e.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",e.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",e.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",e.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",e.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",e.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",e.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",e.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",e.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",e.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",e.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",e.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",e.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",e.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",e.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",e.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",e.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",e.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",e.INVALID_PLUGIN="INVALID_PLUGIN",e.DISCONNECT_P2P="DISCONNECT_P2P",e.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",e.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",e.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",e.CREATE_DATACHANNEL_ERROR="CREATE_DATACHANNEL_ERROR",e.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",e.PROHIBITED_OPERATION="PROHIBITED_OPERATION",e.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED",e.P2P_MESSAGE_FAILED="P2P_MESSAGE_FAILED",e}({}),ON=class extends Error{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2?arguments[2]:void 0;super(t),CN(this,"code",void 0),CN(this,"message",void 0),CN(this,"data",void 0),CN(this,"name","AgoraRTCException"),this.code=e,this.message="AgoraRTCError ".concat(this.code,": ").concat(t),this.data=n}toString(){return this.data?"".concat(this.message,"\ndata: ").concat(JSON.stringify(this.data)):this.message}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error",t=arguments.length>1?arguments[1]:void 0;return"error"===e&&(t||console).error(this.toString()),"warning"===e&&(t||console).warn(this.toString()),this}throw(e){throw this.print("error",e),this}};function NN(e,t){if("boolean"!=typeof e)throw new ON(wN.INVALID_PARAMS,"Invalid ".concat(t,": The value is of the boolean type."))}function DN(e,t,n){if(!Ui(n).call(n,e))throw new ON(wN.INVALID_PARAMS,"".concat(t," can only be set as ").concat(JSON.stringify(n)))}function PN(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e4;if(e<n||e>i||(!(arguments.length>4&&void 0!==arguments[4])||arguments[4])&&!function(e){return"number"==typeof e&&e%1==0}(e))throw new ON(wN.INVALID_PARAMS,"invalid ".concat(t,": the value range is [").concat(n,", ").concat(i,"]. integer only"))}function LN(e,t){if("number"!=typeof e){if(!(e.min||e.max||e.ideal||e.exact))throw new ON(wN.INVALID_PARAMS,"".concat(t," is not a valid ConstrainLong"));void 0!==e.min&&PN(e.min,"".concat(t,".min"),0,1/0),void 0!==e.max&&PN(e.max,"".concat(t,".max"),1,1/0),void 0!==e.exact&&PN(e.exact,"".concat(t,".exact"),1,1/0),void 0!==e.ideal&&PN(e.ideal,"".concat(t,".ideal"),1,1/0)}else PN(e,t,1,1/0)}function kN(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:255,r=!(arguments.length>4&&void 0!==arguments[4])||arguments[4];if(null==e)throw new ON(wN.INVALID_PARAMS,"".concat(t||"param"," cannot be empty"));if(!VN(e,n,i,r))throw new ON(wN.INVALID_PARAMS,"Invalid ".concat(t||"string param",": Length of the string: [").concat(n,",").concat(i,"].").concat(r?" ASCII characters only.":""))}function MN(e,t){if(!Array.isArray(e))throw new ON(wN.INVALID_PARAMS,"".concat(t," should be an array"))}function UN(e){return null==e}function VN(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:255,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];return"string"==typeof e&&e.length<=n&&e.length>=t&&(!i||function(e){if("string"!=typeof e)return!1;for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(n<0||n>255)return!1}return!0}(e))}function xN(e,t,n){if("getBigUint64"in DataView.prototype)return e.getBigUint64(t,n);const i=e.getUint32(t,n),r=e.getUint32(t+4,n),o=Number(!!n),s=Number(!n);return BigInt(i*s+r*o)<<BigInt(32)|BigInt(i*o+r*s)}function FN(e,t,n,i){if("setBigUint64"in DataView.prototype)return e.setBigUint64(t,n,i);const r=Number(n>>BigInt(32)),o=Number(n&BigInt(4294967295));i?(e.setUint32(t+4,r,i),e.setUint32(t,o,i)):(e.setUint32(t,r,i),e.setUint32(t+4,o,i))}var BN=function(e){return e.COVERED="COVERED",e.POSITION="POSITION",e.SIZE="SIZE",e.STYLE="STYLE",e}(BN||{}),jN=function(e){return e.UNMOUNTED="UNMOUNTED",e.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",e}(jN||{});const GN=new class{constructor(){CN(this,"_clientSize",null),CN(this,"getClientWidth",(()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth)),CN(this,"getClientHeight",(()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight)),CN(this,"getStyle",(e=>window.getComputedStyle(e,null))),CN(this,"checkCssVisibleProperty",(e=>{var t;let n=!0;const i=this.getStyle(e),r=i.display,o=i.visibility,s=i.opacity,a=i.filter;return("none"===r||Ui(t=["hidden","collapse"]).call(t,o)||Number(s)<.1)&&(n=!1),!!n&&(a&&a.split(" ").filter((e=>{var t;const n=e.split("(")[0];return Ui(t=["brightness","blur","opacity"]).call(t,n)})).map((e=>{const t=AN(e.split(/\(|\)/),2),n=t[0],i=t[1];return[n,Number(i.match(/^[0-9\.]+/))]})).forEach((e=>{const t=AN(e,2),i=t[0],r=t[1];switch(i){case"brightness":(r<.1||r>3)&&(n=!1);break;case"blur":r>3&&(n=!1);break;case"opacity":r<.1&&(n=!1)}})),n)})),CN(this,"checkPropertyUpToAllParentNodes",((e,t)=>{let n=!0,i=!0;const r=e=>t(e);let o=e;for(;o&&i;)r(o)||(n=!1,i=!1),o=o.parentElement,o||(i=!1);return n})),CN(this,"checkActualCssVisibleIncludeInherit",(e=>this.checkPropertyUpToAllParentNodes(e,this.checkCssVisibleProperty))),CN(this,"getSizeAboutClient",(e=>{const t=e.getBoundingClientRect(),n=t.width,i=t.height,r=t.left,o=t.right,s=t.top,a=t.bottom,c=this.getClientWidth(),d=this.getClientHeight();return{width:n,height:i,left:r,right:o,top:s,bottom:a,clientWidth:c,clientHeight:d,clientMin:Math.min(c,d)}})),CN(this,"checkActualSize",(()=>{const e=this._clientSize,t=e.width,n=e.height,i=e.clientMin;return this.checkSizeIsVisible(t,n,i)})),CN(this,"elementFromPoint",((e,t)=>document.elementFromPoint?document.elementFromPoint(e,t):null)),CN(this,"checkCoverForAPoint",((e,t,n)=>{const i=this.elementFromPoint(e,t);return null!==i&&i!==n})),CN(this,"getPointPositionList",(()=>{const e=this._clientSize,t=e.width,n=e.height,i=e.left,r=e.top,o=t/6,s=n/6,a=[],c=10**6;for(let e=0;e<5;e++)for(let t=0;t<5;t++){const n=(i*c+(0===e?.1:4===e?(o*e*c-1e5)/c:o*e)*c)/c,d=(r*c+(0===t?.1:4===t?(s*t*c-1e5)/c:s*t)*c)/c;a.push({x:n,y:d})}return[...a]})),CN(this,"checkElementCover",(e=>this.getPointPositionList().map((t=>this.checkCoverForAPoint(t.x,t.y,e))).filter((e=>!!e)).length>6)),CN(this,"checkSizeIsVisible",((e,t,n)=>(e>50||n/e<=10)&&(t>50||n/t<=10))),CN(this,"checkSizeOfPartInClient",(()=>{const e=this._clientSize,t=e.left,n=e.right,i=e.top,r=e.bottom,o=e.clientHeight,s=e.clientWidth,a=e.clientMin;let c,d,l,u;if(t<0)c=0;else{if(!(t<s))return!1;c=t}if(n<0)return!1;if(d=n<s?n:s,i<0)l=0;else{if(!(i<o))return!1;l=i}if(r<0)return!1;u=r<o?r:o;const h=d-c,p=u-l;return this.checkSizeIsVisible(h,p,a)})),CN(this,"returnHiddenResult",(e=>(this._clientSize=null,{visible:!1,reason:e}))),CN(this,"checkOneElementVisible",(e=>{if(e instanceof HTMLElement){if(this.checkElementIsMountedOnDom(e)){if(this.checkActualCssVisibleIncludeInherit(e)){if(this._clientSize=this.getSizeAboutClient(e),this.checkElementCover(e))return this.returnHiddenResult(BN.COVERED);{const e=this.checkActualSize(),t=this.checkSizeOfPartInClient();return e&&!t?this.returnHiddenResult(BN.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(BN.SIZE)}}return this.returnHiddenResult(BN.STYLE)}return this.returnHiddenResult(jN.UNMOUNTED)}return this.returnHiddenResult(jN.INVALID_HTML_ELEMENT)})),CN(this,"checkElementIsMountedOnDom",(e=>this.checkPropertyUpToAllParentNodes(e,(e=>"HTML"!==e.nodeName.toUpperCase()?null!==e.parentElement:!!document.documentElement))))}};function WN(e){return(new TextEncoder).encode(e)}const KN=function(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n};const HN=async e=>function(e,t){let n="";return new Uint8Array(e).forEach((e=>{n+=e.toString(t).padStart(2,"0")})),n}(await crypto.subtle.digest("SHA-256",WN(e)),16);let YN=class{constructor(){CN(this,"_events",{}),CN(this,"addListener",this.on)}getListeners(e){return this._events[e]?this._events[e].map((e=>e.listener)):[]}on(e,t){this._events[e]||(this._events[e]=[]);const n=this._events[e];-1===this._indexOfListener(n,t)&&n.push({listener:t,once:!1})}once(e,t){this._events[e]||(this._events[e]=[]);const n=this._events[e];-1===this._indexOfListener(n,t)&&n.push({listener:t,once:!0})}off(e,t){if(!this._events[e])return;const n=this._events[e],i=this._indexOfListener(n,t);-1!==i&&n.splice(i,1),0===this._events[e].length&&delete this._events[e]}removeAllListeners(e){e?delete this._events[e]:this._events={}}emit(e){this._events[e]||(this._events[e]=[]);const t=this._events[e].map((e=>e));for(var n=arguments.length,i=new Array(n>1?n-1:0),r=1;r<n;r++)i[r-1]=arguments[r];for(let n=0;n<t.length;n+=1){const r=t[n];r.once&&this.off(e,r.listener),r.listener.apply(this,i||[])}}safeEmit(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];[...this._events[e]||[]].forEach((t=>{t.once&&this.off(e,t.listener);try{t.listener.apply(this,n)}catch(t){console.error("safeEmit event:".concat(e," error ").concat(null==t?void 0:t.toString()))}}))}_indexOfListener(e,t){let n=e.length;for(;n--;)if(e[n].listener===t)return n;return-1}};let XN=null;function JN(){if(XN)return XN;if(window.electron)return XN=window.electron;if(!window.require)return null;try{return XN=window.require("electron"),XN}catch(e){return null}}let zN=function(e){return e.CREATE_CLIENT="createClient",e.CREATE_CLIENT_PRECONNECT="createClientPreconnect",e.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",e.SET_AREA="setArea",e.PRELOAD="PRELOAD",e.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",e.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",e.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",e.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",e.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",e.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",e.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",e.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",e.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",e.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",e.START_PROXY_SERVER="Client.startProxyServer",e.STOP_PROXY_SERVER="Client.stopProxyServer",e.SET_PROXY_SERVER="Client.setProxyServer",e.SET_TURN_SERVER="Client.setTurnServer",e.SET_CLIENT_ROLE="Client.setClientRole",e.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",e.ENABLE_DUAL_STREAM="Client.enableDualStream",e.DISABLE_DUAL_STREAM="Client.disableDualStream",e.JOIN="Client.join",e.LEAVE="Client.leave",e.PUBLISH="Client.publish",e.UNPUBLISH="Client.unpublish",e.SUBSCRIBE="Client.subscribe",e.MASS_SUBSCRIBE="Client.massSubscribe",e.MASS_UNSUBSCRIBE="Client.massUnsubscribe",e.UNSUBSCRIBE="Client.unsubscribe",e.RENEW_TOKEN="Client.renewToken",e.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",e.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",e.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",e.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",e.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",e.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",e.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",e.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",e.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",e.START_LIVE_STREAMING="Client.startLiveStreaming",e.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",e.STOP_LIVE_STREAMING="Client.stopLiveStreaming",e.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",e.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",e.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",e.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",e.SET_CONFIG_DISTRIBUTE="_configDistribute",e.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",e.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",e.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",e.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",e.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",e.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",e.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",e.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",e.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",e.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",e.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",e.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",e.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",e.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",e.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",e.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",e.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",e.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",e.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",e.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",e.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",e.STREAM_TYPE_CHANGE="streamTypeChange",e.CONNECTION_STATE_CHANGE="connectionStateChange",e.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",e.IMAGE_MODERATION_UPLOAD="imageModerationUpload",e.REPUB_AFTER_PC_CONNECTED="repubAfterPCConnected",e.PRELOAD_MEDIA_FAILED="preloadMediaFailed",e.MISMATCH_DTLS_PARAMETERS="mismatchDtlsParameters",e.MISMATCH_ICE_PARAMETERS="mismatchIceParameters",e.VOS_FALLBACK_CN="vosFallbackCN",e.DATACHANNEL_FAILBACK="datachannelFailback",e}({}),ZN=function(e){return e.TRACER="tracer",e}({});function qN(e){return PN(e.timeout,"config.timeout",0,1e5),PN(e.timeoutFactor,"config.timeoutFactor",0,100,!1),PN(e.maxRetryCount,"config.maxRetryConfig",0,1/0),PN(e.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let QN=function(e){return e[e.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",e[e.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",e[e.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY",e}({}),$N=function(e){return e.LEAVE="LEAVE",e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.UID_BANNED="UID_BANNED",e.FALLBACK="FALLBACK",e.IP_BANNED="IP_BANNED",e.CHANNEL_BANNED="CHANNEL_BANNED",e.LICENSE_MISSING="LICENSE_MISSING",e.LICENSE_EXPIRED="LICENSE_EXPIRED",e.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",e.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",e.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",e.LICENSE_ILLEGAL="LICENSE_ILLEGAL",e.TOKEN_EXPIRE="TOKEN_EXPIRE",e.FALLBACK_TO_HLS="FALLBACK_TO_HLS",e.UID_CONFLICT="UID_CONFLICT",e}({});function eD(e){if(!Array.isArray(e)||e.length<1)return!1;try{e.forEach((e=>{if(!e.urls)throw Error()}))}catch(e){return!1}return!0}function tD(e){return kN(e.turnServerURL,"turnServerURL"),kN(e.username,"username"),kN(e.password,"password"),e.udpport&&PN(e.udpport,"udpport",1,99999,!0),e.forceturn&&NN(e.forceturn,"forceturn"),e.security&&NN(e.security,"security"),e.tcpport&&PN(e.tcpport,"tcpport",1,99999,!0),!0}let nD=function(e){return e[e.AUTO_SIMULCAST_STREAM=-1]="AUTO_SIMULCAST_STREAM",e[e.DISABLE_SIMULCAST_STREM=0]="DISABLE_SIMULCAST_STREM",e[e.ENABLE_SIMULCAST_STREAM=1]="ENABLE_SIMULCAST_STREAM",e}({});function iD(e){return void 0!==e.level&&DN(e.level,"level",[1,2,3]),void 0!==e.delay&&PN(e.delay,"delay",0,3e3,!0),!0}let rD=function(e){return e.PEERCONNECTION_STATE_CHANGE="peerconnection-state-change",e.AUDIO_METADATA="audio-metadata",e.AUDIO_PTS="audio-pts",e.CONNECTION_STATE_CHANGE="connection-state-change",e.MEDIA_RECONNECT_START="media-reconnect-start",e.MEDIA_RECONNECT_END="media-reconnect-end",e.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",e.USER_JOINED="user-joined",e.USER_LEAVED="user-left",e.USER_PUBLISHED="user-published",e.USER_UNPUBLISHED="user-unpublished",e.USER_INFO_UPDATED="user-info-updated",e.CLIENT_BANNED="client-banned",e.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",e.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",e.VOLUME_INDICATOR="volume-indicator",e.CRYPT_ERROR="crypt-error",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGED="stream-type-changed",e.STREAM_FALLBACK="stream-fallback",e.RECEIVE_METADATA="receive-metadata",e.STREAM_MESSAGE="stream-message",e.LIVE_STREAMING_ERROR="live-streaming-error",e.LIVE_STREAMING_WARNING="live-streaming-warning",e.EXCEPTION="exception",e.ERROR="error",e.P2P_LOST="p2p_lost",e.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",e.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",e.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",e.PUBLISHED_USER_LIST="published-user-list",e.USER_LIST="user-list",e.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",e.CONTENT_INSPECT_ERROR="content-inspect-error",e.CONTENT_INSPECT_RESULT="content-inspect-result",e.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change",e.FALLBACK_TO_HLS="fallback-to-hls",e.FIRST_VIDEO_BUFFER_READY="first-video-buffer-ready",e.FIRST_VIDEO_PRE_RENDER="first-video-pre-render",e.AV1_DECODABLE_RESULT="av1-decodable-result",e}({}),oD=function(e){return e.CONFIG="config",e.VOSERROR="vos_error",e.AP_ERROR="ap_error",e}({}),sD=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e.REGIONAL_DISTRIBUTION="REGIONAL_DISTRIBUTION",e}({}),aD=function(e){return e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({}),cD=function(e){return e.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",e.ONLINE="ONLINE",e.OFFLINE="OFFLINE",e}({});function dD(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return 0===e.getListeners(t).length?cp.reject(new ON(wN.UNEXPECTED_ERROR,"can not emit promise")):new cp(((n,r)=>{e.emit(t,...i,n,r)}))}function lD(e,t){if(0===e.getListeners(t).length)return cp.resolve();for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return dD(e,t,...i)}function uD(e,t){if(0===e.getListeners(t).length)return null;for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return hD(e,t,...i)}function hD(e,t){let n=null,i=null;for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];if(e.emit(t,...o,(e=>{n=e}),(e=>{i=e})),null!==i)throw i;if(null===n)throw new ON(wN.UNEXPECTED_ERROR,"handler is not sync");return n}const pD=new class extends YN{set networkState(e){this.emit(cD.NETWORK_STATE_CHANGE,e,this._networkState),e===aD.ONLINE?this.emit(cD.ONLINE):e===aD.OFFLINE&&(this.onlineWaiter=new cp((e=>{this.once(cD.ONLINE,(()=>{this.onlineWaiter=void 0,e(aD.ONLINE)}))})),this.emit(cD.OFFLINE)),this._networkState=e}get networkState(){return this._networkState}get isOnline(){return this._networkState===aD.ONLINE}constructor(){super(),CN(this,"_moduleName","network-indicator"),CN(this,"_networkState",aD.ONLINE),CN(this,"onlineWaiter",void 0),window.addEventListener("online",(()=>{this.networkState=aD.ONLINE})),window.addEventListener("offline",(()=>{this.networkState=aD.OFFLINE}))}},_D=[];for(let e=0;e<256;++e)_D.push((e+256).toString(16).slice(1));const ED="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);let mD;const fD=new Uint8Array(16);function gD(){return ED?ED():function(e,t,n){var i,r,o,s;const a=null!==(i=null!==(r=(e=e||{}).random)&&void 0!==r?r:null===(o=(s=e).rng)||void 0===o?void 0:o.call(s))&&void 0!==i?i:function(){if(!mD){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");mD=crypto.getRandomValues.bind(crypto)}return mD(fD)}();if(a.length<16)throw new Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t){if((n=n||0)<0||n+16>t.length)throw new RangeError("UUID byte range ".concat(n,":").concat(n+15," is out of buffer bounds"));for(let e=0;e<16;++e)t[n+e]=a[e];return t}return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return(_D[e[t+0]]+_D[e[t+1]]+_D[e[t+2]]+_D[e[t+3]]+"-"+_D[e[t+4]]+_D[e[t+5]]+"-"+_D[e[t+6]]+_D[e[t+7]]+"-"+_D[e[t+8]]+_D[e[t+9]]+"-"+_D[e[t+10]]+_D[e[t+11]]+_D[e[t+12]]+_D[e[t+13]]+_D[e[t+14]]+_D[e[t+15]]).toLowerCase()}(a)}(e,t,undefined);var e,t}function SD(e,t){const n=e.indexOf(t);-1!==n&&e.splice(n,1)}function TD(e){const t=[];return e.forEach((e=>{-1===t.indexOf(e)&&t.push(e)})),t}function RD(e){void 0!==cp?cp.resolve().then(e):setTimeout(e,0)}function vD(e){return JSON.parse(JSON.stringify(e))}function yD(e){try{return vD(e)}catch(t){return e}}const CD={};function bD(e,t){CD[t]||(CD[t]=!0,e())}function ID(e){const t=window.atob(e),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}function AD(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return window.btoa(t)}function wD(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:16,n=(new TextEncoder).encode(e);if(n.length>t)n=n.slice(0,t);else if(n.length<t){const e=new Uint8Array(t);e.set(n),n=e}return n}function OD(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=sr(t).call(t,((e,t)=>e+t.length),0),r=new Uint8Array(new ArrayBuffer(i));let o=0;return t.forEach((e=>{r.set(e,o),o+=e.length})),r}function ND(e){return window.TextEncoder?(new TextEncoder).encode(e).length:e.length}function DD(e){let t=0;return(/DingTalk/i.test(navigator.userAgent)||/AliApp/i.test(navigator.userAgent))&&e.realFormData&&(e=e.realFormData),e.forEach((e=>{t+="string"==typeof e?ND(e):e.size})),t+138}function PD(e){const t=new ON(wN.TIMEOUT,"timeout");return new cp(((n,i)=>{window.setTimeout((()=>i(t)),e)}))}function LD(e){return new cp((t=>{window.setTimeout(t,e)}))}function kD(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:7,t=arguments.length>1?arguments[1]:void 0;const n=Math.random().toString(16).substr(2,e).toLowerCase();return n.length===e?"".concat(t).concat(n):"".concat(t).concat(n)+kD(e-n.length,"")}function MD(){let e,t=!1;try{var n;e=Pb(n=gD()).call(n,"-","")}catch(e){t=!0}return!t&&e&&32===e.length||(e=kD(32,"")),e.toUpperCase()}const UD=()=>{},VD=new class{constructor(){CN(this,"fnMap",new Map)}throttleByKey(e,t,n,i){for(var r=arguments.length,o=new Array(r>4?r-4:0),s=4;s<r;s++)o[s-4]=arguments[s];if(this.fnMap.has(t)){const r=this.fnMap.get(t);if(r.threshold!==n){r.fn(...r.args),clearTimeout(r.timer);const s=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),n);this.fnMap.set(t,{fn:e,threshold:n,timer:s,args:o,skipFn:i})}else r.skipFn&&r.skipFn(...r.args),this.fnMap.set(t,IN(IN({},r),{},{fn:e,args:o,skipFn:i}))}else{const r=window.setTimeout((()=>{const e=this.fnMap.get(t);e&&e.fn(...e.args),this.fnMap.delete(t)}),n);this.fnMap.set(t,{fn:e,threshold:n,timer:r,args:o,skipFn:i})}}},xD=VD.throttleByKey.bind(VD);function FD(e){return"object"==typeof e&&null!==e&&!(e instanceof RegExp)}function BD(e,t){if(!FD(e)||!FD(t))return t;if(Array.isArray(e)&&!Array.isArray(t)||!Array.isArray(e)&&Array.isArray(t))return t;if(Array.isArray(t)&&Array.isArray(e)){const n=[...e];for(let i=0;i<t.length;i++)n[i]=BD(e[i],t[i]);return n}{const n=IN({},e);for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(Object.prototype.hasOwnProperty.call(e,i)?n[i]=BD(e[i],t[i]):n[i]=t[i]);return n}}function jD(e,t){let n=[0];if(t&&(n=new Array(t).fill(0)),0===e)return n;let i=0;for(;e>0&&(n[i]=255&e,e>>=8,i++,!t||i!==t););return n}function GD(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function WD(e,t){try{return"object"==typeof e&&"object"==typeof t&&JSON.stringify(e)===JSON.stringify(t)}catch(e){return!1}}function KD(e){return sr(e).call(e,((e,t)=>e+t),0)}function HD(e){const t="0123456789abcdef";function n(e){let n,i="";for(n=0;n<=3;n++)i+=t.charAt(e>>8*n+4&15)+t.charAt(e>>8*n&15);return i}function i(e,t){const n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function r(e,t,n,r,o,s){return i(function(e,t){return e<<t|e>>>32-t}(i(i(t,e),i(r,s)),o),n)}function o(e,t,n,i,o,s,a){return r(t&n|~t&i,e,t,o,s,a)}function s(e,t,n,i,o,s,a){return r(t&i|n&~i,e,t,o,s,a)}function a(e,t,n,i,o,s,a){return r(t^n^i,e,t,o,s,a)}function c(e,t,n,i,o,s,a){return r(n^(t|~i),e,t,o,s,a)}const d=function(e){let t;const n=1+(e.length+8>>6),i=new Array(16*n);for(t=0;t<16*n;t++)i[t]=0;for(t=0;t<e.length;t++)i[t>>2]|=e.charCodeAt(t)<<t%4*8;return i[t>>2]|=128<<t%4*8,i[16*n-2]=8*e.length,i}(e);let l,u,h,p,_,E=1732584193,m=-271733879,f=-1732584194,g=271733878;for(l=0;l<d.length;l+=16)u=E,h=m,p=f,_=g,E=o(E,m,f,g,d[l+0],7,-680876936),g=o(g,E,m,f,d[l+1],12,-389564586),f=o(f,g,E,m,d[l+2],17,606105819),m=o(m,f,g,E,d[l+3],22,-1044525330),E=o(E,m,f,g,d[l+4],7,-176418897),g=o(g,E,m,f,d[l+5],12,1200080426),f=o(f,g,E,m,d[l+6],17,-1473231341),m=o(m,f,g,E,d[l+7],22,-45705983),E=o(E,m,f,g,d[l+8],7,1770035416),g=o(g,E,m,f,d[l+9],12,-1958414417),f=o(f,g,E,m,d[l+10],17,-42063),m=o(m,f,g,E,d[l+11],22,-1990404162),E=o(E,m,f,g,d[l+12],7,1804603682),g=o(g,E,m,f,d[l+13],12,-40341101),f=o(f,g,E,m,d[l+14],17,-1502002290),m=o(m,f,g,E,d[l+15],22,1236535329),E=s(E,m,f,g,d[l+1],5,-165796510),g=s(g,E,m,f,d[l+6],9,-1069501632),f=s(f,g,E,m,d[l+11],14,643717713),m=s(m,f,g,E,d[l+0],20,-373897302),E=s(E,m,f,g,d[l+5],5,-701558691),g=s(g,E,m,f,d[l+10],9,38016083),f=s(f,g,E,m,d[l+15],14,-660478335),m=s(m,f,g,E,d[l+4],20,-405537848),E=s(E,m,f,g,d[l+9],5,568446438),g=s(g,E,m,f,d[l+14],9,-1019803690),f=s(f,g,E,m,d[l+3],14,-187363961),m=s(m,f,g,E,d[l+8],20,1163531501),E=s(E,m,f,g,d[l+13],5,-1444681467),g=s(g,E,m,f,d[l+2],9,-51403784),f=s(f,g,E,m,d[l+7],14,1735328473),m=s(m,f,g,E,d[l+12],20,-1926607734),E=a(E,m,f,g,d[l+5],4,-378558),g=a(g,E,m,f,d[l+8],11,-2022574463),f=a(f,g,E,m,d[l+11],16,1839030562),m=a(m,f,g,E,d[l+14],23,-35309556),E=a(E,m,f,g,d[l+1],4,-1530992060),g=a(g,E,m,f,d[l+4],11,1272893353),f=a(f,g,E,m,d[l+7],16,-155497632),m=a(m,f,g,E,d[l+10],23,-1094730640),E=a(E,m,f,g,d[l+13],4,681279174),g=a(g,E,m,f,d[l+0],11,-358537222),f=a(f,g,E,m,d[l+3],16,-722521979),m=a(m,f,g,E,d[l+6],23,76029189),E=a(E,m,f,g,d[l+9],4,-640364487),g=a(g,E,m,f,d[l+12],11,-421815835),f=a(f,g,E,m,d[l+15],16,530742520),m=a(m,f,g,E,d[l+2],23,-995338651),E=c(E,m,f,g,d[l+0],6,-198630844),g=c(g,E,m,f,d[l+7],10,1126891415),f=c(f,g,E,m,d[l+14],15,-1416354905),m=c(m,f,g,E,d[l+5],21,-57434055),E=c(E,m,f,g,d[l+12],6,1700485571),g=c(g,E,m,f,d[l+3],10,-1894986606),f=c(f,g,E,m,d[l+10],15,-1051523),m=c(m,f,g,E,d[l+1],21,-2054922799),E=c(E,m,f,g,d[l+8],6,1873313359),g=c(g,E,m,f,d[l+15],10,-30611744),f=c(f,g,E,m,d[l+6],15,-1560198380),m=c(m,f,g,E,d[l+13],21,1309151649),E=c(E,m,f,g,d[l+4],6,-145523070),g=c(g,E,m,f,d[l+11],10,-1120210379),f=c(f,g,E,m,d[l+2],15,718787259),m=c(m,f,g,E,d[l+9],21,-343485551),E=i(E,u),m=i(m,h),f=i(f,p),g=i(g,_);return n(E)+n(m)+n(f)+n(g)}let YD=1,XD=console,JD=class{static setLogger(e){XD=e}constructor(e,t){CN(this,"id",void 0),CN(this,"lockingPromise",cp.resolve()),CN(this,"locks",0),CN(this,"name",""),CN(this,"lockId",void 0),this.lockId=YD++,e&&(this.name=e),t&&(this.id=t),this.logger("created")}logger(e,t){const n=(this.id?"[".concat(this.id,"]"):"")+"[lock-".concat(this.name,"-").concat(this.lockId,"]"),i="created"===e?"is ".concat(e,"."):"is ".concat(e,", current queue ").concat(this.locks,". ").concat(null!=t?t:"");XD.debug("".concat(n," ").concat(i))}setId(e){this.id=e}get isLocked(){return this.locks>0}lock(e){let t;this.locks+=1,this.logger("locked",e);const n=new cp((n=>{t=()=>{this.locks-=1,this.logger("unlocked",e),n()}})),i=this.lockingPromise.then((()=>t));return this.lockingPromise=this.lockingPromise.then((()=>n)),i}};function zD(e,t){return function(n,i,r){const o=r.value;if("function"!=typeof o)throw new Error("Cannot use mutex on object property.");return r.value=async function(){const n=this[t];if(!n)throw new Error("mutex property key ".concat(t," doesn't exist on ").concat(e));const r=await n.lock("From ".concat(e,".").concat(i));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return await o.apply(this,a)}finally{r()}},r}}const ZD={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function qD(e,t){const n=Math.floor(t.timeout*Math.pow(t.timeoutFactor,e));return Math.min(t.maxRetryTimeout,n)}function QD(e,t,n,i){const r=Object.assign({},ZD,i);let o=r.timeout;const s=async()=>{await function(e){return new cp((t=>{window.setTimeout(t,e)}))}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)};let a=!1;const c=new cp((async(i,o)=>{t=t||(()=>!1),n=n||(()=>!0);for(let c=0;c<r.maxRetryCount;c+=1){if(a)return o(new ON(wN.OPERATION_ABORTED));try{const n=await e();if(!t(n,c))return i(n);if(c+1===r.maxRetryCount)return i(n);await s()}catch(e){if(!n(e,c))return o(e);if(c+1===r.maxRetryCount)return o(e);await s()}}}));return c.cancel=()=>a=!0,c}let $D,eP=class{constructor(e){CN(this,"input",[]),CN(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}mean(){var e;return 0===this.input.length?0:sr(e=this.input).call(e,((e,t)=>e+t))/this.input.length}},tP=0,nP=0;function iP(e,t,n,i){return new cp(((r,o)=>{t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),tP+=ND(t.data)):n&&(t.data.size?tP+=t.data.size:t.data instanceof FormData?tP+=DD(t.data):tP+=ND(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,DO.request(t).then((e=>{"string"==typeof e.data?nP+=ND(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?nP+=e.data.byteLength:nP+=ND(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{DO.isCancel(e)?o(new ON(wN.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new ON(wN.NETWORK_TIMEOUT,e.message)):e.response?o(new ON(wN.NETWORK_RESPONSE_ERROR,e.response.status)):o(new ON(wN.NETWORK_ERROR,e.message))}))}))}async function rP(e,t){const n=new Blob([t.data],{type:"buffer"});return await iP(e,IN(IN({},t),{},{data:n,headers:{"Content-Type":"application/octet-stream"}}),!0)}const oP=()=>void 0!==window.isSecureContext;function sP(e){if(Array.isArray(e))return e.map((e=>e));if(!aP(e))return e;const t={};for(const n in e){const i=e[n];aP(i)||Array.isArray(i)?t[n]=sP(i):t[n]=i}return t}function aP(e){return!("object"!=typeof e||Array.isArray(e)||!e)}let cP=class{constructor(e){CN(this,"input",[]),CN(this,"size",void 0),this.size=e}add(e){this.input.push(e),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return 0===this.input.length?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}};const dP={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},lP={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],transport:{bytesSent:0,bytesReceived:0,packetsSent:0,packetsReceived:0},selectedCandidatePair:{id:"unknown",localCandidate:dP,remoteCandidate:dP},updateInterval:0},uP={firsCount:0,nacksCount:0,plisCount:0,framesDecodeCount:0,framesDecodeInterval:0,framesDecodeFreezeTime:0,decodeFrameRate:0,bytes:0,packetsLost:0,packetLostRate:0,packets:0,ssrc:0,qpSumPerFrame:0,framesDroppedCount:0,outputFrameRate:0,packetsDiscarded:0,framesAssembledFromMultiplePackets:0,totalProcessingDelay:0,avgDecodeMs:0,avgFramesAssembledFromMultiplePacketsMs:0,avgProcessingDelayMs:0,avgInterFrameDelayMs:0,totalAssemblyTime:0},hP={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},pP={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},_P={jitterBufferMs:0,jitterMs:0,bytes:0,packetsLost:0,packetLostRate:0,packetsDiscarded:0,packets:0,ssrc:0,receivedFrames:0,droppedFrames:0,concealedSamples:0,totalSamplesReceived:0,silentConcealedSamples:0,concealmentEvents:0,freezeMs80:0,freezeMs200:0,freezeSamples80:0,freezeSamples200:0};let EP=class{constructor(e,t){CN(this,"onFirstVideoReceived",void 0),CN(this,"onFirstVideoDecoded",void 0),CN(this,"onFirstAudioReceived",void 0),CN(this,"onFirstVideoDecodedTimeout",void 0),CN(this,"onFirstAudioDecoded",void 0),CN(this,"onSelectedLocalCandidateChanged",void 0),CN(this,"onSelectedRemoteCandidateChanged",void 0),CN(this,"videoIsReady",!1),CN(this,"videoIsReady2",{}),CN(this,"pc",void 0),CN(this,"options",void 0),CN(this,"intervalTimer",void 0),CN(this,"stats",sP(lP)),CN(this,"isFirstVideoReceived",{}),CN(this,"isFirstVideoDecoded",{}),CN(this,"isFirstAudioReceived",{}),CN(this,"isFirstAudioDecoded",{}),CN(this,"isFirstVideoDecodedTimeout",{}),CN(this,"lossRateWindowStats",[]),this.pc=e,this.options=t,this.intervalTimer=window.setInterval((async()=>{this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new cp((e=>{e({local:IN({},dP),remote:IN({},dP)})}))}setVideoIsReady(e){this.videoIsReady=e}setVideoIsReady2(e,t){this.videoIsReady2[e]=t}getVideoIsReady(e){return this.videoIsReady2[e]||!1}setIsFirstAudioDecoded(e){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(e){this.lossRateWindowStats.push(e),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const t=this.lossRateWindowStats.length,n=["videoSend","audioSend","videoRecv","audioRecv"];let i=0,r=0,o=0,s=0;for(const a of n)e[a].forEach(((e,n)=>{if(!this.lossRateWindowStats[t-1][a][n]||!this.lossRateWindowStats[0][a][n])return;const c=this.lossRateWindowStats[t-1][a][n].packets-this.lossRateWindowStats[0][a][n].packets,d=this.lossRateWindowStats[t-1][a][n].packetsLost-this.lossRateWindowStats[0][a][n].packetsLost;"videoSend"===a||"audioSend"===a?(i+=c,o+=d):(r+=c,s+=d),Number.isNaN(c)||Number.isNaN(c)?e.packetLostRate=0:e.packetLostRate=c<=0||d<=0?0:d/(c+d)}));e.sendPacketLossRate=i<=0||o<=0?0:o/(i+o),e.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}},mP=class extends EP{constructor(){super(...arguments),CN(this,"_stats",lP),CN(this,"lastDecodeVideoReceiverStats",new Map)}async updateStats(){const e=await this._getStats(),t=this.statsResponsesToObjects(e);this._stats=sP(lP);const n=t.filter((e=>"ssrc"===e.type));this.processSSRCStats(n);const i=t.find((e=>"VideoBwe"===e.type));i&&this.processBandwidthStats(i),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}processBandwidthStats(e){this._stats.bitrate={actualEncoded:Number(e.googActualEncBitrate),targetEncoded:Number(e.googTargetEncBitrate),retransmit:Number(e.googRetransmitBitrate),transmit:Number(e.googTransmitBitrate)},this._stats.sendBandwidth=Number(e.googAvailableSendBandwidth)}processSSRCStats(e){e.forEach((e=>{var t;const n=Ui(t=e.id).call(t,"send");switch("".concat(e.mediaType,"_").concat(n?"send":"recv")){case"video_send":{const t=sP(hP);t.codec=e.googCodecName,t.adaptionChangeReason="none",e.googCpuLimitedResolution&&(t.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(t.adaptionChangeReason="bandwidth"),t.avgEncodeMs=Number(e.googAvgEncodeMs),t.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},t.firsCount=Number(e.googFirReceived),t.nacksCount=Number(e.googNacksReceived),t.plisCount=Number(e.googPlisReceived),t.frameCount=Number(e.framesEncoded),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(t),this._stats.rtt=t.rttMs;break}case"video_recv":{const t=sP(uP),n=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(t.codec=e.googCodecName,t.targetDelayMs=Number(e.googTargetDelayMs),t.renderDelayMs=Number(e.googRenderDelayMs),t.currentDelayMs=Number(e.googCurrentDelayMs),t.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),t.decodeMs=Number(e.googDecodeMs),t.maxDecodeMs=Number(e.googMaxDecodeMs),t.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},t.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},t.decodeFrameRate=Number(e.googFrameRateDecoded),t.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},t.jitterBufferMs=Number(e.googJitterBufferMs),t.firsCount=Number(e.googFirsSent),t.nacksCount=Number(e.googNacksSent),t.plisCount=Number(e.googPlisSent),t.framesDecodeCount=Number(e.framesDecoded),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,t.decodedFrame.width,t.decodedFrame.height),this.isFirstVideoDecoded[t.ssrc]=!0),n){const i=n.stats,r=Date.now()-n.lts;t.framesDecodeFreezeTime=i.framesDecodeFreezeTime,t.framesDecodeInterval=i.framesDecodeInterval,t.framesDecodeCount>i.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(n.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<n.stats.framesDecodeCount&&(t.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:IN({},t),lts:Date.now()}),this._stats.videoRecv.push(t);break}case"audio_recv":{const t=sP(_P);t.codec=e.googCodecName,t.outputLevel=Math.abs(Number(e.audioOutputLevel))/32767,t.decodingCNG=Number(e.googDecodingCNG),t.decodingCTN=Number(e.googDecodingCTN),t.decodingCTSG=Number(e.googDecodingCTSG),t.decodingNormal=Number(e.googDecodingNormal),t.decodingPLC=Number(e.googDecodingPLC),t.decodingPLCCNG=Number(e.googDecodingPLCCNG),t.expandRate=Number(e.googExpandRate),t.accelerateRate=Number(e.googAccelerateRate),t.preemptiveExpandRate=Number(e.googPreemptiveExpandRate),t.secondaryDecodedRate=Number(e.googSecondaryDecodedRate),t.speechExpandRate=Number(e.googSpeechExpandRate),t.preferredJitterBufferMs=Number(e.googPreferredJitterBufferMs),t.jitterBufferMs=Number(e.googJitterBufferMs),t.jitterMs=Number(e.googJitterReceived),t.bytes=Number(e.bytesReceived),t.packets=Number(e.packetsReceived),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.receivedFrames=Number(e.googDecodingCTN)||Number(e.packetsReceived),t.droppedFrames=Number(e.googDecodingPLC)+Number(e.googDecodingPLCCNG)||Number(e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.decodingNormal>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),this._stats.audioRecv.push(t);break}case"audio_send":{const t=sP(pP);t.codec=e.googCodecName,t.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,t.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),t.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),t.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),t.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),t.bytes=Number(e.bytesSent),t.packets=Number(e.packetsSent),t.packetsLost=Number(e.packetsLost),t.ssrc=Number(e.ssrc),t.rttMs=Number(e.googRtt||0),this._stats.rtt=t.rttMs,this._stats.audioSend.push(t);break}}}))}_getStats(){return new cp(((e,t)=>{this.pc.getStats(e,t)}))}statsResponsesToObjects(e){const t=[];return e.result().forEach((e=>{const n={id:e.id,timestamp:e.timestamp.valueOf().toString(),type:e.type};e.names().forEach((t=>{n[t]=e.stat(t)})),t.push(n)})),t}},fP=function(e){return e.BANDWIDTH="bandwidth",e.CPU="cpu",e.NONE="none",e.OTHER="other",e}({}),gP=function(e){return e.L1T1="L1T1",e.L1T2="L1T2",e.L1T3="L1T3",e.L1T3_KEY="L1T3_KEY",e.L2T1_KEY="L2T1_KEY",e.L2T2_KEY="L2T2_KEY",e.L2T3_KEY="L2T3_KEY",e.L3T1_KEY="L3T1_KEY",e.L3T2_KEY="L3T2_KEY",e.L3T3_KEY="L3T3_KEY",e}({}),SP=function(e){return e[e.new=0]="new",e[e.connecting=1]="connecting",e[e.connected=2]="connected",e[e.disconnected=3]="disconnected",e[e.failed=4]="failed",e[e.closed=5]="closed",e}({}),TP=function(e){return e.CERTIFICATE="certificate",e.CODEC="codec",e.CANDIDATE_PAIR="candidate-pair",e.LOCAL_CANDIDATE="local-candidate",e.REMOTE_CANDIDATE="remote-candidate",e.INBOUND="inbound-rtp",e.TRACK="track",e.OUTBOUND="outbound-rtp",e.PC="peer-connection",e.REMOTE_INBOUND="remote-inbound-rtp",e.REMOTE_OUTBOUND="remote-outbound-rtp",e.TRANSPORT="transport",e.CSRC="csrc",e.DATA_CHANNEL="data-channel",e.STREAM="stream",e.SENDER="sender",e.RECEIVER="receiver",e}({});var RP=function(e){return e[e.kNone=1]="kNone",e[e.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",e[e.kBytesToBits=8]="kBytesToBits",e}(RP||{});function vP(e,t,n,i){let r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:RP.kNone;if(!t)return;const o=Number(t[n]);if("number"!=typeof o)return;const s=Number(t[i]);if("number"!=typeof s)return;if(!e)return s?o/s*r:void 0;const a=Number(e[n]);if("number"!=typeof a)return;const c=Number(e[i]);if("number"!=typeof c)return;const d=s-c;return d?(o-a)/d*r:void 0}let yP=class extends EP{constructor(){super(...arguments),CN(this,"_stats",lP),CN(this,"report",void 0),CN(this,"lastDecodeVideoReceiverStats",new Map),CN(this,"lastVideoFramesRecv",new Map),CN(this,"lastVideoFramesSent",new Map),CN(this,"lastVideoFramesDecode",new Map),CN(this,"lastVideoFramesOutput",new Map),CN(this,"lastVideoJBDelay",new Map),CN(this,"lastAudioJBDelay",new Map),CN(this,"mediaBytesSent",new Map),CN(this,"mediaBytesRetransmit",new Map),CN(this,"mediaBytesTargetEncode",new Map),CN(this,"lastDecodeAudioReceiverStats",new Map),CN(this,"lastAudioConcealment",new Map),CN(this,"lastEncoderMs",new Map)}async updateStats(){this.report=await this.pc.getStats(),this._stats=sP(lP),this.report.forEach((e=>{switch(e.type){case TP.OUTBOUND:case TP.INBOUND:{const t=e.mediaType||e.kind,n=!t&&"frameWidth"in e,i=!t&&!("frameWidth"in e);e.type===TP.OUTBOUND?"audio"===t||i?this.processAudioOutboundStats(e):("video"===t||n)&&this.processVideoOutboundStats(e):e.type===TP.INBOUND&&("audio"===t||i?this.processAudioInboundStats(e):("video"===t||n)&&this.processVideoInboundStats(e));break}case TP.TRANSPORT:{this.processTransportStats(e);const t=this.report.get(e.selectedCandidatePairId);t&&this.processCandidatePairStats(t);break}case TP.CANDIDATE_PAIR:e.selected&&this.processCandidatePairStats(e)}})),this.updateSendBitrate(),this._stats.updateInterval=Date.now()-this.stats.timestamp,this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats}async getSelectedCandidatePair(){const e=await this.pc.getStats(),t={local:IN({},dP),remote:IN({},dP)};return e.forEach((n=>{let i;if(n.type===TP.TRANSPORT&&(i=e.get(n.selectedCandidatePairId)),n.type===TP.CANDIDATE_PAIR&&n.selected&&(i=n),i){const n=(e,t)=>{e.type=t.type,e.id=t.id,t.address&&(e.address=t.address),t.candidateType&&(e.candidateType=t.candidateType),t.port&&(e.port=t.port),t.priority&&(e.priority=t.priority),t.protocol&&(e.protocol=t.protocol),t.relayProtocol&&(e.relayProtocol=t.relayProtocol)};if(i.localCandidateId){const r=e.get(i.localCandidateId);r&&n(t.local,r)}if(i.remoteCandidateId){const r=e.get(i.remoteCandidateId);r&&n(t.remote,r)}}})),t}processCandidatePairStats(e){if(this._stats.sendBandwidth=e.availableOutgoingBitrate||0,e.currentRoundTripTime&&(this._stats.rtt=1e3*e.currentRoundTripTime),this._stats.videoSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.audioSend.forEach((t=>{e.currentRoundTripTime&&(t.rttMs=1e3*e.currentRoundTripTime)})),this._stats.selectedCandidatePair.id=e.id,e.localCandidateId){const t=this.report.get(e.localCandidateId);t&&this.processCandidateStats(t)}if(e.remoteCandidateId){const t=this.report.get(e.remoteCandidateId);t&&this.processCandidateStats(t)}}processCandidateStats(e){let t;e.type===TP.LOCAL_CANDIDATE&&(t=this._stats.selectedCandidatePair.localCandidate),e.type===TP.REMOTE_CANDIDATE&&(t=this._stats.selectedCandidatePair.remoteCandidate),t&&(t.type=e.type,t.id=e.id,e.address&&(t.address=e.address),e.candidateType&&(t.candidateType=e.candidateType),e.port&&(t.port=e.port),e.priority&&(t.priority=e.priority),e.protocol&&(t.protocol=e.protocol),e.relayProtocol&&(t.relayProtocol=e.relayProtocol),e.type===TP.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==t.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(IN({},t),IN({},this.stats.selectedCandidatePair.localCandidate)),e.type===TP.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==t.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(IN({},t),IN({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(e){let t=this._stats.audioRecv.find((t=>t.ssrc===e.ssrc));t||(t=sP(_P),this._stats.audioRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.packetsDiscarded=e.packetsDiscarded,t.bytes=e.bytesReceived,t.jitterMs=1e3*e.jitter,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.totalProcessingDelay=e.totalProcessingDelay,t.jitterBufferEmittedCount=e.jitterBufferEmittedCount,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const n=this.lastDecodeAudioReceiverStats.get(t.ssrc);t.avgProcessingDelayMs=vP(n,t,"totalProcessingDelay","jitterBufferEmittedCount",RP.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(e,e.trackId,t),this.calculateAudioFreeze(t,n,e),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),t.receivedFrames||(t.receivedFrames=e.packetsReceived),t.droppedFrames||(t.droppedFrames=e.packetsLost),t.receivedFrames>0&&!this.isFirstAudioReceived[t.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(t.ssrc),this.isFirstAudioReceived[t.ssrc]=!0),t.outputLevel&&t.outputLevel>0&&!this.isFirstAudioDecoded[t.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(t.ssrc),this.isFirstAudioDecoded[t.ssrc]=!0),"number"==typeof e.concealedSamples&&(t.concealedSamples=e.concealedSamples),this.lastDecodeAudioReceiverStats.set(t.ssrc,IN({},t))}calculateAudioFreeze(e,t,n){const i=this.lastAudioConcealment.get(e.ssrc);if(null!=t&&null!=i){const r=i.lts,o=n.timestamp,s=o-r;if(s<=0)return;const a=e.concealedSamples-t.concealedSamples-0,c=i.nonSilent+a,d=e.totalSamplesReceived-t.totalSamplesReceived;if(d<=0)return;const l=80*d/s,u=200*d/s,h=s/d;let p=0;e.freezeSamples80=t.freezeSamples80,e.freezeMs80=t.freezeMs80,c>l&&(i.plc80>0?(e.freezeSamples80+=a,e.freezeMs80+=Math.round(a*h)):(e.freezeSamples80+=c,e.freezeMs80+=Math.round(c*h)),p=i.plc80+1);let _=0;e.freezeSamples200=t.freezeSamples200,e.freezeMs200=t.freezeMs200,c>u&&(i.plc200>0?(e.freezeSamples200+=a,e.freezeMs200+=Math.round(a*h)):(e.freezeSamples200+=c,e.freezeMs200+=Math.round(c*h)),_=i.plc200+1),this.lastAudioConcealment.set(e.ssrc,{nonSilent:a,lts:o,plc80:p,plc200:_})}else e.freezeSamples80=0,e.freezeSamples200=0,e.freezeMs80=0,e.freezeMs200=0,this.lastAudioConcealment.set(e.ssrc,{nonSilent:0,lts:n.timestamp,plc80:0,plc200:0})}processVideoInboundStats(e){let t=this._stats.videoRecv.find((t=>t.ssrc===e.ssrc));t||(t=sP(uP),this._stats.videoRecv.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsReceived,t.packetsLost=e.packetsLost,t.bytes=e.bytesReceived,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.framesDecodeCount=e.framesDecoded,t.framesDroppedCount=e.framesDropped,t.totalInterFrameDelay=e.totalInterFrameDelay,t.totalSquaredInterFrameDelay=e.totalSquaredInterFrameDelay,t.totalFreezesDuration=e.totalFreezesDuration,t.totalProcessingDelay=e.totalProcessingDelay,t.packetsDiscarded=e.packetsDiscarded,t.framesAssembledFromMultiplePackets=e.framesAssembledFromMultiplePackets,t.totalAssemblyTime=e.totalAssemblyTime,t.keyFramesDecoded=e.keyFramesDecoded,t.retransmittedBytesReceived=e.retransmittedBytesReceived,t.retransmittedPacketsReceived=e.retransmittedPacketsReceived,t.estimatedPlayoutTimestamp=e.estimatedPlayoutTimestamp;const n=this.lastDecodeVideoReceiverStats.get(t.ssrc),i=this.lastVideoFramesDecode.get(t.ssrc),r=this.lastVideoFramesOutput.get(t.ssrc),o=Date.now();if(t.framesDecodeCount>0&&!this.isFirstVideoDecoded[t.ssrc]){const e=t.decodedFrame?t.decodedFrame.width:0,n=t.decodedFrame?t.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(t.ssrc,e,n),this.isFirstVideoDecoded[t.ssrc]=!0}if(n){const i=n.stats,r=o-n.lts;t.framesDecodeFreezeTime=i.framesDecodeFreezeTime,t.framesDecodeInterval=i.framesDecodeInterval,!this.isFirstVideoDecoded[t.ssrc]&&r>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[t.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(t.ssrc),this.isFirstVideoDecodedTimeout[t.ssrc]=!0),t.framesDecodeCount>i.framesDecodeCount&&this.isFirstVideoDecoded[t.ssrc]?(n.lts=Date.now(),t.framesDecodeInterval=r,t.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc))?t.framesDecodeFreezeTime+=t.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):t.framesDecodeCount<i.framesDecodeCount&&(t.framesDecodeInterval=0),e.framesDecoded&&e.qpSum&&(n.stats.framesDecodeCount>e.framesDecoded?t.qpSumPerFrame=e.qpSum/e.framesDecoded:t.qpSumPerFrame=(e.qpSum-n.qpSum)/(e.framesDecoded-n.stats.framesDecodeCount))}e.totalDecodeTime&&(t.decodeMs=1e3*e.totalDecodeTime,t.avgDecodeMs=vP(null==n?void 0:n.stats,t,"decodeMs","framesDecodeCount")),t.avgProcessingDelayMs=vP(null==n?void 0:n.stats,t,"totalProcessingDelay","framesDecodeCount",RP.kMillisecondsFromSeconds),t.avgFramesAssembledFromMultiplePacketsMs=vP(null==n?void 0:n.stats,t,"totalAssemblyTime","framesAssembledFromMultiplePackets",RP.kMillisecondsFromSeconds),t.avgInterFrameDelayMs=vP(null==n?void 0:n.stats,t,"totalInterFrameDelay","framesDecodeCount",RP.kMillisecondsFromSeconds),i&&o-i.lts>=800?(t.decodeFrameRate=Math.round((t.framesDecodeCount-i.count)/((o-i.lts)/1e3)),this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:t.decodeFrameRate})):i?t.decodeFrameRate=i.rate:this.lastVideoFramesDecode.set(t.ssrc,{count:t.framesDecodeCount,lts:o,rate:0}),t.framesDroppedCount&&e.framesReceived&&(r&&o-r.lts>=800?(t.outputFrameRate=Math.round((e.framesReceived-t.framesDroppedCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:Math.max(t.outputFrameRate,0)})):r?t.outputFrameRate=r.rate:this.lastVideoFramesOutput.set(t.ssrc,{count:e.framesReceived-t.framesDroppedCount,lts:o,rate:0})),this.processVideoTrackReceiverStats(e,e.trackId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),"boolean"==typeof e.powerEfficientDecoder&&(t.powerEfficientDecoder=e.powerEfficientDecoder?1:0),e.framerateMean&&(t.framesRateFirefox=e.framerateMean),t.packets>0&&!this.isFirstVideoReceived[t.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(t.ssrc),this.isFirstVideoReceived[t.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(t.ssrc,{stats:IN({},t),lts:n?n.lts:Date.now(),qpSum:e.qpSum})}processVideoOutboundStats(e){let t=this._stats.videoSend.find((t=>t.ssrc===e.ssrc));t||(t=sP(hP),this._stats.videoSend.push(t));const n=this.mediaBytesSent.get(e.ssrc);if(n)n.add(e.bytesSent);else{const t=new cP(10);t.add(e.bytesSent),this.mediaBytesSent.set(e.ssrc,t)}if(void 0!==e.retransmittedBytesSent){const t=this.mediaBytesRetransmit.get(e.ssrc);if(t)t.add(e.retransmittedBytesSent);else{const t=new cP(10);t.add(e.retransmittedBytesSent),this.mediaBytesRetransmit.set(e.ssrc,t)}}if(e.totalEncodedBytesTarget){const t=this.mediaBytesTargetEncode.get(e.ssrc);if(t)t.add(e.totalEncodedBytesTarget);else{const t=new cP(10);t.add(e.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(e.ssrc,t)}}if(t.ssrc=e.ssrc,t.bytes=e.bytesSent,t.packets=e.packetsSent,t.firsCount=e.firCount,t.nacksCount=e.nackCount,t.plisCount=e.pliCount,t.frameCount=e.framesEncoded,t.adaptionChangeReason=e.qualityLimitationReason,t.scalabilityMode=e.scalabilityMode,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,t.hugeFramesSent=e.hugeFramesSent,t.keyFramesEncoded=e.keyFramesEncoded,t.targetBitrate=e.targetBitrate,e.totalEncodeTime&&e.framesEncoded){const n=this.lastEncoderMs.get(e.ssrc);if(!n||n.lastFrameCount>e.framesEncoded)t.avgEncodeMs=1e3*e.totalEncodeTime/e.framesEncoded;else{const i=e.framesEncoded-n.lastFrameCount,r=e.totalEncodeTime-n.lastEncoderTime;t.avgEncodeMs=1e3*r/i}}if(e.framesEncoded&&e.qpSum){const n=this.lastEncoderMs.get(e.ssrc);!n||n.lastFrameCount>e.framesEncoded?t.qpSumPerFrame=e.qpSum/e.framesEncoded:t.qpSumPerFrame=(e.qpSum-n.lastQpSum)/(e.framesEncoded-n.lastFrameCount)}if(this.lastEncoderMs.set(e.ssrc,{lastFrameCount:e.framesEncoded,lastEncoderTime:e.totalEncodeTime,lastQpSum:e.qpSum,lts:Date.now()}),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),"boolean"==typeof e.powerEfficientEncoder&&(t.powerEfficientEncoder=e.powerEfficientEncoder?1:0),e.mediaSourceId&&this.processVideoMediaSource(e.mediaSourceId,t),this.processVideoTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const n=this.findRemoteStatsId(e.ssrc,TP.REMOTE_INBOUND);n&&this.processRemoteInboundStats(n,t)}}processAudioOutboundStats(e){let t=this._stats.audioSend.find((t=>t.ssrc===e.ssrc));if(t||(t=sP(pP),this._stats.audioSend.push(t)),t.ssrc=e.ssrc,t.packets=e.packetsSent,t.bytes=e.bytesSent,t.retransmittedBytesSent=e.retransmittedBytesSent,t.retransmittedPacketsSent=e.retransmittedPacketsSent,e.mediaSourceId&&this.processAudioMediaSource(e.mediaSourceId,t),e.codecId&&(t.codec=this.getCodecFromCodecStats(e.codecId)),this.processAudioTrackSenderStats(e,e.trackId,t),e.remoteId)this.processRemoteInboundStats(e.remoteId,t);else{const n=this.findRemoteStatsId(e.ssrc,TP.REMOTE_INBOUND);n&&this.processRemoteInboundStats(n,t)}}processTransportStats(e){this._stats.transport.bytesReceived=e.bytesReceived||this._stats.transport.bytesReceived,this._stats.transport.bytesSent=e.bytesSent||this._stats.transport.bytesSent,this._stats.transport.packetsReceived=e.packetsReceived||this._stats.transport.packetsReceived,this._stats.transport.packetsSent=e.packetsSent||this._stats.transport.packetsSent}findRemoteStatsId(e,t){var n;const i=Array.from(fp(n=this.report).call(n)).find((n=>n.type===t&&n.ssrc===e));return i?i.id:null}processVideoMediaSource(e,t){const n=this.report.get(e);n&&n.width&&n.height&&n.framesPerSecond&&(t.inputFrame={width:n.width,height:n.height,frameRate:n.framesPerSecond})}processAudioMediaSource(e,t){const n=this.report.get(e);n&&(t.inputLevel=n.audioLevel)}processVideoTrackSenderStats(e,t,n){var i,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(i=null==a?void 0:a.framesSent)&&void 0!==i?i:e.framesSent;if("number"!=typeof c)return;let d=null!==(r=null==a?void 0:a.frameWidth)&&void 0!==r?r:e.frameWidth,l=null!==(o=null==a?void 0:a.frameHeight)&&void 0!==o?o:e.frameHeight,u=null!==(s=null==a?void 0:a.framesPerSecond)&&void 0!==s?s:e.framesPerSecond;if("number"==typeof d&&"number"==typeof l||(d=0,l=0),null==u){const e=Date.now(),t=this.lastVideoFramesSent.get(n.ssrc);t&&e-t.lts>=800?(u=Math.round((c-t.count)/((e-t.lts)/1e3)),this.lastVideoFramesSent.set(n.ssrc,{count:c,lts:e,rate:u})):t?u=t.rate:this.lastVideoFramesSent.set(n.ssrc,{count:c,lts:e,rate:0})}n.sentFrame={width:d,height:l,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(e,t,n){var i,r,o,s,a;const c=t?this.report.get(t):void 0,d=null!==(i=null==c?void 0:c.framesReceived)&&void 0!==i?i:e.framesReceived,l=null!==(r=null==c?void 0:c.frameWidth)&&void 0!==r?r:e.frameWidth,u=null!==(o=null==c?void 0:c.frameHeight)&&void 0!==o?o:e.frameHeight,h=null!==(s=null==c?void 0:c.jitterBufferDelay)&&void 0!==s?s:e.jitterBufferDelay,p=null!==(a=null==c?void 0:c.jitterBufferEmittedCount)&&void 0!==a?a:e.jitterBufferEmittedCount;if("number"==typeof d){const e=this.lastVideoFramesRecv.get(n.ssrc),t=Date.now();n.framesReceivedCount=d;let i=0;e&&t-e.lts>=800?(i=Math.round((d-e.count)/((t-e.lts)/1e3)),this.lastVideoFramesRecv.set(n.ssrc,{count:d,lts:t,rate:i})):e?i=e.rate:this.lastVideoFramesRecv.set(n.ssrc,{count:d,lts:t,rate:0}),n.receivedFrame={width:l||0,height:u||0,frameRate:i||0},n.decodedFrame={width:l||0,height:u||0,frameRate:n.decodeFrameRate||0},n.outputFrame={width:l||0,height:u||0,frameRate:n.outputFrameRate||n.decodeFrameRate||0}}if(h&&p){const e=this.lastVideoJBDelay.get(n.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const i=p-e.jitterBufferEmittedCount;i>0&&(t=1e3*(h-e.jitterBufferDelay)/i),n.jitterBufferMs=t,n.currentDelayMs=Math.round(t),this.lastVideoJBDelay.set(n.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:n.currentDelayMs})}}processAudioTrackSenderStats(e,t,n){var i,r,o,s;const a=t?this.report.get(t):void 0,c=null!==(i=null!==(r=null==a?void 0:a.echoReturnLoss)&&void 0!==r?r:e.echoReturnLoss)&&void 0!==i?i:0,d=null!==(o=null!==(s=null==a?void 0:a.echoReturnLossEnhancement)&&void 0!==s?s:e.echoReturnLossEnhancement)&&void 0!==o?o:0;n.aecReturnLoss=c,n.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(e,t,n){var i,r,o,s,a,c,d,l,u;const h=t?this.report.get(t):void 0,p=null!==(i=null==h?void 0:h.removedSamplesForAcceleration)&&void 0!==i?i:e.removedSamplesForAcceleration,_=null!==(r=null==h?void 0:h.totalSamplesReceived)&&void 0!==r?r:e.totalSamplesReceived,E=null!==(o=null==h?void 0:h.jitterBufferDelay)&&void 0!==o?o:e.jitterBufferDelay,m=null!==(s=null==h?void 0:h.jitterBufferEmittedCount)&&void 0!==s?s:e.jitterBufferEmittedCount,f=null!==(a=null==h?void 0:h.audioLevel)&&void 0!==a?a:null==e?void 0:e.audioLevel,g=null!==(c=null==h?void 0:h.totalSamplesDuration)&&void 0!==c?c:null==e?void 0:e.totalSamplesDuration,S=null!==(d=null==h?void 0:h.concealedSamples)&&void 0!==d?d:e.concealedSamples,T=null!==(l=null==h?void 0:h.silentConcealedSamples)&&void 0!==l?l:e.silentConcealedSamples,R=null!==(u=null==h?void 0:h.concealmentEvents)&&void 0!==u?u:e.concealmentEvents;if("number"==typeof _&&(n.totalSamplesReceived=_),"number"==typeof T&&(n.silentConcealedSamples=T),"number"==typeof R&&(n.concealmentEvents=R),"number"==typeof S&&(n.concealedSamples=S),p&&_&&(n.accelerateRate=p/_),E&&m){const e=this.lastAudioJBDelay.get(n.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let t=e.jitterBufferMs;const i=m-e.jitterBufferEmittedCount;i>0&&(t=1e3*(E-e.jitterBufferDelay)/i),n.jitterBufferMs=Math.round(t),this.lastAudioJBDelay.set(n.ssrc,{jitterBufferDelay:E,jitterBufferEmittedCount:m,jitterBufferMs:n.jitterBufferMs})}n.outputLevel=f;let v=1920;g&&_&&(v=_/g/50,n.receivedFrames=Math.round(_/v)),S&&(n.droppedFrames=Math.round(S/v))}processRemoteInboundStats(e,t){const n=this.report.get(e);n&&(t.packetsLost=n.packetsLost,n.roundTripTime&&(t.rttMs=1e3*n.roundTripTime),n.jitter&&(t.jitterMs=1e3*n.jitter),n.timestamp&&(t.timestamp=n.timestamp))}getCodecFromCodecStats(e){const t=this.report.get(e);if(!t)return"";const n=t.mimeType.match(/\/(.*)$/);return n&&n[1]?n[1]:""}updateSendBitrate(){let e=0,t=null,n=null;this.mediaBytesSent.forEach((t=>{e+=t.diffMean()})),this.mediaBytesRetransmit.forEach((e=>{t=null===t?e.diffMean():t+e.diffMean()})),this.mediaBytesTargetEncode.forEach((e=>{n=null===n?e.diffMean():n+e.diffMean()}));const i=null!==t?e-t:e;this._stats.bitrate={actualEncoded:8*i/(this.options.updateInterval/1e3),transmit:8*e/(this.options.updateInterval/1e3)},null!==t&&(this._stats.bitrate.retransmit=8*t/(this.options.updateInterval/1e3)),null!==n&&(this._stats.bitrate.targetEncoded=8*n/(this.options.updateInterval/1e3))}},CP=class extends EP{updateStats(){return cp.resolve()}};function bP(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:250,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:8,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:500,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1e4;const o=function(){const e=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return e&&e[0]?Number(e[0].split("/")[1]):null}();return o?o<76?new mP(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):new yP(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):function(e){if(!window.RTCStatsReport)return!1;const t=e.getStats();return!!(t instanceof cp||function(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}(t))}(e)?new yP(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r}):new CP(e,{updateInterval:t,lossRateInterval:n,freezeRateLimit:i,firstVideoDecodedTimeout:r})}const IP="websdk_ng_install_id";function AP(){try{if(xP("INSTALL_ID"))return xP("INSTALL_ID");let e=window.localStorage.getItem(IP);return e||(e=MD(),window.localStorage.setItem(IP,e)),VP("INSTALL_ID",e),e}catch(e){return}}const wP=function(e){if(e.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return e;const t=e.match(/([0-9]+\.[0-9]+\.[0-9]+)\-([0-9]+)/);if(t&&t[1]&&t[2]){const e=t[1],n=t[2];return"".concat(e,".").concat(n)}return"4.0.0.999"}("4.24.8"),OP=function(){try{return!0===JSON.parse("true")}catch(e){return!0}}();let NP=function(e){return e.Default="default",e.Auto="auto",e.Relay="relay",e.SdRtn="sd-rtn",e}({});const DP=function(){const e="us".concat("erna","me"),t="pa".concat("sswo","rd"),n=["t","s","t"];n.splice(1,0,"e");const i=n.join(""),r=[];for(let e=0;e<6;e++)r.push("1");const o=r.join(""),s={};return s[e]=i,s[t]=o,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=DP;const PP={ENABLE_PUBLISHED_USER_LIST:!0,ENABLE_USER_LIST:!1,MAX_SUBSCRIPTION:50,SUBSCRIBE_AUDIO_FILTER_TOPN:void 0,ENABLE_PUBLISH_AUDIO_FILTER:void 0,ENABLE_USER_LICENSE_CHECK:!0,DISABLE_FEC:void 0,ENABLE_NTP_REPORT:!0,ENABLE_INSTANT_VIDEO:!1,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_LOSSBASED_BWE:!0,ENABLE_AUT_CC:!0,FORCE_ENABLE_AUT_CC:!1,ENABLE_CC_FALLBACK:void 0,SUBSCRIBE_TWCC:!0,PUBLISH_TWCC:!1,ENABLE_SVC_DEFAULT_CODECS:["H264","VP8","VP9","AV1"],SVC:[],ENABLE_FULL_LINK_AV_SYNC:!1,SVC_MODE:null,ENABLE_AUT_FEEDBACK:!0,SVC_EXTENDED:["VP9"],ENABLE_AP_COMPRESS:!0},LP={MIN_FRAME_RATE:1,MAX_FRAME_RATE:30,MAX_THRESHOLD_FRAMERATE:30,BITRATE_MIN_THRESHOLD:100,BITRATE_MAX_THRESHOLD:100,MAX_SCALE:5,BWE_SCALE_UP_THRESHOLD:.6,BWE_SCALE_DOWN_THRESHOLD:.6,PERF_SCALE_UP_THRESHOLD:.7,PERF_SCALE_DOWN_THRESHOLD:.6,MOTION_RESOLUTION_FACTOR:.8,MOTION_BITRATE_FACTOR:.6,DETAIL_FRAMERATE_FACTOR:.8,DETAIL_BITRATE_FACTOR:.6,BALANCE_RESOLUTION_FACTOR:.9,BALANCE_FRAMERATE_FACTOR:.9,BALANCE_BITRATE_FACTOR:.6,OVERUSE_TIMES_THRESHOLD:10,UNDERUSE_TIMES_THRESHOLD:40},kP="v4.24.8-0-gf100be755-dirty(8/31/2026, 4:23:50 PM)",MP={ENABLE_EVENT_REPORT:!0,UPLOAD_LOG:!1,ENABLE_AG_ADAPTATION:!0,FORCE_AG_HIGH_FRAMERATE:!1,FORCE_SUPPORT_AG_ADAPTATION:!1,ENCODER_CONFIG_LIMIT:{},CAMERA_CAPTURE_CONFIG:void 0,ENABLE_PRELOAD:!0,ENABLE_CREATE_CLIENT_PRECONNECT:!0,CREATE_CLIENT_PRECONNECT_MODE:"report",CREATE_CLIENT_PRECONNECT_KEEPALIVE:!1,CREATE_CLIENT_PRECONNECT_INTERVAL_MS:55e3,NEW_ICE_RESTART:!0,ICE_RESTART_INTERVAL:1e4,RESTART_SEQUENCE:["udp_tcp_relay","relay"],FIRST_TCP_CANDIDATE:!1,MAX_CONFIG_RETRY:10,ENABLE_CONFIG_RESTORE:!1,CONFIG_RESTORE_ERROR_API:["createClient","Client.join"],CONFIG_ERROR_MONITOR:["INVALID_OPERATION","UNEXPECTED_ERROR"],BLOCKED_CONFIG_MAX_TIME:864e5,FIRST_TCP_CANDIDATE_INTERVAL:1e3,TURN_DOMAIN:"edge.agora.io",TURN_DOMAINS:["edge.agora.io"],USE_TURN_IP:!0,NEW_TURN_MODE:4,NEW_FORCE_TURN:!1,USE_NEW_RENDER_FREEZE_TIME:!0,FLS_FALLBACK_TIMEOUT:3e4,RTE_DETAIL_REPORT_INTERVAL:6e4,ENCODE_EXCEPTION_TIMES:5,ENABLE_ENCODE_EXCEPTION:!0,ENCODE_EXCEPTION_VALIDATE_CODEC:["h264"],VIDEO_ENCODER_CONFIG_LIST:[{width:240,height:180},{width:320,height:240},{width:400,height:300},{width:480,height:360},{width:560,height:420},{width:640,height:480}],DELETE_NEQ_AFTER_USER_LEAVE:!0,UPDATE_RTP_CAP_IN_HOST:!1,IOS_BG_TAG:!0,IOS_AUTO_RESTART_BG_TAG:!0,IGNORE_UID_CHECK:!1,ENABLE_UP_SPS_PPS:!1,ENABLE_DOWN_SPS_PPS:!0,NO_EDGES_RETRY:!0,BUFFER_READY_FRAMES:3,FLS_SYNC_AV_PLAY_LIMIT:0,FLS_BUFFER_WAIT_TIME:1500,VOS_CONFIGURE:void 0,ENABLE_QUALITY_FALLBACK:!1,QUALITY_FALLBACK_REHEARSAL:!0,ENABLE_FLS_AV1_FIRST:!1,ENABLE_AP_MULTI_IP:!0,FLS_ENABLE_AV1_DETECT:!0,FLS_ENABLE_AV1_DECODE_DETECT:!0,ENABLE_SDP_ENDPOINT_LOG:!1,REMOTE_VIDEO_FREEZE_TIME_VERSION:2,ENABLE_ICE_EARLY_JOIN:!0},UP=IN(IN(IN(IN({},MP),{},{PROCESS_ID:"",ENCRYPT_AES:!0,AREAS:["CHINA","GLOBAL"],WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io","webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io","webrtc2-4.ap.sd-rtn.com"],SDP_ENDPOINT_DOMAIN:["sdp-ap-web-1.rtnsvc.com","sdp-ap-web-1.rtesvc.com"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-web-2.ap.sd-rtn.com","cds-ap-web-3.agora.io","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-web-2.ap.sd-rtn.com","sua-ap-web-3.agora.io","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-ap-web-1.agora.io","uap-web-2.ap.sd-rtn.com","uap-ap-web-3.agora.io","uap-web-4.ap.sd-rtn.com"],LOG_UPLOAD_SERVER:"logservice.agora.io",EVENT_REPORT_DOMAIN:"statscollector-1.agora.io",EVENT_REPORT_BACKUP_DOMAIN:"web-2.statscollector.sd-rtn.com",GATEWAY_ADDRESS:[],GATEWAY_WSS_ADDRESS:"",LIVE_STREAMING_ADDRESS:"",HTTP_CONNECT_TIMEOUT:5e3,SIGNAL_REQUEST_TIMEOUT:1e4,REPORT_STATS:!0,NOT_REPORT_EVENT:[],PING_PONG_TIME_OUT:10,WEBSOCKET_TIMEOUT_MIN:1e4,EVENT_REPORT_SEND_INTERVAL:3e3,CONFIG_DISTRIBUTE_INTERVAL:3e5,ENABLE_CONFIG_DISTRIBUTE:!0,CANDIDATE_TIMEOUT:5e3,SHOW_REPORT_INVOKER_LOG:!1,SHOW_REPORT_USER_INVOKER_LOG:!0,JOIN_EXTEND:"",PUB_EXTEND:"",SUB_EXTEND:"",FORCE_TURN:!1,TURN_ENABLE_TCP:!0,TURN_ENABLE_UDP:!0,MAX_UPLOAD_CACHE:50,UPLOAD_CACHE_INTERVAL:2e3,AJAX_REQUEST_CONCURRENT:3,REPORT_APP_SCENARIO:void 0,GATEWAY_DOMAINS:["edge.agora.io","edge.sd-rtn.com"],CONNECT_GATEWAY_WITHOUT_DOMAIN:!1,WORKER_DOMAIN:"edge.agora.io",EVENT_REPORT_RETRY:!0,CHROME_FORCE_PLAN_B:!1,AUDIO_SOURCE_VOLUME_UPDATE_INTERVAL:400,AUDIO_SOURCE_AVG_VOLUME_DURATION:3e3,AUDIO_VOLUME_INDICATION_INTERVAL:2e3,VOLUME_VOICE_WEIGHT:10,GET_VOLUME_OF_MUTED_AUDIO_TRACK:!1,STATS_UPDATE_INTERVAL:250,NORMAL_EVENT_QUEUE_CAPACITY:100,CUSTOM_REPORT:!0,CUSTOM_REPORT_LIMIT:20,PROXY_SERVER_TYPE2:"webnginx-proxy.agora.io",PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com","webrtc-cloud-proxy.agora.io"],CUSTOM_PUB_ANSWER_MODIFIER:null,CUSTOM_SUB_ANSWER_MODIFIER:null,CUSTOM_PUB_OFFER_MODIFIER:null,CUSTOM_SUB_OFFER_MODIFIER:null,DSCP_TYPE:"high",REMOVE_NEW_CODECS:!0,FRAGEMENT_LENGTH:3,WEBSOCKET_COMPRESS:!1,SIMULCAST:!1,CHECK_VIDEO_VISIBLE_INTERVAL:3e4,CHECK_LOCAL_STATS_INTERVAL:250,PROFILE_SWITCH_INTERVAL:2e3,UNSUPPORTED_VIDEO_CODEC:[],ENUMERATE_DEVICES_INTERVAL:!1,ENUMERATE_DEVICES_INTERVAL_TIME:1e4,USE_NEW_TOKEN:!1,CLOSE_AFB_FOR_LOCAL_AP:!0,JOIN_MAX_CONCURRENCY:6,JOIN_WITH_FALLBACK_SIGNAL_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY:!0,JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE:!1,JOIN_GATEWAY_TRY_443PORT_DURATION:2e3,JOIN_GATEWAY_USE_443PORT_ONLY:!1,JOIN_GATEWAY_USE_DUAL_DOMAIN:!0,JOIN_GATEWAY_FALLBACK_PORT:443,USE_TURN_SERVER_OF_GATEWAY:!1,H264_PROFILE_LEVEL_ID:"",USE_NEW_LOG:!1,LOG_VERSION:3,MEDIA_DEVICE_CONSTRAINTS:null,ENCRYPT_PROXY_USERNAME_AND_PSW:!0,SDP_LOGGING:!1,CSP_DETECTED_HOSTNAME_LIST:["agora.io","sd-rtn.com"],REMOTE_AUDIO_TRACK_USES_WEB_AUDIO:!1,LOCAL_AUDIO_TRACK_USES_WEB_AUDIO:!1,BITRATE_ADAPTER_TYPE:"STANDARD_BITRATE",AI_DENOISER_PARAMETERS:{excludedLinks:[]},ADJUST_3A_FROM_PLUGINS:!0,RAISE_H264_BASELINE_PRIORITY:!0,FILTER_SEND_H264_BASELINE:!1,FIRST_H264_PROFILE_LEVEL_ID:"42001f",FIRST_PACKETIZATION_MODE:"",X_GOOGLE_START_BITRATE:void 0,NEW_REPORT_SERVER:!1,NEW_REPORT_SERVER_DOMAINS:["data-reporting.agora.io","data-reporting.agora.io"],VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT:3e5,VIDEO_INSPECT_INTERVAL_MINIMUM:1e3,VIDEO_INSPECT_QUALITY_RATIO:.9,VIDEO_INSPECT_WORKER_MANAGER_HOST:"edge.agora.io",VIDEO_INSPECT_WORKER_MANAGER_PORT:"",VIDEO_INSPECT_WORKER_MANAGER_WSS:"",VIDEO_INSPECT_WORKER_PORT:"",SHOW_VIDEO_INSPECT_WORKER_MESSAGE:!1,STATS_COLLECTOR_PORT:443,FORCE_TURN_TCP:!1,WEBAUDIO_INIT_OPTIONS:void 0,FILTER_VIDEO_FEC:!0,FILTER_AUDIO_FEC:!1,CHROME_DUAL_STREAM_USE_ENCODING:!0,DISABLE_DUAL_STREAM_USE_ENCODING:!1,EXTENSION_USAGE_UPLOAD_INTERVAL:1e4,ICE_RESTART:!0,FINGERPRINT:null,ENABLE_VIDEO_FRAME_CALLBACK:!0,VIDEO_FREEZE_DURATION:500,SPATIALIZER_PARAMETERS:{},UPLOAD_LOG_INTERVAL:3e3,UPLOAD_LOG_REQUEST_RETRY_INTERVAL:2e3,UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL:2e4,UPLOAD_LOG_TRY_INTERVAL_WHILE_OFF:5e3,UPLOAD_LOG_RETRY_INTERVAL_V1:1e4,UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1:200,UPLOAD_LOG_LENGTH_EACH_TIME:10,APP_TYPE:0,DISABLE_WEBAUDIO:!1,CHANNEL_MEDIA_RELAY_SERVERS:void 0,KEEP_LAST_FRAME:!0,FORWARD_P2P_CREATION:!0,SYNC_GROUP:!0,BLOCK_LOCAL_CLIENT:!1,ENABLE_AUDIO_TOPN:!1,ENABLE_AUDIO_METADATA:!1,ENABLE_AUDIO_PTS:!1,TOPN_SMOOTH_LEVEL:void 0,TOPN_NEW_SPEAKER_DELAY:void 0,TOPN_SWITCH_HOLD_MS:void 0,TOPN_AUDIO_GAIN:void 0,TOPN_SILENCE_THRESHOLD:250,AP_AREA:!0,ENABLE_ENCODED_TRANSFORM:!1,ENABLE_VIDEO_SEI:!1,IMAGE_MODERATION_WORKER_HOST:"edge.agora.io",IMAGE_MODERATION_WORKER_WSS:"",IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT:3e5,IMAGE_MODERATION_INTERVAL_MINIMUM:1e3,SHOW_IMAGE_MODERATION_WORKER_MESSAGE:!1,IMAGE_MODERATION_QUALITY_RATIO:.9,IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL:5e3,SHOW_GLOBAL_CLIENT_LIST:!1,DATASTREAM_MAX_RETRANSMITS:10,TCP_CANDIDATE_ONLY:!1,EXTERNAL_SIGNAL_REQUEST_TIMEOUT:3e3,SHOW_P2P_LOG:!1,MAX_P2P_TIMEOUT:3e4,P2P_TOKEN_INTERVAL:1e3,SHOW_DATASTREAM2_LOG:!1,RESTRICTION_SET_PLAYBACK_DEVICE:!0,USE_PURE_ENCRYPTION_MASTER_KEY:!1,ENABLE_AUDIO_RED:!1,OPUS_PTIME:void 0,AUDIO_DUPLICATE_NUM:void 0,ENABLE_ABSSENDTIME_AS_SENTTS:!0,ACCOUNT_REGISTER_RETRY_TIMEOUT:1,ACCOUNT_REGISTER_RETRY_RATIO:2,ACCOUNT_REGISTER_RETRY_TIMEOUT_MAX:6e4,ACCOUNT_REGISTER_RETRY_COUNT_MAX:1e5,AUDIO_CONTEXT:null,WEBCS_BACKUP_CONNECT_TIMEOUT:6e3,PLAYER_STATE_DEFER:2e3,SIGNAL_REQUEST_WATCH_INTERVAL:1e3,FILEPATH_LENMAX:255,DUALSTREAM_OPERATION_CHECK:!0,MEDIA_ELEMENT_EXISTS_DEPTH:3,SHIM_CANDIDATE:!1,LEAVE_MSG_TIMEOUT:2e3,STATS_FILTER:{transportId:!0,googTrackId:!0},FILTER_VIDEO_CODEC:[],SIGNAL_CHANNEL:0,TRANSMITTER_INITIAL_RTT:30,TRANSMITTER_INITIAL_RTO:30,TRANSMITTER_MAX_BATCH_ACK_COUNT:2,TRANSMITTER_MAX_RTO:500,DATACHANNEL_COMPRESS:!1,DC_JOIN_WITH_FAILBACK:4e3,DC_CONNECTION_TIMEOUT:2e3,DC_PINGPONG_INTERVAL:2e3,DC_DEBUG_LOG:!1,UNSUPPORTED_VIDEO_UPLINK_CODEC:[],UNSUPPORTED_VIDEO_DOWNLINK_CODEC:[],USE_NEW_NETWORK_CONFIG:!1,AUTO_RESET_AUDIO_ROUTE:!1,PLUGIN_INFO:[],OVERUSE_DETECTOR_PARAMS:LP,CUSTOM_ADAPTATION_DEFAULT_MODE:"",HIDE_NO_POSTER:!1,AP_CACHE_NUM:10,AP_UPDATE_INTERVAL:12e4,AP_CACHE_LIFETIME:12e4,MAX_PRELOAD_ASYNC_LENGTH:3,DISABLE_SCREEN_SHARE_REMB:!1},PP),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1,AP_REQUEST_DETAIL:void 0,AP_REQUEST_DETAIL_EXTEND:void 0,ENABLE_ROLE_SELECT_EDGE:!1,CLIENT_ROLE_OPTIONS:void 0,REMOTE_VIDEO_STREAM_TYPE:void 0,COMPATIBLE_SDP_EXTENSION:["gdpr_forbidden"],LIMIT_BITRATE:void 0,EXPERIMENTS:{},USE_PUB_RTX:!0,USE_SUB_RTX:!0,ENABLE_DATASTREAM_2:!1,USE_XR:!0,ENABLE_PREALLOC_PC:!1,FLEXIBLE_PC:!1,ENABLE_PRE_SUB:!1,ENABLE_JOIN_V4:!1,ENABLE_SVC:!1,ENABLE_FORCE_HLS:!1,MAX_WEBAUDIO_VOLUME:300,ENABLE_VOS_FALLBACK:!1,ENABLE_FALLBACK_TO_HLS:!1,ENABLE_PRE_RENDER:!1,FORCE_DISABLE_AUTO_SUB:!1,ENABLE_PRE_SUB_WITH_PRE_PC:!0,PRE_USE_LOCAL_CODECS:!0},{INSTALL_ID:""}),{},{K_MIN_RENDER_DELAY:66,USE_STANDARD_BITRATE_DEFAULT:!1,VIDEO_NEW_BITRATE_RATIO:void 0,VIDEO_STANDARD_BITRATE_VERSION:2,BASELINE_MORE_H264_BITRATE_RATIO:1.1,IGNORE_RTC_DEVICE_CHECK:!1,FLS_AUTOPLAY_EMITS:!1,ENABLE_DUAL_STREAM_FLAG:!1,FORBID_MODIFY_LOCAL_OFFER_SDP:!1,RESERVE_MID_1_MLINE:!1,PRE_SUB_NUM:1,DC_IN_ESM:!0,PRE_PLAYOUT_DELAY_HINT:void 0});function VP(e,t,n){var i,r,o;Ui(i=Object.keys(UP)).call(i,e)&&(!n&&Ui(r=Object.keys(BP)).call(r,e)||(UP[e]=t,"ENABLE_VIDEO_SEI"!==e&&"ENABLE_AUDIO_TOPN"!==e&&"ENABLE_AUDIO_METADATA"!==e&&"ENABLE_AUDIO_PTS"!==e||!0!==t||(UP.ENABLE_ENCODED_TRANSFORM=!0),"USE_NEW_NETWORK_CONFIG"===e&&t&&(o=!!t,UP.USE_NEW_NETWORK_CONFIG=o,o&&(UP.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],UP.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],UP.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],UP.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UP.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",UP.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",UP.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),"ENABLE_PRE_SUB"===e&&t&&(UP.ENABLE_INSTANT_VIDEO=!0,UP.ENABLE_PREALLOC_PC=!0),"ENABLE_SVC"===e&&t&&(UP.ENABLE_AUT_CC=!0),"NEW_FORCE_TURN"===e&&t&&(UP.NEW_TURN_MODE||(UP.NEW_TURN_MODE=4))))}function xP(e){if("TURN_DOMAINS"===e){const e=UP.TURN_DOMAINS;return Ui(e).call(e,xP("TURN_DOMAIN"))?e:[xP("TURN_DOMAIN")].concat(e)}return UP[e]}OP||(UP.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],UP.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],UP.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],UP.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],UP.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UP.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],UP.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",UP.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",UP.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",UP.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",UP.AREAS=["NORTH_AMERICA","OVERSEA"]);let FP=function(e){return e[e.REALTIME=1]="REALTIME",e}({});const BP={};var jP=function(e){return e.SET_SESSION_ID="SET_SESSION_ID",e.SET_RTE_URL="SET_RTE_URL",e.SET_RTE_SID="SET_RTE_SID",e.SET_P2P_ID="SET_P2P_id",e.SET_DC_ID="SET_DC_id",e.SET_UID="SET_UID",e.SET_INT_UID="SET_INT_UID",e.SET_PUB_ID="SET_PUB_ID",e.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",e.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",e.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",e.KEY_METRIC_PRELOAD_START="KEY_METRIC_PRELOAD_START",e.KEY_METRIC_PRELOAD_END="KEY_METRIC_PRELOAD_END",e.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",e.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",e.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",e.KEY_METRIC_REQUEST_SUA_END="KEY_METRIC_REQUEST_SUA_END",e.KEY_METRIC_BEFORE_CONNECT="KEY_METRIC_BEFORE_CONNECT",e.KEY_METRIC_PEER_RECEIVER="KEY_METRIC_PEER_RECEIVER",e.KEY_METRIC_SIGNAL_CONNECTED="KEY_METRIC_SIGNAL_CONNECTED",e.KEY_METRIC_JOIN_REQ="KEY_METRIC_JOIN_REQ",e.KEY_METRIC_JOIN_REP="KEY_METRIC_JOIN_REP",e.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",e.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",e.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",e.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",e.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED="KEY_METRIC_FIRST_VIDEO_FRAME_DECODED",e.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",e.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",e.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",e.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",e.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",e.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",e.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",e.RESET_KEY_METRICS="RESET_KEY_METRICS",e.RESET_FIRST_VIDEO_FRAME_DECODED="RESET_FIRST_VIDEO_FRAME_DECODED",e.SET_USE_P2P="SET_USE_P2P",e.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE",e}(jP||{});let GP=function(e){return e.h264="h264",e.h265="h265",e.vp8="vp8",e.vp9="vp9",e.av1="av1",e}({});!function(e){e.opus="opus",e.pcma="pcma",e.pcmu="pcmu",e.g722="g722"}({});const WP=128,KP=96,HP=1e3,YP=10;let XP=0;var JP=(()=>{var e={8:(e,t,n)=>{n.r(t),n.d(t,{Parser:()=>v,Printer:()=>A,parse:()=>D,print:()=>P});const i="\n",r="".concat("\r").concat(i),o=" ";let s;function a(e){return e>="0"&&e<="9"}function c(e){return e>="!"&&e<="~"}function d(e){return c(e)||e>="€"&&e<="ÿ"}function l(e){return"!"===e||e>="#"&&e<="'"||e>="*"&&e<="+"||e>="-"&&e<="."||e>="0"&&e<="9"||e>="A"&&e<="Z"||e>="^"&&e<="~"}function u(e){return e>="1"&&e<="9"}function h(e){return e>="A"&&e<="Z"||e>="a"&&e<="z"}function p(e){return"d"===e||"h"===e||"m"===e||"s"===e}function _(e){return e>""&&e<"\t"||e>"\v"&&e<"\f"||e>""&&e<"ÿ"}function E(e){return h(e)||a(e)||"+"===e||"/"===e}function m(e){return a(e)||h(e)||"+"===e||"/"===e||"-"===e||"_"===e}function f(e){return h(e)||a(e)||"+"===e||"/"===e}function g(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function S(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?g(Object(n),!0).forEach((function(t){T(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function T(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e){e.VERSION="v",e.ORIGIN="o",e.SESSION_NAME="s",e.INFORMATION="i",e.URI="u",e.EMAIL="e",e.PHONE="p",e.CONNECTION="c",e.BANDWIDTH="b",e.TIME="t",e.REPEAT="r",e.ZONE_ADJUSTMENTS="z",e.KEY="k",e.ATTRIBUTE="a",e.MEDIA="m"}(s||(s={}));class R{consumeText(e,t){let n=t;for(;n<e.length;){const t=e[n];if("\0"===t||"\r"===t||t===i)break;n+=1}if(n-t==0)throw new Error("Invalid text, at ".concat(e));return n}consumeUnicastAddress(e,t,n){return this.consumeTill(e,t,o)}consumeOneOrMore(e,t,n){let i=t;for(;n(e[i]);)i++;if(i-t==0)throw new Error("Invalid rule at ".concat(t,"."));return i}consumeSpace(e,t){if(e[t]===o)return t+1;throw new Error("Invalid space at ".concat(t,"."))}consumeIP4Address(e,t){let n=t;for(let t=0;t<4;t++)if(n=this.consumeDecimalUChar(e,n),3!==t){if("."!==e[n])throw new Error("Invalid IP4 address.");n++}return n}consumeDecimalUChar(e,t){let n=t;for(let t=0;t<3&&a(e[n]);t++,n++);if(n-t==0)throw new Error("Invalid decimal uchar.");const i=parseInt(e.slice(t,n));if(i>=0&&i<=255)return n;throw new Error("Invalid decimal uchar")}consumeIP6Address(e,t){let n=this.consumeHexpart(e,t);return":"===e[n]?(n+=1,n=this.consumeIP4Address(e,n),n):n}consumeHexpart(e,t){let n=t;if(":"===e[n]&&":"===e[n+1]){n+=2;try{n=this.consumeHexseq(e,n)}catch(e){}return n}if(n=this.consumeHexseq(e,n),":"===e[n]&&":"===e[n+1]){n+=2;try{n=this.consumeHexseq(e,n)}catch(e){}return n}return n}consumeHexseq(e,t){let n=t;for(;n=this.consumeHex4(e,n),":"===e[n]&&":"!==e[n+1];)n+=1;return n}consumeHex4(e,t){let n=0;for(;n<4;n++)if(!((i=e[t+n])>="0"&&i<="9"||i>="a"&&i<="f"||i>="A"&&i<="F")){if(0===n)throw new Error("Invalid hex 4");break}var i;return t+n}consumeFQDN(e,t){let n=t;for(;a(e[n])||h(e[n])||"-"===e[n]||"."===e[n];)n+=1;if(n-t<4)throw new Error("Invalid FQDN");return n}consumeExtnAddr(e,t){return this.consumeOneOrMore(e,t,d)}consumeMulticastAddress(e,t,n){switch(n){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(e,t);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(e,t);default:try{return this.consumeFQDN(e,t)}catch(n){return this.consumeExtnAddr(e,t)}}}consumeIP6MulticastAddress(e,t){const n=this.consumeHexpart(e,t);return"/"===e[n]?this.consumeInteger(e,n+1):n}consumeIP4MulticastAddress(e,t){let n=t+3;const i=e.slice(t,n),r=parseInt(i);if(r<224||r>239)throw new Error("Invalid IP4 multicast address, IPv4 multicast addresses may be in the range 224.0.0.0 to 239.255.255.255.");for(let t=0;t<3;t++){if("."!==e[n])throw new Error("Invalid IP4 multicast address.");n+=1,n=this.consumeDecimalUChar(e,n)}return"/"===e[n]&&(n+=1),n=this.consumeTTL(e,n),"/"===e[n]&&(n=this.consumeInteger(e,n)),n}consumeInteger(e,t){if(!u(e[t]))throw new Error("Invalid integer.");for(t+=1;a(e[t]);)t+=1;return t}consumeTTL(e,t){if("0"===e[t])return t+1;if(!u(e[t]))throw new Error("Invalid TTL.");t+=1;for(let n=0;n<2&&a(e[t]);n++)t+=1;return t}consumeToken(e,t){return this.consumeOneOrMore(e,t,l)}consumeTime(e,t){let n=t;if("0"===e[n])return n+1;for(u(e[n])&&(n+=1);a(e[n]);)n++;if(n-t<10)throw new Error("Invalid time");return n}consumeAddress(e,t){return this.consumeTill(e,t,o)}consumeTypedTime(e,t){let n=t;return n=this.consumeOneOrMore(e,n,a),p(e[n])?n+1:n}consumeRepeatInterval(e,t){if(!u(e[t]))throw new Error("Invalid repeat interval");for(t+=1;a(e[t]);)t+=1;return p(e[t])&&(t+=1),t}consumePort(e,t){return this.consumeOneOrMore(e,t,a)}consume(e,t,n){for(let i=0;i<n.length;i++){if(t+i>=e.length)throw new Error("consume exceeding value length");if(e[t+i]!==n[i])throw new Error("consume ".concat(n," failed at ").concat(i))}return t+n.length}consumeTill(e,t,n){let i=t;for(;i<e.length&&("string"!=typeof n||e[i]!==n)&&("function"!=typeof n||!n(e[i]));)i++;return i}}class v extends R{constructor(){super(),T(this,"records",[]),T(this,"currentLine",0)}parse(e){const t=this.probeEOL(e);this.records=e.split(t).filter((e=>!!zS(e).call(e))).map(this.parseLine),this.currentLine=0;const n=this.parseVersion(),i=this.parseOrigin(),r=this.parseSessionName(),o=this.parseInformation(),s=this.parseUri(),a=this.parseEmail(),c=this.parsePhone(),d=this.parseConnection(),l=this.parseBandWidth(),u=this.parseTimeFields(),h=this.parseKey(),p=this.parseSessionAttribute(),_=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:n,origin:i,sessionName:r,information:o,uri:s,emails:a,phones:c,connection:d,bandwidths:l,timeFields:u,key:h,attributes:p,mediaDescriptions:_}}getCurrentRecord(){const e=this.records[this.currentLine];if(!e)throw new Error("Record doesn't exit.");return e}probeEOL(e){for(let t=0;t<e.length;t++)if(e[t]===i)return"\r"===e[t-1]?r:i;throw new Error("Invalid newline character.")}parseLine(e,t){if(e.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const n=e[0];if("="!==e[1])throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:n,value:e.slice(2),line:t,cur:0}}parseSessionAttribute(){const e=new C;for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.ATTRIBUTE)break;const n={attField:this.extractOneOrMore(t,(e=>l(e)&&":"!==e)),_cur:0};":"===t.value[t.cur]&&(t.cur+=1,n.attValue=this.extractOneOrMore(t,_)),e.parse(n),this.currentLine++}return e.digest()}parseMediaAttributes(e){const t=new b(e);for(;this.currentLine<this.records.length;){const e=this.getCurrentRecord();if(e.type!==s.ATTRIBUTE)break;const n={attField:this.extractOneOrMore(e,(e=>l(e)&&":"!==e)),_cur:0};":"===e.value[e.cur]&&(e.cur+=1,n.attValue=this.extractOneOrMore(e,_)),t.parse(n),this.currentLine++}return t.digest()}parseKey(){const e=this.getCurrentRecord();if(e.type===s.KEY){if("prompt"===e.value||"clear:"===e.value||"base64:"===e.value||"uri:"===e.value)return e.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const e=this.getCurrentRecord();if(e.type===s.ZONE_ADJUSTMENTS){const t=[];for(;;)try{const n=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);let i=!1;"-"===e.value[e.cur]&&(i=!0,e.cur+=1);const r=this.extract(e,this.consumeTypedTime);t.push({time:n,typedTime:r,back:i})}catch(e){break}if(0===t.length)throw new Error("Invalid zone adjustments");return this.currentLine++,t}return[]}parseRepeat(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.REPEAT)break;{const n=this.extract(t,this.consumeRepeatInterval),i=this.parseTypedTime(t);e.push({repeatInterval:n,typedTimes:i}),this.currentLine++}}return e}parseTypedTime(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeTypedTime))}catch(e){break}if(0===t.length)throw new Error("Invalid typed time.");return t}parseTime(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeTime);this.consumeSpaceForRecord(e);const n=this.extract(e,this.consumeTime);return this.currentLine++,{startTime:t,stopTime:n}}parseBandWidth(){const e=[];for(;this.currentLine<this.records.length;){const t=this.getCurrentRecord();if(t.type!==s.BANDWIDTH)break;{const n=this.extractOneOrMore(t,l);if(":"!==t.value[t.cur])throw new Error("Invalid bandwidth field.");t.cur++;const i=this.extractOneOrMore(t,a);e.push({bwtype:n,bandwidth:i}),this.currentLine++}}return e}parseVersion(){const e=this.getCurrentRecord();if(e.type!==s.VERSION)throw new Error("first sdp record must be version");const t=e.value.slice(0,this.consumeOneOrMore(e.value,0,a));if(t.length!==e.value.length)throw new Error('invalid proto version, "v='.concat(e.value,'"'));return this.currentLine++,t}parseOrigin(){const e=this.getCurrentRecord();if(e.type!==s.ORIGIN)throw new Error("second line of sdp must be origin");const t=this.extractOneOrMore(e,d);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const i=this.extractOneOrMore(e,a);this.consumeSpaceForRecord(e);const r=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const o=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const c=this.extract(e,this.consumeUnicastAddress);return this.currentLine++,{username:t,sessId:n,sessVersion:i,nettype:r,addrtype:o,unicastAddress:c}}parseSessionName(){const e=this.getCurrentRecord();if(e.type===s.SESSION_NAME){const t=this.extract(e,this.consumeText);return this.currentLine++,t}}parseInformation(){const e=this.getCurrentRecord();if(e.type!==s.INFORMATION)return;const t=this.extract(e,this.consumeText);return this.currentLine++,t}parseUri(){const e=this.getCurrentRecord();if(e.type===s.URI)return this.currentLine++,e.value}parseEmail(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.EMAIL)break;e.push(t.value),this.currentLine++}return e}parsePhone(){const e=[];for(;;){const t=this.getCurrentRecord();if(t.type!==s.PHONE)break;e.push(t.value),this.currentLine++}return e}parseConnection(){const e=this.getCurrentRecord();if(e.type===s.CONNECTION){const t=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const n=this.extractOneOrMore(e,l);this.consumeSpaceForRecord(e);const i=this.extract(e,this.consumeAddress);return this.currentLine++,{nettype:t,addrtype:n,address:i}}}parseMedia(){const e=this.getCurrentRecord(),t=this.extract(e,this.consumeToken);this.consumeSpaceForRecord(e);let n=this.extract(e,this.consumePort);"/"===e.value[e.cur]&&(e.cur+=1,n+=this.extract(e,this.consumeInteger)),this.consumeSpaceForRecord(e);const i=[];for(i.push(this.extract(e,this.consumeToken));"/"===e.value[e.cur];)e.cur+=1,i.push(this.extract(e,this.consumeToken));if(0===i.length)throw new Error("Invalid proto");const r=this.parseFmt(e);return this.currentLine++,{mediaType:t,port:n,protos:i,fmts:r}}parseTimeFields(){const e=[];for(;this.getCurrentRecord().type===s.TIME;){const t=this.parseTime(),n=this.parseRepeat(),i=this.parseZone();e.push({time:t,repeats:n,zones:i})}return e}parseMediaDescription(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.MEDIA;){const t=this.parseMedia(),n=this.parseInformation(),i=this.parseConnections(),r=this.parseBandWidth(),o=this.parseKey(),s=this.parseMediaAttributes(t);e.push({media:t,information:n,connections:i,bandwidths:r,key:o,attributes:s})}return e}parseConnections(){const e=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===s.CONNECTION;)e.push(this.parseConnection());return e}parseFmt(e){const t=[];for(;;)try{this.consumeSpaceForRecord(e),t.push(this.extract(e,this.consumeToken))}catch(e){break}if(0===t.length)throw new Error("Invalid fmts");return t}extract(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];const o=t.call(this,e.value,e.cur,...i),s=e.value.slice(e.cur,o);return e.cur=o,s}extractOneOrMore(e,t){const n=this.consumeOneOrMore(e.value,e.cur,t),i=e.value.slice(e.cur,n);return e.cur=n,i}consumeSpaceForRecord(e){if(e.value[e.cur]!==o)throw new Error("Invalid space at ".concat(e.cur,"."));e.cur+=1}}class y extends R{constructor(){super(...arguments),T(this,"attributes",void 0),T(this,"digested",!1)}extractOneOrMore(e,t,n){const i=this.consumeOneOrMore(e.attValue,e._cur,t),r=e.attValue.slice(e._cur,i),o=KC(n||[],2),s=o[0],a=o[1];if("number"==typeof s&&r.length<s)throw new Error("error in length, should be more or equal than ".concat(s," characters."));if("number"==typeof a&&r.length>a)throw new Error("error in length, should be less or equal than ".concat(a," characters."));return e._cur=i,r}consumeAttributeSpace(e){if(e.attValue[e._cur]!==o)throw new Error("Invalid space at ".concat(e._cur,"."));e._cur+=1}extract(e,t){if(!e.attValue)throw new Error("Nothing to extract from attValue.");for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];const o=t.call(this,e.attValue,e._cur,...i),s=e.attValue.slice(e._cur,o);return e._cur=o,s}atEnd(e){if(!e.attValue)throw new Error;return e._cur>=e.attValue.length}peekChar(e){if(!e.attValue)throw new Error;return e.attValue[e._cur]}peek(e,t){if(!e.attValue)throw new Error;for(let n=0;n<t.length;n++)if(t[n]!==e.attValue[e._cur+n])return!1;return!0}parseIceUfrag(e){if(this.attributes.iceUfrag)throw new Error("Invalid ice-ufrag, should be only a single line if 'a=ice-ufrag'");this.attributes.iceUfrag=this.extractOneOrMore(e,E,[4,256])}parseIcePwd(e){if(this.attributes.icePwd)throw new Error("Invalid ice-pwd, should be only a single line if 'a=ice-pwd'");this.attributes.icePwd=this.extractOneOrMore(e,E,[22,256])}parseIceOptions(e){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const t=[];for(;!this.atEnd(e);){t.push(this.extractOneOrMore(e,E));try{this.consumeAttributeSpace(e)}catch(t){if(this.atEnd(e))break;throw t}}this.attributes.iceOptions=t}parseFingerprint(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill);this.attributes.fingerprints.push({hashFunction:t,fingerprint:n})}parseExtmap(e){const t=this.extractOneOrMore(e,a);let n;"/"===this.peekChar(e)&&(this.extract(e,this.consume,"/"),n=this.extract(e,this.consumeToken)),this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeTill,o),r=S(S({entry:parseInt(t,10)},n&&{direction:n}),{},{extensionName:i});this.peekChar(e)===o&&(this.consumeAttributeSpace(e),r.extensionAttributes=this.extract(e,this.consumeTill)),this.attributes.extmaps.push(r)}parseSetup(e){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const t=this.extract(e,this.consumeTill);if("active"!==t&&"passive"!==t&&"actpass"!==t&&"holdconn"!==t)throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=t}}class C extends y{constructor(){super(...arguments),T(this,"attributes",{unrecognized:[],groups:[],extmaps:[],fingerprints:[],identities:[]})}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"group":this.parseGroup(e);break;case"ice-lite":this.parseIceLite();break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"fingerprint":this.parseFingerprint(e);break;case"setup":this.parseSetup(e);break;case"tls-id":this.parseTlsId(e);break;case"identity":this.parseIdentity(e);break;case"extmap":this.parseExtmap(e);break;case"msid-semantic":this.parseMsidSemantic(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing session attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}digest(){return this.digested=!0,this.attributes}parseGroup(e){const t=this.extract(e,this.consumeToken),n=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;)this.consumeAttributeSpace(e),n.push(this.extract(e,this.consumeToken));this.attributes.groups.push({semantic:t,identificationTag:n})}parseIceLite(){if(this.attributes.iceLite)throw new Error("Invalid ice-lite, should be only a single line of 'a=ice-lite'");this.attributes.iceLite=!0}parseTlsId(e){if(this.attributes.tlsId)throw new Error("must be only one tld-id line");this.attributes.tlsId=this.extractOneOrMore(e,m)}parseIdentity(e){const t=this.extractOneOrMore(e,f),n=[];for(;!this.atEnd(e)&&this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.extract(e,this.consume,"=");const i=this.extractOneOrMore(e,(e=>e!==o&&_(e)));n.push({name:t,value:i})}this.attributes.identities.push({assertionValue:t,extensions:n})}parseMsidSemantic(e){this.peekChar(e)===o&&this.consumeAttributeSpace(e);const t={semantic:this.extract(e,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(e)}catch(e){break}if("*"===this.peekChar(e)){this.extract(e,this.consume,"*"),t.applyForAll=!0;break}{const n=this.extract(e,this.consumeTill,o);t.identifierList.push(n)}}this.attributes.msidSemantic=t}}class b extends y{constructor(e){super(),T(this,"attributes",void 0),-1!==e.protos.indexOf("RTP")||e.protos.indexOf("rtp"),this.attributes={unrecognized:[],candidates:[],extmaps:[],fingerprints:[],imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[]}}parse(e){if(this.digested)throw new Error("already digested");try{switch(e.attField){case"extmap":this.parseExtmap(e);break;case"setup":this.parseSetup(e);break;case"ice-ufrag":this.parseIceUfrag(e);break;case"ice-pwd":this.parseIcePwd(e);break;case"ice-options":this.parseIceOptions(e);break;case"candidate":this.parseCandidate(e);break;case"remote-candidate":this.parseRemoteCandidate(e);break;case"end-of-candidates":this.parseEndOfCandidates();break;case"fingerprint":this.parseFingerprint(e);break;case"rtpmap":this.parseRtpmap(e);break;case"ptime":this.parsePtime(e);break;case"maxptime":this.parseMaxPtime(e);break;case"sendrecv":case"recvonly":case"sendonly":case"inactive":this.parseDirection(e);break;case"ssrc":this.parseSSRC(e);break;case"fmtp":this.parseFmtp(e);break;case"rtcp-fb":this.parseRtcpFb(e);break;case"rtcp-mux":this.parseRTCPMux();break;case"rtcp-mux-only":this.parseRTCPMuxOnly();break;case"rtcp-rsize":this.parseRTCPRsize();break;case"rtcp":this.parseRTCP(e);break;case"mid":this.parseMid(e);break;case"msid":this.parseMsid(e);break;case"imageattr":this.parseImageAttr(e);break;case"rid":this.parseRid(e);break;case"simulcast":this.parseSimulcast(e);break;case"sctp-port":this.parseSctpPort(e);break;case"max-message-size":this.parseMaxMessageSize(e);break;case"ssrc-group":this.parseSSRCGroup(e);break;default:e.ignored=!0,this.attributes.unrecognized.push(e)}}catch(t){throw console.error("parsing media attribute ".concat(e.attField,' error, "a=').concat(e.attField,":").concat(e.attValue,'"')),t}if(!e.ignored&&e.attValue&&!this.atEnd(e))throw new Error("attribute parsing error")}parseCandidate(e){const t=this.extractOneOrMore(e,E,[1,32]);this.consumeAttributeSpace(e);const n=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const r=this.extractOneOrMore(e,a,[1,10]);this.consumeAttributeSpace(e);const s=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const d=this.extract(e,this.consumePort);this.consumeAttributeSpace(e),this.extract(e,this.consume,"typ"),this.consumeAttributeSpace(e);const l={foundation:t,componentId:n,transport:i,priority:r,connectionAddress:s,port:d,type:this.extract(e,this.consumeToken),extension:{}};for(this.peek(e," raddr")&&(this.extract(e,this.consume," raddr"),this.consumeAttributeSpace(e),l.relAddr=this.extract(e,this.consumeAddress)),this.peek(e," rport")&&(this.extract(e,this.consume," rport"),this.consumeAttributeSpace(e),l.relPort=this.extract(e,this.consumePort));this.peekChar(e)===o;){this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e),l.extension[t]=this.extractOneOrMore(e,c)}this.attributes.candidates.push(l)}parseRemoteCandidate(e){const t=[];for(;;){const n=this.extractOneOrMore(e,a,[1,5]);this.consumeAttributeSpace(e);const i=this.extract(e,this.consumeAddress);this.consumeAttributeSpace(e);const r=this.extract(e,this.consumePort);t.push({componentId:n,connectionAddress:i,port:r});try{this.consumeAttributeSpace(e)}catch(e){break}}this.attributes.remoteCandidatesList.push(t)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(e){const t=this.extract(e,this.consumeToken);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,"/");this.extract(e,this.consume,"/");const i={encodingName:n,clockRate:this.extractOneOrMore(e,a)};this.atEnd(e)||"/"!==this.peekChar(e)||(this.extract(e,this.consume,"/"),i.encodingParameters=parseInt(this.extract(e,this.consumeTill),10));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.rtpMap=i:this.attributes.payloads.push({payloadType:parseInt(t,10),rtpMap:i,rtcpFeedbacks:[]})}parsePtime(e){if(this.attributes.ptime)throw new Error("must be only one line of ptime");this.attributes.ptime=this.extract(e,this.consumeTill)}parseMaxPtime(e){if(this.attributes.maxPtime)throw new Error("must be only one line of ptime");this.attributes.maxPtime=this.extract(e,this.consumeTill)}parseDirection(e){if(this.attributes.direction)throw new Error("must be only one line of direction info");this.attributes.direction=e.attField}parseSSRC(e){const t=this.extractOneOrMore(e,a);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,":");let i;":"===this.peekChar(e)&&(this.extract(e,this.consume,":"),i=this.extract(e,this.consumeTill));const r=this.attributes.ssrcs.find((e=>e.ssrcId===parseInt(t,10)));r?r.attributes[n]=i:this.attributes.ssrcs.push({ssrcId:parseInt(t,10),attributes:{[n]:i}})}parseFmtp(e){const t=this.extract(e,this.consumeTill,o);this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill),i={};n.split(";").forEach((e=>{let t=KC(e.split("="),2),n=t[0],r=t[1];n=zS(n).call(n);const o="string"==typeof r?zS(r).call(r):null;"string"==typeof n&&n.length>0&&(i[n]=o)}));const r=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));r?r.fmtp={parameters:i}:this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[],fmtp:{parameters:i}})}parseFmtParameters(e){const t={},n=this.extract(e,this.consumeTill,"=");e._cur++;const i=this.extract(e,this.consumeTill,";");for(t[n]=i;";"===e.attValue[e._cur];){const n=this.extract(e,this.consumeTill,"=");e._cur++;const i=this.extract(e,this.consumeTill,";");t[n]=i}return t}parseRtcpFb(e){let t="";t="*"===this.peekChar(e)?this.extract(e,this.consume,"*"):this.extract(e,this.consumeTill,o),this.consumeAttributeSpace(e);const n=this.extract(e,this.consumeTill,o);let i;if("trr-int"===n)i={type:n,interval:this.extract(e,this.consumeTill)};else{const t={type:n};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.parameter=this.extract(e,this.consumeToken),this.peekChar(e)===o&&(t.additional=this.extract(e,this.consumeTill))),i=t}if("*"===t)this.attributes.rtcpFeedbackWildcards.push(i);else{const e=this.attributes.payloads.find((e=>e.payloadType===parseInt(t,10)));e?e.rtcpFeedbacks.push(i):this.attributes.payloads.push({payloadType:parseInt(t,10),rtcpFeedbacks:[i]})}}parseRTCPMux(){if(this.attributes.rtcpMux)throw new Error("must be single line of rtcp-mux");this.attributes.rtcpMux=!0}parseRTCPMuxOnly(){if(this.attributes.rtcpMuxOnly)throw new Error("must be single line of rtcp-only");this.attributes.rtcpMuxOnly=!0}parseRTCPRsize(){if(this.attributes.rtcpRsize)throw new Error("must be single line of rtcp-rsize");this.attributes.rtcpRsize=!0}parseRTCP(e){if(this.attributes.rtcp)throw new Error("must be single line of rtcp");const t={port:this.extract(e,this.consumePort)};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.netType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.addressType=this.extractOneOrMore(e,l),this.consumeAttributeSpace(e),t.address=this.extract(e,this.consumeAddress)),this.attributes.rtcp=t}parseMsid(e){const t={id:this.extractOneOrMore(e,l,[1,64])};this.peekChar(e)===o&&(this.consumeAttributeSpace(e),t.appdata=this.extractOneOrMore(e,l,[1,64])),this.attributes.msids.push(t)}parseImageAttr(e){this.attributes.imageattr.push(e.attValue)}parseRid(e){const t=this.extractOneOrMore(e,(e=>h(e)||a(e)||"_"===e||"-"===e));this.consumeAttributeSpace(e);const n={id:t,direction:this.extract(e,this.consumeToken),params:[]};if(this.peekChar(e)===o){if(this.consumeAttributeSpace(e),this.peek(e,"pt=")){this.extract(e,this.consume,"pt=");const t=[];for(;;){const n=this.extract(e,this.consumeToken);t.push(n);try{this.extract(e,this.consume,",")}catch(e){break}}n.payloads=t,this.peekChar(e)===o&&this.extract(e,this.consume,o)}for(;;){const t=this.extract(e,this.consumeToken);switch(t){case"depend":{const i={type:t,rids:this.extract(e,this.consume,"=").split(",")};n.params.push(i);break}default:{const i={type:t};"="===this.peekChar(e)&&(this.extract(e,this.consume,"="),i.val=this.extract(e,this.consumeTill,";")),n.params.push(i)}}try{this.extract(e,this.consume,";")}catch(e){break}}}this.attributes.rids.push(n)}parseSimulcast(e){if(this.attributes.simulcast)throw new Error("must be single line of simulcast");this.attributes.simulcast=e.attValue,this.extract(e,this.consumeTill)}parseSctpPort(e){this.attributes.sctpPort=this.extractOneOrMore(e,a,[1,5])}parseMaxMessageSize(e){this.attributes.maxMessageSize=this.extractOneOrMore(e,a,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(e){this.attributes.mid=this.extract(e,this.consumeToken)}parseSSRCGroup(e){const t=this.extract(e,this.consumeToken),n=[];for(;;)try{this.consumeAttributeSpace(e);const t=this.extract(e,this.consumeInteger);n.push(parseInt(t,10))}catch(e){break}this.attributes.ssrcGroups.push({semantic:t,ssrcIds:n})}}function I(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}class A{constructor(){I(this,"eol",r)}print(e,t){let n="";return t&&(this.eol=t),n+=this.printVersion(e.version),n+=this.printOrigin(e.origin),n+=this.printSessionName(e.sessionName),n+=this.printInformation(e.information),n+=this.printUri(e.uri),n+=this.printEmail(e.emails),n+=this.printPhone(e.phones),n+=this.printConnection(e.connection),n+=this.printBandwidth(e.bandwidths),n+=this.printTimeFields(e.timeFields),n+=this.printKey(e.key),n+=this.printSessionAttributes(e.attributes),n+=this.printMediaDescription(e.mediaDescriptions),n}printVersion(e){return"v=".concat(e).concat(this.eol)}printOrigin(e){return"o=".concat(e.username," ").concat(e.sessId," ").concat(e.sessVersion," ").concat(e.nettype," ").concat(e.addrtype," ").concat(e.unicastAddress).concat(this.eol)}printSessionName(e){return e?"s=".concat(e).concat(this.eol):""}printInformation(e){return e?"i=".concat(e).concat(this.eol):""}printUri(e){return e?"u=".concat(e).concat(this.eol):""}printEmail(e){let t="";for(const n of e)t+="e=".concat(n).concat(this.eol);return t}printPhone(e){let t="";for(const n of e)t+="e=".concat(n).concat(this.eol);return t}printConnection(e){return e?"c=".concat(e.nettype," ").concat(e.addrtype," ").concat(e.address).concat(this.eol):""}printBandwidth(e){let t="";for(const n of e)t+="b=".concat(n.bwtype,":").concat(n.bandwidth).concat(this.eol);return t}printTimeFields(e){let t="";for(const n of e){t+="t=".concat(n.time.startTime," ").concat(n.time.startTime).concat(this.eol);for(const e of n.repeats)t+="r=".concat(e.repeatInterval," ").concat(e.typedTimes.join(" ")).concat(this.eol);n.zoneAdjustments&&(t+="z=",t+="z=".concat(n.zoneAdjustments.map((e=>"".concat(e.time," ").concat(e.back?"-":""," ").concat(e.typedTime))).join(" ")).concat(this.eol),t+=this.eol)}return t}printKey(e){return e?"k=".concat(e).concat(this.eol):""}printAttributes(e){let t="";for(const n of e)t+="a=".concat(n.attField).concat(n.attValue?":".concat(n.attValue):"").concat(this.eol);return t}printMediaDescription(e){let t="";for(const n of e)t+=this.printMedia(n.media),t+=this.printInformation(n.information),t+=this.printConnections(n.connections),t+=this.printBandwidth(n.bandwidths),t+=this.printKey(n.key),t+=this.printMediaAttributes(n);return t}printConnections(e){let t="";for(const n of e)t+=this.printConnection(n);return t}printMedia(e){return"m=".concat(e.mediaType," ").concat(e.port," ").concat(e.protos.join("/")," ").concat(e.fmts.join(" ")).concat(this.eol)}printSessionAttributes(e){return new O(this.eol).print(e)}printMediaAttributes(e){return new N(this.eol).print(e)}}class w{constructor(e){I(this,"eol",void 0),this.eol=e}printIceUfrag(e){return void 0===e?"":"a=ice-ufrag:".concat(e).concat(this.eol)}printIcePwd(e){return void 0===e?"":"a=ice-pwd:".concat(e).concat(this.eol)}printIceOptions(e){return void 0===e?"":"a=ice-options:".concat(e.join(o)).concat(this.eol)}printFingerprints(e){return e.length>0?e.map((e=>"a=fingerprint:".concat(e.hashFunction).concat(o).concat(e.fingerprint))).join(this.eol)+this.eol:""}printExtmap(e){return e.map((e=>"a=extmap:".concat(e.entry).concat(e.direction?"/".concat(e.direction):"").concat(o).concat(e.extensionName).concat(e.extensionAttributes?"".concat(o).concat(e.extensionAttributes):"").concat(this.eol))).join("")}printSetup(e){return void 0===e?"":"a=setup:".concat(e).concat(this.eol)}printUnrecognized(e){return e.map((e=>"a=".concat(e.attField).concat(e.attValue?":".concat(e.attValue):"").concat(this.eol))).join("")}}class O extends w{print(e){let t="";return t+=this.printGroups(e.groups),t+=this.printMsidSemantic(e.msidSemantic),t+=this.printIceLite(e.iceLite),t+=this.printIceUfrag(e.iceUfrag),t+=this.printIcePwd(e.icePwd),t+=this.printIceOptions(e.iceOptions),t+=this.printFingerprints(e.fingerprints),t+=this.printSetup(e.setup),t+=this.printTlsId(e.tlsId),t+=this.printIdentity(e.identities),t+=this.printExtmap(e.extmaps),t+=this.printUnrecognized(e.unrecognized),t}printGroups(e){let t="";return e.length>0&&(t+=e.map((e=>"a=group:".concat(e.semantic).concat(e.identificationTag.map((e=>"".concat(o).concat(e))).join("")).concat(this.eol))).join("")),t}printIceLite(e){return void 0===e?"":"a=ice-lite"+this.eol}printTlsId(e){return e?"a=tls-id:".concat(e).concat(this.eol):""}printIdentity(e){return 0===e.length?"":e.map((e=>"a=identity:".concat(e.assertionValue).concat(e.extensions.map((e=>"".concat(o).concat(e.name).concat(e.value?"=".concat(e.value):"")))))).join(this.eol)+this.eol}printMsidSemantic(e){if(!e)return"";let t="a=msid-semantic:".concat(e.semantic);return e.applyForAll?t+="".concat(o,"*"):e.identifierList.length>0&&(t+=e.identifierList.map((e=>"".concat(o).concat(e)))),t+this.eol}}class N extends w{print(e){const t=e.attributes;let n="";return n+=this.printRTCP(t.rtcp),n+=this.printIceUfrag(t.iceUfrag),n+=this.printIcePwd(t.icePwd),n+=this.printIceOptions(t.iceOptions),n+=this.printCandidates(t.candidates),n+=this.printRemoteCandidatesList(t.remoteCandidatesList),n+=this.printEndOfCandidates(t.endOfCandidates),n+=this.printFingerprints(t.fingerprints),n+=this.printSetup(t.setup),n+=this.printMid(t.mid),n+=this.printExtmap(t.extmaps),n+=this.printRTPRelated(t),n+=this.printPtime(t.ptime),n+=this.printMaxPtime(t.maxPtime),n+=this.printDirection(t.direction),n+=this.printSSRCGroups(t.ssrcGroups),n+=this.printSSRC(t.ssrcs),n+=this.printRTCPMux(t.rtcpMux),n+=this.printRTCPMuxOnly(t.rtcpMuxOnly),n+=this.printRTCPRsize(t.rtcpRsize),n+=this.printMSId(t.msids),n+=this.printImageattr(t.imageattr),n+=this.printRid(t.rids),n+=this.printSimulcast(t.simulcast),n+=this.printSCTPPort(t.sctpPort),n+=this.printMaxMessageSize(t.maxMessageSize),n+=this.printUnrecognized(t.unrecognized),n}printCandidates(e){return e.map((e=>"a=candidate:".concat(e.foundation).concat(o).concat(e.componentId).concat(o).concat(e.transport).concat(o).concat(e.priority).concat(o).concat(e.connectionAddress).concat(o).concat(e.port).concat(o,"typ").concat(o).concat(e.type).concat(e.relAddr?"".concat(o,"raddr").concat(o).concat(e.relAddr):"").concat(e.relPort?"".concat(o,"rport").concat(o).concat(e.relPort):"").concat(Object.keys(e.extension).map((t=>"".concat(o).concat(t).concat(o).concat(e.extension[t]))).join("")).concat(this.eol))).join("")}printRemoteCandidatesList(e){return e.map((e=>"a=remote-candidates:".concat(e.join(o)).concat(this.eol))).join("")}printEndOfCandidates(e){return void 0===e?"":"a=end-of-candidates"+this.eol}printRTPRelated(e){if(!e.payloads)return"";const t=e.payloads;let n="";n+=e.rtcpFeedbackWildcards.map((e=>this.printRTCPFeedback("*",e))).join("");for(const e of t)n+=this.printRtpMap(e.payloadType,e.rtpMap),n+=this.printFmtp(e.payloadType,e.fmtp),n+=e.rtcpFeedbacks.map((t=>this.printRTCPFeedback(e.payloadType,t))).join("");return n}printFmtp(e,t){if(!t)return"";const n=Object.keys(t.parameters);return 1===n.length&&null===t.parameters[n[0]]?"a=fmtp:".concat(e).concat(o).concat(n[0]).concat(this.eol):"a=fmtp:".concat(e).concat(o).concat(Object.keys(t.parameters).map((e=>"".concat(e,"=").concat(t.parameters[e]))).join(";")).concat(this.eol)}printRtpMap(e,t){return t?"a=rtpmap:".concat(e).concat(o).concat(t.encodingName,"/").concat(t.clockRate).concat(t.encodingParameters?"/".concat(t.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(e,t){let n="a=rtcp-fb:".concat(e).concat(o),i=t;return"trr-int"===i.type?n+="ttr-int".concat(o).concat(i.interval):(n+="".concat(i.type),i.parameter&&(n+="".concat(o).concat(i.parameter),i.additional&&(n+="".concat(o).concat(i.additional)))),n+this.eol}printPtime(e){return void 0===e?"":"a=ptime:".concat(e).concat(this.eol)}printMaxPtime(e){return void 0===e?"":"a=maxptime:".concat(e).concat(this.eol)}printDirection(e){return void 0===e?"":"a=".concat(e).concat(this.eol)}printSSRC(e){return e.map((e=>Object.keys(e.attributes).map((t=>"a=ssrc:".concat(e.ssrcId.toString(10)).concat(o).concat(t).concat(e.attributes[t]?":".concat(e.attributes[t]):"").concat(this.eol))).join(""))).join("")}printRTCPMux(e){return void 0===e?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(e){return void 0===e?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(e){return void 0===e?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(e){if(void 0===e)return"";let t="a=rtcp:".concat(e.port);return e.netType&&(t+="".concat(o).concat(e.netType)),e.addressType&&(t+="".concat(o).concat(e.addressType)),e.address&&(t+="".concat(o).concat(e.address)),t+this.eol}printMSId(e){return e.map((e=>"a=msid:".concat(e.id).concat(e.appdata?"".concat(o).concat(e.appdata):"").concat(this.eol))).join("")}printImageattr(e){return e.map((e=>"a=imageattr:".concat(e).concat(this.eol))).join("")}printRid(e){return e.map((e=>{let t="a=rid:".concat(e.id).concat(o).concat(e.direction);return e.payloads&&(t+="".concat(o,"pt=").concat(e.payloads.join(","))),e.params.length>0&&(t+="".concat(o).concat(e.params.map((e=>"depend"===e.type?"depend=".concat(e.rids.join(",")):"".concat(e.type,"=").concat(e.val))).join(";"))),t+this.eol})).join("")}printSimulcast(e){return void 0===e?"":"a=simulcast:".concat(e).concat(this.eol)}printSCTPPort(e){return void 0===e?"":"a=sctp-port:".concat(e).concat(this.eol)}printMaxMessageSize(e){return void 0===e?"":"a=max-message-size:".concat(e).concat(this.eol)}printMid(e){return void 0===e?"":"a=mid:".concat(e).concat(this.eol)}printSSRCGroups(e){return e.map((e=>"a=ssrc-group:".concat(e.semantic).concat(e.ssrcIds.map((e=>"".concat(o).concat(e.toString(10)))).join("")).concat(this.eol))).join("")}}function D(e){return(new v).parse(e)}function P(e,t){return(new A).print(e,t)}}},t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={exports:{}};return e[i](r,r.exports,n),r.exports}return n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n(8)})();function zP(e){return JP.parse(e)}function ZP(e,t){return JP.print(e,t)}var qP=ni("Array","keys"),QP=gi,$P=$e,eL=l,tL=qP,nL=Array.prototype,iL={DOMTokenList:!0,NodeList:!0},rL=function(e){var t=e.keys;return e===nL||eL(nL,e)&&t===nL.keys||$P(iL,QP(e))?tL:t},oL=n(rL);function sL(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function aL(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cL(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function dL(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?cL(Object(n),!0).forEach((function(t){aL(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):cL(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function lL(e,t){return lL=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},lL(e,t)}function uL(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return sL(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?sL(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function hL(){hL=function(e,t){return new n(e,void 0,t)};var e=RegExp.prototype,t=new WeakMap;function n(e,i,r){var o=RegExp(e,i);return t.set(o,r||t.get(e)),lL(o,n.prototype)}function i(e,n){var i,r=t.get(n);return sr(i=Object.keys(r)).call(i,(function(t,n){var i=r[n];if("number"==typeof i)t[n]=e[i];else{for(var o=0;void 0===e[i[o]]&&o+1<i.length;)o++;t[n]=e[i[o]]}return t}),Object.create(null))}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&lL(e,t)}(n,RegExp),n.prototype.exec=function(t){var n=e.exec.call(this,t);if(n){n.groups=i(n,this);var r=n.indices;r&&(r.groups=i(r,this))}return n},n.prototype[Symbol.replace]=function(n,r){if("string"==typeof r){var o=t.get(this);return e[Symbol.replace].call(this,n,r.replace(/\$<([^>]+)(>|$)/g,(function(e,t,n){if(""===n)return e;var i=o[t];return Array.isArray(i)?"$"+i.join("$"):"number"==typeof i?"$"+i:""})))}if("function"==typeof r){var s=this;return e[Symbol.replace].call(this,n,(function(){var e=arguments;return"object"!=typeof e[e.length-1]&&(e=[].slice.call(e)).push(i(e,s)),r.apply(this,e)}))}return e[Symbol.replace].call(this,n,r)},hL.apply(this,arguments)}const pL=new class extends YN{constructor(){super(...arguments),aL(this,"currentUploadLogID",0)}reportLogUploadError(e){const t=e.errorRange;t[t.length-1]&&t[t.length-1]>this.currentUploadLogID&&(this.currentUploadLogID=t[t.length-1],this.emit("REPORT_LOG_UPLOAD",e))}};function _L(){const e=new Date;return e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}function EL(){const e=new Date,t=/((\d+:){2}\d+)/.exec((new Date).toUTCString());return t?(null==t?void 0:t[0])+":"+e.getUTCMilliseconds():e.toTimeString().split(" ")[0]+":"+e.getMilliseconds()}const mL={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},fL=Date.now(),gL=e=>{for(const t in mL)if(Object.prototype.hasOwnProperty.call(mL,t)&&mL[t]===e)return t;return"DEFAULT"};const SL=new class{constructor(){aL(this,"proxyServerURL",void 0),aL(this,"logLevel",mL.DEBUG),aL(this,"uploadState","collecting"),aL(this,"uploadStartTimer",void 0),aL(this,"uploadLogWaitingList",[]),aL(this,"uploadLogUploadingList",[]),aL(this,"uploadErrorCount",0),aL(this,"currentLogID",0),aL(this,"url",void 0),aL(this,"extLog",((e,t)=>{this.appendLogToWaitingList(e,...t)}))}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[mL.DEBUG].concat(t);this.log.apply(this,i)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[mL.INFO].concat(t);this.log.apply(this,i)}warning(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[mL.WARNING].concat(t);this.log.apply(this,i)}warn(){this.warning(...arguments)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[mL.ERROR].concat(t);this.log.apply(this,i)}upload(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const i=[mL.DEBUG].concat(t);this.uploadLog.apply(this,i)}setLogLevel(e){e=Math.min(Math.max(0,e),4),this.logLevel=e}enableLogUpload(){VP("UPLOAD_LOG",!0)}disableLogUpload(){VP("UPLOAD_LOG",!1),this.uploadState="collecting",void 0!==this.uploadStartTimer&&(window.clearTimeout(this.uploadStartTimer),this.uploadStartTimer=void 0),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(e){this.proxyServerURL=e}prefix(e){return new class{constructor(e){aL(this,"logger",void 0),aL(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.debug(...this.prefixLists,...t)}info(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.info(...this.prefixLists,...t)}warning(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.warning(...this.prefixLists,...t)}error(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];this.logger.error(...this.prefixLists,...t)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}}(this).prefix(e)}log(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(Date.now()-fL<100)return void setTimeout((()=>{this.log(...t)}),Date.now()-fL);const i=Math.max(0,Math.min(4,t[0]));if(t[0]=_L()+" Agora-SDK [".concat(gL(i),"]:"),this.appendLogToWaitingList(i,...t),i<this.logLevel)return;const r=_L()+" %cAgora-SDK [".concat(gL(i),"]:");let o=[];if(!xP("USE_NEW_LOG"))switch(i){case mL.DEBUG:o=[r,"color: #64B5F6;"].concat(t.slice(1)),console.log.apply(console,o);break;case mL.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(t.slice(1)),console.log.apply(console,o);break;case mL.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(t.slice(1)),console.warn.apply(console,o);break;case mL.ERROR:o=[r,"color: #B00020; font-weight: bold;"].concat(t.slice(1)),console.error.apply(console,o)}}uploadLog(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];if(Date.now()-fL<100)return void setTimeout((()=>{this.uploadLog(...t)}),Date.now()-fL);const i=Math.max(0,Math.min(4,t[0]));t[0]=_L()+" Agora-SDK [".concat(gL(i),"]:"),this.appendLogToWaitingList(i,...t)}appendLogToWaitingList(e){if(!xP("UPLOAD_LOG"))return;for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];Array.isArray(n[0])?n[0][0]=EL()+" Agora-SDK [".concat(gL(e),"]:"):n[0]=EL()+" Agora-SDK [".concat(gL(e),"]:");let r="";n.forEach((e=>{"object"==typeof e&&(e=JSON.stringify(e)),r+="".concat(e," ")})),this.uploadLogWaitingList.push({payload_str:r,log_level:e,log_item_id:this.currentLogID++}),"uploading"===this.uploadState&&0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",void 0!==this.uploadStartTimer&&(window.clearTimeout(this.uploadStartTimer),this.uploadStartTimer=void 0),0===this.uploadLogUploadingList.length&&this.uploadLogInterval()}scheduleUploadStart(){"uploading"!==this.uploadState&&void 0===this.uploadStartTimer&&(this.uploadStartTimer=window.setTimeout((()=>{this.uploadStartTimer=void 0,xP("UPLOAD_LOG")&&this.startUpload()}),5e3))}async uploadLogs(){const e=this.uploadLogUploadingList,t={sdk_version:wP,process_id:xP("PROCESS_ID"),payload:JSON.stringify(e)};return QD((async()=>{const e=await DO.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(xP("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(xP("LOG_UPLOAD_SERVER"),"/upload/v1")),t,{responseType:"text"});if("OK"!==e.data){const t=new Error("unexpected upload log response");throw t.response=e,t}}),(()=>(this.uploadLogUploadingList=[],!1)),(t=>{const n={status:-1,message:t.message,errorRange:e.map((e=>e.log_item_id))};return t.response?(n.status=t.response.status,n.data=t.response.data,n.headers=t.response.headers):t.request&&(n.status=t.request.status),pL.reportLogUploadError(n),!0}),{timeout:xP("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:xP("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")})}uploadLogInterval(){0===this.uploadLogUploadingList.length&&0===this.uploadLogWaitingList.length||(0===this.uploadLogUploadingList.length&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,xP("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then((()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout((()=>this.uploadLogInterval()),xP("UPLOAD_LOG_INTERVAL"))})).catch((e=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout((()=>this.uploadLogInterval()),xP("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout((()=>this.uploadLogInterval()),xP("UPLOAD_LOG_RETRY_INTERVAL_V1"))})))}};var TL;function RL(e){return kN(e.reportId,"params.reportId",0,100,!1),kN(e.category,"params.category",0,100,!1),kN(e.event,"params.event",0,100,!1),kN(e.label,"params.label",0,100,!1),PN(e.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(TL={}).FREE="free",TL.UPLOADING="uploading",function(e){e[e.MISC=0]="MISC",e[e.INTERNAL_EVENT=1]="INTERNAL_EVENT",e[e.PUBLIC_EVENT=2]="PUBLIC_EVENT",e[e.WEB_EVENT=3]="WEB_EVENT",e[e.INTERNAL_API=4]="INTERNAL_API",e[e.WEB_API=5]="WEB_API",e[e.PUBLIC_API=6]="PUBLIC_API"}({});let vL=function(e){return e[e.RECOVER=0]="RECOVER",e[e.WARNING=1]="WARNING",e[e.ERROR=2]="ERROR",e}({}),yL=function(e){return e.CONFIG_DISTRIBUTE="config-distribute-error",e}({});const CL={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let bL=function(e){return e.PUBLISH="publish",e.SUBSCRIBE="subscribe",e.WS_COMPRESSOR_INIT="ws_compressor_init",e.SESSION_INIT="session_init",e.JOIN_CHOOSE_SERVER="join_choose_server",e.RTE_DETAIL="rte_detail_stats",e.REQ_USER_ACCOUNT="req_user_account",e.JOIN_GATEWAY="join_gateway",e.REJOIN_GATEWAY="rejoin_gateway",e.STREAM_SWITCH="stream_switch",e.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",e.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",e.FIRST_VIDEO_RECEIVED="first_video_received",e.FIRST_AUDIO_RECEIVED="first_audio_received",e.FIRST_VIDEO_DECODE="first_video_decode",e.FIRST_AUDIO_DECODE="first_audio_decode",e.XLA_PEER_FIRST_VIDEO_FRAME="xla_peer_first_video_frame",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_UPDATE_STREAM="on_update_stream",e.ON_REMOVE_STREAM="on_remove_stream",e.USER_ANALYTICS="req_user_analytics",e.PC_STATS="pc_stats",e.UPDATE_REMOTE_RTPCAPABILITIES="update_remote_rtpCapabilities",e.AB_TEST="ab_test",e.ALARM_STATUS_NOTIFY="alarm_status_notify",e}({}),IL=function(e){return e.SESSION="io.agora.pb.Wrtc.Session",e.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",e.RTE_DETAIL="io.agora.pb.Wrtc.RteDetailStats",e.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",e.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",e.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",e.PUBLISH="io.agora.pb.Wrtc.Publish",e.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",e.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",e.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",e.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",e.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",e.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",e.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",e.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",e.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",e.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",e.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",e.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",e.XLA_PEER_FIRST_VIDEO_FRAME="io.agora.pb.Wrtc.XLAPeerFirstVideoFrame",e.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",e.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",e.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",e.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",e.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",e.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",e.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",e.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",e.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",e.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",e.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",e.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",e.PC_STATS="io.agora.pb.Wrtc.PCStats",e.UPDATE_REMOTE_RTPCAPABILITIES="io.agora.pb.Wrtc.UpdateRemoteRTPCapabilities",e.AB_TEST="io.agora.pb.Wrtc.ABTest",e.ALARM_STATUS_NOTIFY="io.agora.pb.Wrtc.AlarmStatusNotify",e}({});!function(e){e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"}({});let AL=function(e){return e[e.SESSION=26]="SESSION",e[e.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",e[e.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",e[e.JOIN_GATEWAY=28]="JOIN_GATEWAY",e[e.PUBLISH=30]="PUBLISH",e[e.SUBSCRIBE=29]="SUBSCRIBE",e[e.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",e[e.STREAM_SWITCH=32]="STREAM_SWITCH",e[e.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",e[e.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",e[e.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",e[e.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",e[e.API_INVOKE=41]="API_INVOKE",e[e.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",e[e.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",e[e.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",e[e.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",e[e.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",e[e.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",e[e.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",e[e.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",e[e.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",e[e.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",e[e.WORKER_EVENT=156]="WORKER_EVENT",e[e.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",e[e.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",e[e.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",e[e.USER_ANALYTICS=1e4]="USER_ANALYTICS",e[e.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED",e}({});const wL="[config-restore]",OL="websdk_ng_",NL=OL+"blocked_config_hashes",DL=OL+"api_failure_records",PL=OL+"global_parameter",LL=OL+"config_restore_state";function kL(e){var t;return null==e||"object"!=typeof e?JSON.stringify(e):Array.isArray(e)?"["+e.map((e=>kL(e))).join(",")+"]":"{"+t_(t=Object.keys(e)).call(t).map((t=>JSON.stringify(t)+":"+kL(e[t]))).join(",")+"}"}function ML(e){return function(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}(kL(e))}function UL(){try{const e=window.localStorage.getItem(LL);if(e)return JSON.parse(e)}catch(e){}return{currentConfigHash:"",configVerified:!1}}function VL(e){try{window.localStorage.setItem(LL,JSON.stringify(e))}catch(e){}}function xL(){try{const e=window.localStorage.getItem(DL);return e?JSON.parse(e):[]}catch(e){return SL.debug("[error] ".concat(wL," error getting API failure records:"),e),[]}}function FL(){var e;return sr(e=xL()).call(e,((e,t)=>e+t.count),0)}function BL(){try{window.localStorage.removeItem(DL)}catch(e){SL.debug("[error] ".concat(wL," error clearing API failure records:"),e)}}function jL(){try{const e=FL(),t=xP("MAX_CONFIG_RETRY");if(e<t)return;const n=UL().currentConfigHash;SL.debug("[warning] ".concat(wL," restoring config due to ").concat(e," API failures")),n&&function(e){try{const t=window.localStorage.getItem(NL);let n=[];t&&(n=JSON.parse(t).configHashes);const i=[...new Set([...n,e])];window.localStorage.setItem(NL,JSON.stringify({configHashes:i,timestamp:Date.now()})),SL.debug("[warning] ".concat(wL," blocked config hash: ").concat(e))}catch(e){SL.debug("[error] ".concat(wL," error blocking config hash:"),e)}}(n),window.localStorage.removeItem(PL);const i=xL().slice(-5);(function(e,t){HL.reportAlarm(e,t)})(null,{status:vL.ERROR,type:yL.CONFIG_DISTRIBUTE,message:"Config cache cleared due to API failures",extend:{failureCount:e,maxRetry:t,blockedConfigHash:n,recentFailures:i.map((e=>({api:e.apiName,error:e.errorCode||e.errorMessage,count:e.count,lastTime:e.lastTimestamp})))}}),BL()}catch(e){SL.debug("[error] ".concat(wL," error restoring config:"),e)}}function GL(e,t){try{if(!xP("ENABLE_CONFIG_RESTORE"))return;if(t&&"AgoraRTCException"===t.name){const e=xP("CONFIG_ERROR_MONITOR");if(!Array.isArray(e)||!Ui(e).call(e,t.code))return}const n=window.localStorage.getItem(PL);if(!n||n.length<20)return;if(UL().configVerified)return;const i=xP("CONFIG_RESTORE_ERROR_API");if(!Array.isArray(i)||!Ui(i).call(i,e))return;let r,o;t&&(t.code&&(r=t.code),o=t.message?t.message:"string"==typeof t?t:t.toString()),function(e,t,n){try{const i=xL(),r="".concat(e,":").concat(t||""),o=i.find((e=>"".concat(e.apiName,":").concat(e.errorCode||"")===r)),s=UL().currentConfigHash;if(o)o.count++,o.lastTimestamp=Date.now(),n&&(o.errorMessage=n),s&&(o.configHash=s);else{const r=Date.now();i.push({apiName:e,errorCode:t,errorMessage:n,count:1,firstTimestamp:r,lastTimestamp:r,configHash:s||void 0})}const a=i.length>20?i.slice(-20):i;window.localStorage.setItem(DL,JSON.stringify(a))}catch(e){SL.debug("[error] ".concat(wL," error saving API failure record:"),e)}}(e,r,o);const s=FL(),a=xP("MAX_CONFIG_RETRY");SL.debug("".concat(wL," API failure count: ").concat(s,"/").concat(a,", API: ").concat(e,", Error: ").concat(r||o)),s>=a&&jL()}catch(e){}}function WL(){try{window.localStorage.removeItem(NL)}catch(e){SL.debug("[error] ".concat(wL," error resetting blocked config:"),e)}}function KL(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(t,n,i){const r=i.value;if("function"==typeof r){const o=e.className||t.__className__||("AgoraRTCClient"===t.constructor.name?"Client":t.constructor.name);i.value=function(){for(var t,i,s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];let d=a;if(e.argsMap)try{d=e.argsMap(this,...a)}catch(e){SL.warning(e),d=[]}try{JSON.stringify(d)}catch(e){SL.warning("arguments for method ".concat(o,".").concat(String(n)," not serializable for apiInvoke.")),d=[]}const l=(e.report||HL).reportApiInvoke(this._sessionId||null,{id:this._clientId||(null===(t=this.store)||void 0===t?void 0:t.clientId)||this._ID,clientId:"Client"===o?this._clientId||(null===(i=this.store)||void 0===i?void 0:i.clientId):void 0,name:"".concat(o,".").concat(String(n)),options:d,tag:ZN.TRACER,reportResult:e.reportResult},e.throttleTime);try{const t=r.apply(this,a);return t instanceof cp?t.then((t=>(l.onSuccess(e.reportResult&&t),t))).catch((e=>{throw l.onError(e),e})):(l.onSuccess(e.reportResult&&t),t)}catch(e){throw l.onError(e),e}}}return i}}const HL=new class{constructor(){aL(this,"baseInfoMap",new Map),aL(this,"proxyServer",void 0),aL(this,"eventUploadTimer",void 0),aL(this,"setSessionIdTimer",void 0),aL(this,"url",void 0),aL(this,"sids",new Set),aL(this,"backupUrl",void 0),aL(this,"_appId",void 0),aL(this,"_aid",0),aL(this,"keyEventUploadPendingItems",[]),aL(this,"normalEventUploadPendingItems",[]),aL(this,"apiInvokeUploadPendingItems",[]),aL(this,"apiInvokeCount",0),aL(this,"apiInvokeLoggedCount",0),aL(this,"ltsList",[]),aL(this,"lastSendNormalEventTime",Date.now()),aL(this,"customReportCounterTimer",void 0),aL(this,"customReportCount",0),aL(this,"extApiInvoke",(async e=>{for(const t of e){const e=dL(dL({},t),{},{sid:null,invokeId:++this.apiInvokeCount,processId:xP("PROCESS_ID"),tag:ZN.TRACER});this.sendApiInvoke(e)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),xP("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),xP("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(e){return this.baseInfoMap.get(e)}setAppId(e){this._appId=e,this._aid=parseInt(e.replace(/[a-fA-F0-9]{8}/g,(e=>{let t=uL(e,2);return t[0]+t[1]})),16)||0}reportApiInvoke(e,t,n){t.timeout=t.timeout||6e4,t.reportResult=void 0===t.reportResult||t.reportResult;const i=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=!!xP("SHOW_REPORT_INVOKER_LOG"),s=!!xP("SHOW_REPORT_USER_INVOKER_LOG"),a=o||s&&t.id;a&&(this.apiInvokeLoggedCount+=1);const c=this.apiInvokeLoggedCount;function d(e,n){if(a){let i="[apiInvoke-".concat(c,"]");if(t.id&&(i+="[".concat(t.id,"]")),t.name&&(i+="[".concat(t.name,"]"),t.name===zN.JOIN))return SL.info("".concat(i," ").concat(e));SL.info("".concat(i," ").concat(e),"start"===e?t.options:n||"")}}const l=()=>({tag:t.tag,invokeId:r,sid:e,name:t.name,processId:xP("PROCESS_ID"),clientId:t.clientId,apiInvokeTime:i,options:t.options,states:t.states||null});d("start");let u=!1;LD(t.timeout).then((()=>{u||(this.sendApiInvoke(dL(dL({},l()),{},{error:wN.API_INVOKE_TIMEOUT,success:!1})),d("timeout"),GL(t.name,new ON(wN.API_INVOKE_TIMEOUT)))}));const h=new ON(wN.UNEXPECTED_ERROR,"".concat(t.name,": this api invoke is end"));return{onSuccess:e=>{const i=()=>{if(u)throw h;return u=!0,this.sendApiInvoke(dL(dL({},l()),{},{success:!0},t.reportResult&&{result:e})),d("onSuccess"),e};return n?xD(i,t.name+"Success",n,(()=>u=!0)):i()},onError:e=>{const i=()=>{if(u)throw e;u=!0,this.sendApiInvoke(dL(dL({},l()),{},{success:!1,error:e})),GL(t.name,e),d("onFailure",e.toString())};return n?xD(i,t.name+"Error",n,(()=>u=!0)):i()}}}_send(e,t,n){this.send({type:e,data:t},n)}_sendApiInvoke(e){return this.sendApiInvoke(e)}sessionInit(e,t){if(this.baseInfoMap.has(e))return;const n=Date.now(),i=this.createBaseInfo(e,n);i.cname=t.cname,i.rteUrl=t.rteUrl;const r=Object.assign({},{willUploadConsoleLog:xP("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:OP?"global":"oversea",areas:xP("AREAS")&&xP("AREAS").join(",")},t.extend),o=t.stringUid,s=t.channelProfile,a=t.channelMode,c=t.isABTestSuccess,d=t.lsid,l=t.clientRole,u=Date.now(),h=dL(dL({},i),{},{eventType:bL.SESSION_INIT,appid:t.appid,browser:navigator.userAgent,buildFormat:t.buildFormat,build:kP,lts:u,elapse:u-n,extend:JSON.stringify(r),mode:t.mode,process:xP("PROCESS_ID"),appType:xP("APP_TYPE"),success:!0,version:wP,stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientType:vN()?42:20,clientRole:l,serviceId:xP("PROCESS_ID"),extensionID:xP("PLUGIN_INFO").join(",")||"",rteUrl:t.rteUrl,rteSid:t.rteSid,installId:AP()});this.send({type:IL.SESSION,data:h},!0)}reportRteDetail(e){const t=this.baseInfoMap.get(e);if(!t)return;const n=t.info,i=Date.now(),r=dL(dL({},n),{},{eventType:bL.RTE_DETAIL,lts:i,success:!0,elapse:i-t.startTime,vid:void 0===n.vid?0:Number(n.vid),ua:navigator.userAgent});this.send({type:IL.RTE_DETAIL,data:r},!0)}joinChooseServer(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info;t.vid&&(i.vid=t.vid);const r=Date.now(),o=dL(dL({},i),{},{role:t.role,eventType:bL.JOIN_CHOOSE_SERVER,lts:r,eventElapse:t.elapse||r-t.lts,chooseServerAddr:t.csAddr,errorCode:t.ec,elapse:r-n.startTime,success:t.succ,chooseServerAddrList:JSON.stringify(t.serverList),uid:t.uid?parseInt(t.uid):null,cid:t.cid?parseInt(t.cid):null,chooseServerIp:t.csIp||"",opid:t.opid,unilbsServerIds:t.unilbsServerIds,extend:t.extend||void 0,isHttp3:t.isHttp3,corssRegionTagReq:t.corssRegionTagReq||void 0,corssRegionTagRes:t.corssRegionTagRes||void 0,ua:navigator.userAgent,resourceTimingInfo:t.resourceTimingInfo||void 0});this.send({type:IL.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL({},i),{},{eventType:bL.REQ_USER_ACCOUNT,lts:r,success:t.success,serverAddress:t.serverAddr,stringUid:t.stringUid,uid:t.uid,errorCode:t.errorCode,elapse:t.elapse||r-n.startTime,eventElapse:r-t.lts,extend:JSON.stringify(t.extend)});this.send({type:IL.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(e,t){var n;const i=this.baseInfoMap.get(e);if(!i)return;const r=i.info;t.vid&&(r.vid=t.vid),r.uid=t.uid,r.cid=t.cid;const o=Date.now(),s=null!==(n=t.reportAt)&&void 0!==n?n:o,a=t.firstSuccess,c=t.addr,d=t.isProxy,l=t.iceConnectedAt,u=t.joinResponseAt,h=!0===t.succ&&"2"===t.signalChannel&&void 0!==t.reportAt&&void 0!==t.winner&&void 0!==t.winnerAt&&void 0!==l&&void 0!==u,p=t.winnerAt,_=null!=p?p:o,E=dL(dL({},t.winner?{winner:t.winner}:{}),h?{iceConnectedElapse:Math.max(l-i.startTime,0),joinResponseElapse:Math.max(u-i.startTime,0)}:{}),m=void 0===p?o-i.startTime:Math.max(_-i.startTime,0),f=dL(dL({},r),{},{eventType:bL.JOIN_GATEWAY,lts:o,gatewayAddr:t.addr,success:t.succ,errorCode:t.ec,errorMsg:t.errorMsg||"",elapse:m,eventElapse:o-t.lts,firstSuccess:a,signalChannel:t.signalChannel,preload:t.preload?1:0,installId:AP(),isABTestSuccess:t.isABTestSuccess?1:0,gatewayIp:null,gatewayPort:null,isProxy:d?1:0},E),g=f.success?1:0;if(t.succ&&(i.lastJoinSuccessTime=s),c)if("1"===f.signalChannel){const e=hL(/(\d+\.\d+\.\d+\.\d+):(\d+)/,{ip:1,port:2}),t=c.match(e);f.gatewayIp=t&&t.groups?t.groups.ip:"",f.gatewayPort=t&&t.groups?t.groups.port:""}else if(d){const e=c.match(/h=(\d{1,3}-){3}\d{1,3}/g),t=c.match(/p=[0-9]{1,6}/g);f.gatewayIp=e&&e.length?e[0].split("=")[1].replace(/-/g,"."):"",f.gatewayPort=t&&t.length?t[0].split("=")[1]:""}else{const e=c.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),t=c.match(/(:|p=)[0-9]{1,6}/g);f.gatewayIp=e&&e.length?e[0].split("//")[1].replace(/-/g,"."):"",f.gatewayPort=t&&t.length?t[0].split(/:|p=/g)[1]:""}if(a||h)this.send({type:IL.JOIN_GATEWAY,data:f},!0);else{const e={isSuccess:g,port:f.gatewayPort};delete f.success,delete f.eventType,delete f.firstSuccess,delete f.gatewayPort,f.vid=Number(f.vid);const t=Object.assign({},f,e,{eventType:bL.REJOIN_GATEWAY});this.send({type:IL.RE_JOIN_GATEWAY,data:t},!0)}}joinChannelTimeout(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=Date.now(),r=dL(dL({},n.info),{},{lts:i,timeout:t,elapse:i-n.startTime});this.send({type:IL.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL({},i),{},{eventType:bL.PUBLISH,lts:r,eventElapse:t.eventElapse,elapse:r-n.startTime,success:t.succ,errorCode:t.ec,videoName:t.videoName,audioName:t.audioName,screenName:t.screenName,screenshare:t.screenshare,audio:t.audio,video:t.video,p2pid:t.p2pid,publishRequestid:t.publishRequestid});this.send({type:IL.PUBLISH,data:o},!0)}subscribe(e,t,n){const i=this.baseInfoMap.get(e);if(!i)return;const r=i.info,o=Date.now(),s=dL(dL({},r),{},{eventType:bL.SUBSCRIBE,lts:o,eventElapse:t.eventElapse,elapse:o-i.startTime,success:t.succ,errorCode:t.ec,video:t.video,audio:t.audio,subscribeRequestid:t.subscribeRequestid,p2pid:t.p2pid,preSsrc:t.preSsrc?1:0},n&&{extend:JSON.stringify({isMassSubscribe:!0})});"string"==typeof t.peerid?s.peerSuid=t.peerid:s.peer=t.peerid,this.send({type:IL.SUBSCRIBE,data:s},!0)}wsCompressorInit(e){var t;const n=[...oL(t=this.baseInfoMap).call(t)],i=n.length?n[0]:"UnableToGetSid",r=this.baseInfoMap.get(i);if(!r)return;const o=r.info,s=Date.now(),a=dL(dL({},o),{},{eventType:bL.WS_COMPRESSOR_INIT,lts:s,eventElapse:e.eventElapse,elapse:s-r.startTime,status:e.status?1:2});this.send({type:IL.WS_COMPRESSOR_INIT,data:a},!0)}firstXLAPeerFirstVideoFrame(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=t.peerPubStatusMs-(n.lastJoinSuccessTime||r),s=dL(dL({},i),{},{elapse:r-n.startTime,eventType:bL.XLA_PEER_FIRST_VIDEO_FRAME,lts:r,peer:t.peer,width:t.width,height:t.height,ssrc:t.ssrc,p2pid:t.p2pid,peerPublishDuration:t.peerPublishDuration,joinChannelSuccessElapse:o,peerPubStatusMs:t.peerPubStatusMs-t.joinChannelStart,availablePublish:t.peerPublishDuration>o?1:0,preloadStart:Math.max(t.preloadStart-t.joinChannelStart,0),preloadEnd:Math.max(t.preloadEnd-t.joinChannelStart,0),encrypt:Math.max(t.apStart-t.joinChannelStart,0),ap:Math.max(t.apEnd-t.joinChannelStart,0),sua:Math.max(t.suaEnd-t.joinChannelStart,0),beforeConnect:Math.max(t.beforeConnect-t.joinChannelStart,0),peerRecevier:Math.max(t.peerReceiver-t.joinChannelStart,0),ice:Math.max(t.ice-t.joinChannelStart,0),pc:Math.max(t.pc-t.joinChannelStart,0),signalConnected:Math.max(t.signalConnected-t.joinChannelStart,0),joinReq:Math.max(t.joinReq-t.joinChannelStart,0),joinRes:Math.max(t.joinRes-t.joinChannelStart,0),userJoinNotify:Math.max(t.userJoinNotify-t.joinChannelStart,0),videoSsrcNotify:Math.max(t.videoAddNotify-t.joinChannelStart,0),subscribeDelayMs:Math.max(t.subscribeStart-t.videoAddNotify,0),subscribeStart:Math.max(t.subscribeStart-t.joinChannelStart,0),subscribeEnd:Math.max(t.subscribeEnd-t.joinChannelStart,0),firstReceived:Math.max(t.firstReceived-t.joinChannelStart,0),firstDecoded:Math.max(t.firstDecoded-t.joinChannelStart,0),firstPreRender:Math.max(t.firstPreRender-t.joinChannelStart,0),firstRender:Math.max(t.firstRender-t.joinChannelStart,0),playDelayMs:Math.max(t.playStart-t.subscribeEnd,0),playStart:Math.max(t.playStart-t.joinChannelStart,0),playEnd:Math.max(t.playEnd-t.joinChannelStart,0),isPreSub:t.isPreSub?1:0,isPrePc:t.isPrePc?1:0,isPreInstantVideo:t.isPreInstantVideo?1:0,firstReceivedEncodedFrame:t.firstReceivedEncodedFrame?Math.max(t.firstReceivedEncodedFrame-t.joinChannelStart,0):void 0,frameType:t.frameType||"",rtpTimestamp:t.rtpTimestamp||0,framePayloadType:t.framePayloadType||0,frameDataLength:t.frameDataLength||0,mimeType:t.mimeType||"",sdpEndPoint:t.sdpEndPoint?1:0});this.send({type:IL.XLA_PEER_FIRST_VIDEO_FRAME,data:s},!0)}firstRemoteVideoDecode(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=dL(dL(dL({},o),i),{},{elapse:s-r.startTime,eventType:t,lts:s,firstDecodeFrame:Math.max((i.firstFrame||s)-r.startTime,0),apEnd:Math.max(i.apEnd-r.startTime,0),apStart:Math.max(i.apStart-r.startTime,0),joinGwEnd:Math.max(i.joinGwEnd-r.startTime,0),joinGwStart:Math.max(i.joinGwStart-r.startTime,0),pcEnd:Math.max(i.pcEnd-r.startTime,0),pcStart:Math.max(i.pcStart-r.startTime,0),subscriberEnd:Math.max(i.subscriberEnd-r.startTime,0),subscriberStart:Math.max(i.subscriberStart-r.startTime,0),videoAddNotify:Math.max(i.videoAddNotify-r.startTime,0)});this.send({type:n,data:a},!0)}firstRemoteFrame(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=dL(dL(dL({},o),i),{},{elapse:s-r.startTime,eventType:t,lts:s});this.send({type:n,data:a},!0)}abTest(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL(dL({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),elapse:r-n.startTime,eventType:bL.AB_TEST,lts:r});this.send({type:IL.AB_TEST,data:o},!0)}pcStats(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL(dL({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),elapse:r-n.startTime,eventType:bL.PC_STATS,lts:r,preallocation:t.preallocation?1:0});this.send({type:IL.PC_STATS,data:o},!0)}updateRemoteRTPCapabilities(e,t){if(e){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL(dL({},i),t),{},{vid:void 0===i.vid?0:Number(i.vid),eventType:bL.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:IL.UPDATE_REMOTE_RTPCAPABILITIES,data:o},!0)}}onGatewayStream(e,t,n,i){const r=this.baseInfoMap.get(e);if(!r)return;const o=r.info,s=Date.now(),a=dL(dL(dL({},o),i),{},{eventType:t,lts:s});this.send({type:n,data:a},!0)}streamSwitch(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL({},i),{},{eventType:bL.STREAM_SWITCH,lts:r,isDual:t.isdual,elapse:r-n.startTime,success:t.succ});this.send({type:IL.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL({},i),{},{eventType:bL.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-t.lts,elapse:r-n.startTime,APAddr:t.APAddr,workerManagerList:t.workerManagerList,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:IL.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL({},i),{},{eventType:bL.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-t.lts,elapse:r-n.startTime,workerManagerAddr:t.workerManagerAddr,response:t.response,errorCode:t.ec,success:t.succ});this.send({type:IL.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(e){this.proxyServer=e,e?SL.debug("reportProxyServerurl: ".concat(e)):SL.debug("disable reportProxyServerurl: ".concat(e))}peerPublishStatus(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL({},i),{},{subscribeElapse:t.subscribeElapse,peer:t.peer,peerPublishDuration:Math.max(t.audioPublishDuration,t.videoPublishDuration),audiotag:t.audioPublishDuration>0?1:-1,videotag:t.videoPublishDuration>0?1:-1,lts:r,elapse:r-n.startTime,joinChannelSuccessElapse:r-(n.lastJoinSuccessTime||r),peerPublishDurationVideo:t.videoPublishDuration,peerPublishDurationAudio:t.audioPublishDuration});this.send({type:IL.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now();(function(e,t,n){const i=e[t];if(!i||"string"!=typeof i)return[e];e[t]="";const r=ND(JSON.stringify(e));let o=0;const s=[];let a=0;for(let c=0;c<i.length;c++)a+=i.charCodeAt(c)<=127?1:3,a<=n-r||(s[s.length]=IN(IN({},e),{},{[t]:i.substring(o,c)}),o=c,a=i.charCodeAt(c)<=127?1:3);return o!==i.length-1&&(s[s.length]=IN(IN({},e),{},{[t]:i.substring(o)})),s})(dL(dL(dL({},i),t),{},{elapse:r-n.startTime,lts:r,productType:"WebRTC"}),"payload",1300).forEach((e=>this.send({type:IL.WORKER_EVENT,data:e},!0)))}apworkerEvent(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL(dL({},i),t),{},{elapse:r-n.startTime,lts:r});this.send({type:IL.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL(dL({},i),t),{},{elapse:r-n.startTime,lts:r,extend:t.extend||void 0});this.send({type:IL.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(e,t){const n=this.baseInfoMap.get(e);if(!n)return;const i=n.info,r=Date.now(),o=dL(dL(dL({},i),t),{},{elapse:r-n.startTime,lts:r});this.send({type:IL.WEBSOCKET_QUIT,data:o},!0)}async sendCustomReportMessage(e,t){if(this.customReportCount+=t.length,this.customReportCount>xP("CUSTOM_REPORT_LIMIT"))throw new ON(wN.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval((()=>{this.customReportCount=0}),5e3));const n=Date.now(),i=t.map((t=>({type:IL.USER_ANALYTICS,data:dL(dL({sid:e},t),{},{lts:n})})));try{xP("NEW_REPORT_SERVER")?await this.postDataToStatsCollector2(i):await this.postDataToStatsCollector(i)}catch(e){throw SL.error("send custom report message failed",e.toString()),new ON(wN.CUSTOM_REPORT_SEND_FAILED,e.message)}}reportAlarm(e,t){const n=e?this.baseInfoMap.get(e):void 0,i=null==n?void 0:n.info,r=Date.now(),o=dL(dL(dL({},i),t),{},{vid:void 0===(null==i?void 0:i.vid)?0:Number(i.vid),elapse:n?r-n.startTime:0,eventType:bL.ALARM_STATUS_NOTIFY,lts:r,installId:AP(),processId:xP("PROCESS_ID")});this.send({type:IL.ALARM_STATUS_NOTIFY,data:o},!0)}reportCreateClientPreconnect(e){const t=Date.now(),n=xP("PROCESS_ID"),i={invokeId:++this.apiInvokeCount,process:n,sid:n.replace(/^process-/,"").replace(/-/g,""),cname:null,cid:null,uid:null,lts:t,success:!0,elapse:0,execElapse:0,apiName:zN.CREATE_CLIENT_PRECONNECT,options:JSON.stringify({targets:e.targets,mode:e.mode,origin:e.origin})};this.send({type:IL.API_INVOKE,data:i},!0)}sendApiInvoke(e){const t=xP("NOT_REPORT_EVENT");if(e.tag&&Ui(t)&&Ui(t).call(t,e.tag))return!1;if(null===e.sid)return this.apiInvokeUploadPendingItems.push(e),!1;const n=this.baseInfoMap.get(e.sid);if(!n)return this.apiInvokeUploadPendingItems.push(e),!1;const i=n.info,r=i.cname,o=i.uid,s=i.cid;let a;if(e.lts=e.lts||Date.now(),e.error)if(e.error instanceof ON){const t=e.error,n=t.code,i=t.message;a=n||i||e.error.toString()}else a=e.error.toString();const c={invokeId:e.invokeId,process:e.processId||xP("PROCESS_ID"),clientId:e.clientId,sid:e.sid,cname:r,cid:s,uid:o,lts:e.lts,success:e.success,elapse:e.lts-n.startTime,execElapse:e.lts-e.apiInvokeTime,apiName:e.name,options:e.options?JSON.stringify(e.options):void 0,execStates:e.states?JSON.stringify(e.states):void 0,execResult:e.result?JSON.stringify(e.result):void 0,errorCode:e.error?a:void 0,errorMsg:e.error?JSON.stringify(e.error):void 0};return this.send({type:IL.API_INVOKE,data:c},!1),!0}addSid(e){this.sids.add(e)}removeSid(e){this.sids.delete(e)}appendSessionId(){const e=this.apiInvokeUploadPendingItems;if(0===e.length)return;const t=Array.from(this.sids).find((e=>null!==e));t&&e.forEach((e=>{e&&(e.sid=t,this.sendApiInvoke(Object.assign({},e)))})),e.length=0}send(e,t){if(t)return this.keyEventUploadPendingItems.push(e),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(e),this.normalEventUploadPendingItems.length>xP("NORMAL_EVENT_QUEUE_CAPACITY")&&this.normalEventUploadPendingItems.splice(0,1),this.normalEventUploadPendingItems.length>=10&&this.sendItems(this.normalEventUploadPendingItems,!1)}doSend(){this.keyEventUploadPendingItems.length>0&&this.sendItems(this.keyEventUploadPendingItems,!0),this.normalEventUploadPendingItems.length>0&&Date.now()-this.lastSendNormalEventTime>=5e3&&this.sendItems(this.normalEventUploadPendingItems,!1)}sendItems(e,t){const n=[],i=[];for(;e.length;){const t=e.shift();n.length<20?n.push(t):i.push(t)}e.push(...i);for(const e of[...n]){var r;-1!==this.ltsList.indexOf(e.data.lts)?(e.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(e.data.lts)):(this.ltsList.push(e.data.lts),t_(r=this.ltsList).call(r,((e,t)=>e-t)))}return t||(this.lastSendNormalEventTime=Date.now()),xP("ENABLE_EVENT_REPORT")?(n.length&&(xP("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(n):this.postDataToStatsCollector(n)).catch((e=>n=>{xP("EVENT_REPORT_RETRY")&&(t?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(e):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(e),this.normalEventUploadPendingItems.length>xP("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-xP("NORMAL_EVENT_QUEUE_CAPACITY")),SL.warning("report: drop normal events"))))})(n)),e):e}async postDataToStatsCollector2(e){pD.networkState===aD.OFFLINE&&await cp.race([pD.onlineWaiter,LD(2*ZD.maxRetryTimeout)]);const t=e=>{let t=new Uint8Array;return e.forEach((e=>{const n=WN(JSON.stringify(e.data)),i=new ArrayBuffer(5),r=(e=>{let t=0;return Object.entries(IL).forEach((n=>{let i=uL(n,2),r=i[0];i[1]===e.type&&(t=AL[r])})),t})(e),o=new DataView(i);o.setUint16(0,n.byteLength,!0),o.setUint8(2,255&r),o.setUint8(3,r>>>8&255),o.setUint8(4,r>>>16&255),t=KN(t,new Uint8Array(i)),t=KN(t,n)})),t},n="event";let i=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(xP("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(n):"https://".concat(xP("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(n);for(let r=0;r<2;r+=1){1===r&&(i=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(xP("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(n):"https://".concat(xP("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(n));try{await iP(i,{timeout:1e4,data:t(e),headers:dL(dL({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(e){if(1===r)throw e;continue}return}}async postDataToStatsCollector(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=(e=>{const t=e&&e.data.sid&&this.baseInfoMap.get(e.data.sid);return t&&t.info.vid&&+t.info.vid||0})(e[0]),i=n?void 0:this._aid,r={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:e.map((e=>JSON.stringify(e))),vid:n,aid:i};pD.networkState===aD.OFFLINE&&await cp.race([pD.onlineWaiter,LD(2*ZD.maxRetryTimeout)]);const o=t?"/events/proto-raws":"/events/messages";let s=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(xP("EVENT_REPORT_DOMAIN"),"&p=").concat(xP("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(xP("EVENT_REPORT_DOMAIN"),":").concat(xP("STATS_COLLECTOR_PORT")).concat(o));for(let e=0;e<2;e+=1){1===e&&(s=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(xP("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(xP("STATS_COLLECTOR_PORT"),"&d=").concat(o):"https://".concat(xP("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(xP("STATS_COLLECTOR_PORT")).concat(o)));try{t?await rP(s,{timeout:1e4,data:r}):await iP(s,{timeout:1e4,data:r})}catch(t){if(1===e)throw t;continue}return}}createBaseInfo(e,t){const n=Object.assign({},CL);return n.sid=e,this.baseInfoMap.set(e,{info:n,startTime:t}),n}reportResourceTiming(e,t,n){const i=performance.getEntriesByName(e),r=i[i.length-1];r&&this.reportApiInvoke(t,{clientId:n,name:"Client.resourceTiming",options:r,tag:ZN.TRACER}).onSuccess()}};pL.on("REPORT_LOG_UPLOAD",(e=>{e.networkState=pD.networkState,HL.reportApiInvoke(null,{name:"logUploadError",options:e,tag:ZN.TRACER}).onSuccess("logUploadError")}));let YL=class extends ON{constructor(e){super(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",arguments.length>2?arguments[2]:void 0),aL(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"error";return super.print(e,SL)}throw(){super.throw(SL)}};const XL={getDisplayMedia:!1,getStreamFromExtension:!1,supportUnifiedPlan:!1,supportMinBitrate:!1,supportSetRtpSenderParameters:!1,supportDualStream:!0,webAudioMediaStreamDest:!1,supportReplaceTrack:!1,supportWebGL:!1,webAudioWithAEC:!1,supportRequestFrame:!1,supportShareAudio:!1,supportDualStreamEncoding:!1,supportDataChannel:!1,supportPCSetConfiguration:!1,supportWebRTCEncodedTransform:!1,supportWebRTCInsertableStream:!1,supportRequestVideoFrameCallback:!1,supportWebCrypto:!1,supportSuppressLocalAudioPlayback:!1,supportRestrictOwnAudio:!1};function JL(){return XL}function zL(){return"setSinkId"in HTMLAudioElement.prototype&&(!xP("RESTRICTION_SET_PLAYBACK_DEVICE")||(JO()||QO())&&!gN())}function ZL(){return!XL.supportUnifiedPlan||xP("CHROME_FORCE_PLAN_B")&&SN()}function qL(){return xP("ENABLE_JOIN_V4")}function QL(e){return!($O()||nN(87)||ZL()||!xP("ENABLE_PRE_SUB")&&(null==e||!e.autoSubscribe||xP("FORCE_DISABLE_AUTO_SUB")))}function $L(e){return xP("ENABLE_INSTANT_VIDEO")?xP("ENABLE_INSTANT_VIDEO"):!(null==e||!e.autoSubscribe||xP("FORCE_DISABLE_AUTO_SUB"))}function ek(){return!!xP("FORCE_ENABLE_AUT_CC")||!ZL()&&(!!xP("ENABLE_AUT_CC")||void 0)}function tk(){return!!xP("FORCE_ENABLE_AUT_CC")||!ZL()&&(!!xP("ENABLE_AUT_FEEDBACK")||void 0)}function nk(){return navigator.mediaDevices&&"getSupportedConstraints"in navigator.mediaDevices}function ik(){if(nk()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("suppressLocalAudioPlayback"in e)||!e.suppressLocalAudioPlayback)}return tN(141)||rN(141)||lN(141)}function rk(){if(nk()){const e=navigator.mediaDevices.getSupportedConstraints();return!(!("restrictOwnAudio"in e)||!e.restrictOwnAudio)}return tN(141)||rN(141)||lN(125)}let ok=function(e){return e.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",e.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",e.IOS_INTERRUPTION_START="ios-interruption-start",e.IOS_INTERRUPTION_END="ios-interruption-end",e.STATE_CHANGE="state-change",e}({});function sk(e,t,n){return{sampleRate:e,stereo:t,bitrate:n}}function ak(e,t,n,i,r){return{width:e,height:t,frameRate:n,bitrateMin:i,bitrateMax:r}}function ck(e,t,n,i,r){return{width:{max:e},height:{max:t},frameRate:n,bitrateMin:i,bitrateMax:r}}function dk(e,t){return{numSpatialLayers:e,numTemporalLayers:t}}const lk={"90p":ak(160,90),"90p_1":ak(160,90),"120p":ak(160,120,15,30,65),"120p_1":ak(160,120,15,30,65),"120p_3":ak(120,120,15,30,50),"120p_4":ak(212,120),"180p":ak(320,180,15,30,140),"180p_1":ak(320,180,15,30,140),"180p_3":ak(180,180,15,30,100),"180p_4":ak(240,180,15,30,120),"240p":ak(320,240,15,40,200),"240p_1":ak(320,240,15,40,200),"240p_3":ak(240,240,15,40,140),"240p_4":ak(424,240,15,40,220),"360p":ak(640,360,15,80,400),"360p_1":ak(640,360,15,80,400),"360p_3":ak(360,360,15,80,260),"360p_4":ak(640,360,30,80,600),"360p_6":ak(360,360,30,80,400),"360p_7":ak(480,360,15,80,320),"360p_8":ak(480,360,30,80,490),"360p_9":ak(640,360,15,80,800),"360p_10":ak(640,360,24,80,800),"360p_11":ak(640,360,24,80,1e3),"480p":ak(640,480,15,100,500),"480p_1":ak(640,480,15,100,500),"480p_2":ak(640,480,30,100,1e3),"480p_3":ak(480,480,15,100,400),"480p_4":ak(640,480,30,100,750),"480p_6":ak(480,480,30,100,600),"480p_8":ak(848,480,15,100,610),"480p_9":ak(848,480,30,100,930),"480p_10":ak(640,480,10,100,400),"720p":ak(1280,720,15,120,1130),"720p_auto":ak(1280,720,30,900,3e3),"720p_1":ak(1280,720,15,120,1130),"720p_2":ak(1280,720,30,120,2e3),"720p_3":ak(1280,720,30,120,1710),"720p_5":ak(960,720,15,120,910),"720p_6":ak(960,720,30,120,1380),"1080p":ak(1920,1080,15,120,2080),"1080p_1":ak(1920,1080,15,120,2080),"1080p_2":ak(1920,1080,30,120,3e3),"1080p_3":ak(1920,1080,30,120,3150),"1080p_5":ak(1920,1080,60,120,4780),"1440p":ak(2560,1440,30,120,4850),"1440p_1":ak(2560,1440,30,120,4850),"1440p_2":ak(2560,1440,60,120,7350),"4k":ak(3840,2160,30,120,8910),"4k_1":ak(3840,2160,30,120,8910),"4k_3":ak(3840,2160,60,120,13500)},uk={"480p":ck(640,480,5),"480p_1":ck(640,480,5),"480p_2":ck(640,480,30),"480p_3":ck(640,480,15),"720p":ck(1280,720,5),"720p_auto":ak(1280,720,30,900,3e3),"720p_1":ck(1280,720,5),"720p_2":ck(1280,720,30),"720p_3":ck(1280,720,15),"1080p":ck(1920,1080,5),"1080p_1":ck(1920,1080,5),"1080p_2":ck(1920,1080,30),"1080p_3":ck(1920,1080,15)},hk={"1SL1TL":dk(1,1),"3SL3TL":dk(3,3),"2SL3TL":dk(2,3)};function pk(e){return e||(e="480p_1"),"string"==typeof e?Object.assign({},lk[e]):e}function _k(e){return"string"==typeof e?Object.assign({},uk[e]):e}function Ek(e){return"string"==typeof e?Object.assign({},hk[e]):e}const mk={speech_low_quality:sk(16e3,!1),speech_standard:sk(32e3,!1,18),music_standard:sk(48e3,!1),standard_stereo:sk(48e3,!0,56),high_quality:sk(48e3,!1,128),high_quality_stereo:sk(48e3,!0,192)};function fk(e){return"string"==typeof e?Object.assign({},mk[e]):e}const gk=[];function Sk(e){return DN(e,"mediaSource",["screen","window","application"]),!0}let Tk=function(e){return e.NEED_RENEGOTIATE="@need_renegotiate",e.NEED_REPLACE_TRACK="@need_replace_track",e.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",e.NEED_CLOSE="@need_close",e.NEED_ENABLE_TRACK="@need_enable_track",e.NEED_DISABLE_TRACK="@need_disable_track",e.NEED_SESSION_ID="@need_sid",e.SET_OPTIMIZATION_MODE="@set_optimization_mode",e.GET_STATS="@get_stats",e.GET_RTC_STATS="@get_rtc_stats",e.GET_LOW_VIDEO_TRACK="@get_low_video_track",e.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",e.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",e.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",e.NEED_MUTE_TRACK="@need_mute_track",e.NEED_UNMUTE_TRACK="@need_unmute_track",e}({}),Rk=function(e){return e.SCREEN_TRACK="screen_track",e.CUSTOM_TRACK="custome_track",e.LOW_STREAM="low_stream",e.SCREEN_LOW_TRACK="screen_low_track",e}({});let vk=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e}({}),yk=function(e){return e[e.HIGH_STREAM=0]="HIGH_STREAM",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",e}({}),Ck=function(e){return e[e.DISABLE=0]="DISABLE",e[e.LOW_STREAM=1]="LOW_STREAM",e[e.AUDIO_ONLY=2]="AUDIO_ONLY",e[e.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",e[e.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",e[e.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",e[e.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",e[e.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",e[e.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",e}({}),bk=function(e){return e.TRANSCEIVER_UPDATED="transceiver-updated",e.SEI_TO_SEND="sei-to-send",e.SEI_RECEIVED="sei-received",e.TRACK_UPDATED="track-updated",e}({}),Ik=function(e){return e.SOURCE_STATE_CHANGE="source-state-change",e.TRACK_ENDED="track-ended",e.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.CLOSED="closed",e}({}),Ak=function(e){return e.FIRST_FRAME_DECODED="first-frame-decoded",e.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",e.VIDEO_STATE_CHANGED="video-state-changed",e.PLAY_START="play-start",e.PLAY_END="play-end",e.FIRST_FRAME_RENDER="first-frame-render",e}({}),wk=function(e){return e.AUDIO="audio",e.VIDEO="video",e.DATA="data",e}({}),Ok=function(e){return e.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",e.RECEIVE_TRACK_BUFFER="receive_track_buffer",e.ON_AUDIO_BUFFER="on_audio_buffer",e.UPDATE_SOURCE="update_source",e}({});!function(e){e.UPDATE_TRACK_SOURCE="update-track-source"}({});const Nk={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},Dk={sendBytes:0,sendBitrate:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,sendResolutionHeight:0,sendResolutionWidth:0,captureResolutionHeight:0,captureResolutionWidth:0,targetSendBitrate:0,totalDuration:0,totalFreezeTime:0,currentPacketLossRate:0},Pk={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveLevel:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receivePacketsDiscarded:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1},Lk={uplinkNetworkQuality:0,downlinkNetworkQuality:0},kk={transportDelay:0,end2EndDelay:0,receiveBitrate:0,receiveBytes:0,receiveDelay:0,receivePackets:0,receivePacketsLost:0,receiveResolutionHeight:0,receiveResolutionWidth:0,totalDuration:0,totalFreezeTime:0,freezeRate:0,packetLossRate:0,currentPacketLossRate:0,publishDuration:-1};let Mk=function(e){return e.ON_TRACK="on_track",e.ON_NODE="on_node",e}({}),Uk=function(e){return e.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",e.REQUEST_CONSTRAINTS="request_constraints",e}({}),Vk=function(e){return e.IDLE="IDLE",e.INITING="INITING",e.INITEND="INITEND",e}({}),xk=function(e){return e.STATE_CHANGE="state_change",e.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",e.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",e.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",e}({}),Fk=function(e){return e.NONE="none",e.INIT="init",e.CANPLAY="canplay",e.PLAYING="playing",e.PAUSED="paused",e.SUSPEND="suspend",e.STALLED="stalled",e.WAITING="waiting",e.ERROR="error",e.DESTROYED="destroyed",e.ABORT="abort",e.ENDED="ended",e.EMPTIED="emptied",e.LOADEDDATA="loadeddata",e}({}),Bk=function(e){return e[e.VideoStateStopped=0]="VideoStateStopped",e[e.VideoStateStarting=1]="VideoStateStarting",e[e.VideoStateDecoding=2]="VideoStateDecoding",e[e.VideoStateFrozen=3]="VideoStateFrozen",e}({});const jk={uninit:100,none:110,init:120,loadeddata:130,canplay:200,playing:210,paused:220,suspend:300,stalled:310,waiting:320,error:330,destroyed:340,abort:350,ended:360,emptied:370};let Gk=function(e){return e.OPEN="open",e.MESSAGE="message",e.CLOSE="close",e.CLOSING="closing",e.ERROR="error",e}({});function Wk(e,t,n,i,r){var o,s,a={};return Object.keys(i).forEach((function(e){a[e]=i[e]})),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=sr(o=Sr(s=n.slice()).call(s)).call(o,(function(n,i){return i(e,t,n)||n}),a),r&&void 0!==a.initializer&&(a.value=a.initializer?a.initializer.call(r):void 0,a.initializer=void 0),void 0===a.initializer?(Object.defineProperty(e,t,a),null):a}function Kk(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function Hk(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yk(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Xk(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Yk(Object(n),!0).forEach((function(t){Hk(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Yk(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function Jk(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(a.push(i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return Kk(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Kk(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}let zk=class extends YN{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(bk.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,t){super(),Hk(this,"trackMediaType",void 0),Hk(this,"_ID",void 0),Hk(this,"_rtpTransceiver",void 0),Hk(this,"_lowRtpTransceiver",void 0),Hk(this,"_hints",[]),Hk(this,"_isClosed",!1),Hk(this,"_originMediaStreamTrack",void 0),Hk(this,"mediaStreamTrack",void 0),Hk(this,"_external",{}),this._ID=t||kD(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,function(e){Ui(gk).call(gk,e)||gk.push(e)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||bD((()=>{var e;HL.reportApiInvoke(null,{name:zN.GET_MEDIA_STREAM_TRACK,options:[],tag:ZN.TRACER}).onSuccess((null===(e=this._mediaStreamTrack)||void 0===e?void 0:e.label)||"")}),this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===vk.LOW_STREAM?this._lowRtpTransceiver:this._rtpTransceiver}getMediaStreamTrackSettings(){return this.getMediaStreamTrack(!0).getSettings()}close(){this._isClosed=!0,this._lowRtpTransceiver=void 0,this._rtpTransceiver=void 0,function(e){const t=gk.indexOf(e);-1!==t&&gk.splice(t,1)}(this),this.emit(Ik.CLOSED),this.removeAllListeners(bk.SEI_RECEIVED)}_updateRtpTransceiver(e,t){if(t===vk.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(bk.TRANSCEIVER_UPDATED,e,t)}},Zk=class extends zk{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,t){super(e,t),Hk(this,"_enabled",!0),Hk(this,"_muted",!1),Hk(this,"_isExternalTrack",!1),Hk(this,"_isClosed",!1),Hk(this,"_enabledMutex",void 0),Hk(this,"processor",void 0),Hk(this,"_processorContext",void 0),Hk(this,"_handleTrackEnded",(()=>{this.onTrackEnded()})),this._enabledMutex=new JD("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,t;return null!==(e=null===(t=this._originMediaStreamTrack)||void 0===t?void 0:t.label)&&void 0!==e?e:""}close(){this._isClosed||(this.stop(),this._originMediaStreamTrack.stop(),this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack.stop(),this._mediaStreamTrack=null),this._originMediaStreamTrack=null,this._enabledMutex=null,SL.debug("[".concat(this.getTrackId(),"] close")),this.emit(Tk.NEED_CLOSE),super.close())}async _updateOriginMediaStreamTrack(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];this._isExternalTrack=n,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await lD(this,Tk.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))}_getDefaultPlayerConfig(){return{}}onTrackEnded(){SL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ik.TRACK_ENDED)}stateCheck(e,t){if(SL.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(t,"]")),NN(t,e),this._enabled&&this._muted&&"enabled"===e&&!1===t)throw new ON(wN.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",SL);if(!this._enabled&&!this._muted&&"muted"===e&&!0===t)throw new ON(wN.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",SL)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():cp.resolve([])}};const qk=window.AudioContext||window.webkitAudioContext;let Qk,$k=null;const eM=new class extends YN{constructor(){super(...arguments),Hk(this,"prevState",void 0),Hk(this,"curState",void 0),Hk(this,"currentTime",void 0),Hk(this,"currentTimeStuckAt",void 0),Hk(this,"interruptDetectorTrack",void 0),Hk(this,"onLocalAudioTrackMute",(()=>{SL.info("ios15-interruption-start"),this.emit(ok.IOS_15_16_INTERRUPTION_START)})),Hk(this,"onLocalAudioTrackUnmute",(async()=>{SL.info("ios15-interruption-end"),"running"!==this.curState||this.duringInterruption?SL.info("ios15-interruption-end-canceled"):($k&&await $k.suspend(),this.emit(ok.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return"running"===this.prevState&&"interrupted"===this.curState}bindInterruptDetectorTrack(e){SL.debug("webaudio bindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=e,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(e){SL.debug("webaudio unbindInterruptDetectorTrack ".concat(e.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===e&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function tM(){if(!$k){if(function(){if(!qk)return void SL.error("your browser is not support web audio");SL.info("create audio context");const e=Xk({},xP("WEBAUDIO_INIT_OPTIONS"));SL.debug("audio context init option:",JSON.stringify(e)),$k=new qk(e),eM.curState=$k.state,$k.onstatechange=()=>{eM.prevState=eM.curState,eM.curState=$k?$k.state:void 0;const e=eM.prevState,t=eM.curState,n="running"===t,i="interrupted"===t,r="running"===e,o="suspended"===e,s="interrupted"===e,a=GO().osVersion;(eN()||EN())&&r&&i&&(SL.info("ios".concat(a,"-interruption-start")),eM.emit(ok.IOS_INTERRUPTION_START)),(eN()||EN())&&(o||s)&&n&&(SL.info("ios".concat(a,"-interruption-end")),eM.emit(ok.IOS_INTERRUPTION_END)),e!==t&&eM.emit(ok.STATE_CHANGE,t,e)},setInterval((()=>{var e;const t=null===(e=$k)||void 0===e?void 0:e.currentTime;eM.currentTime!==t?(eM.currentTimeStuckAt&&(SL.debug("AudioContext current time resume at ".concat(t)),eM.currentTimeStuckAt=void 0),eM.currentTime=t):(t!==eM.currentTimeStuckAt&&(HL.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:t},tag:ZN.TRACER}).onSuccess(),SL.warning("AudioContext current time stuck at ".concat(t))),eM.currentTimeStuckAt=t)}),5e3),async function(e){const t=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let n,i,r=!1,o=!1,s=!1;function a(t){"running"===e.state?c(!1):eN()||EN()?"suspended"===e.state&&(c(!0),t&&e.resume().then(d,d)):"closed"!==e.state&&(c(!0),t&&e.resume().then(d,d))}function c(e){if(r!==e){r=e;for(let n=0,i=t;n<i.length;n+=1){const t=i[n];e?window.addEventListener(t,l,{capture:!0,passive:!0}):window.removeEventListener(t,l,{capture:!0,passive:!0})}}}function d(){a(!1)}function l(){a(!0)}function u(){let e;try{e=n.play(),e?e.then(_,_):(n.addEventListener("playing",_),n.addEventListener("abort",_),n.addEventListener("error",_))}catch(e){_()}}function h(e){s||(n.paused?e?(p(!1),s=!0,u()):p(!0):p(!1))}function p(e){if(o!==e){o=e;for(let n=0,i=t;n<i.length;n++){const t=i[n];e?window.addEventListener(t,E,{capture:!0,passive:!0}):window.removeEventListener(t,E,{capture:!0,passive:!0})}}}function _(){n.removeEventListener("playing",_),n.removeEventListener("abort",_),n.removeEventListener("error",_),s=!1,h(!1)}function E(){h(!0)}if(eN()&&xP("IOS_BG_TAG")){const t=e.createMediaStreamDestination(),r=document.createElement("div");r.innerHTML="<audio x-webkit-airplay='deny'></audio>",n=r.children.item(0),n.controls=!1,n.disableRemotePlayback=!0,n.preload="auto",n.srcObject=t.stream,i=()=>{if(xP("IOS_AUTO_RESTART_BG_TAG")&&n&&n.srcObject&&!s&&(!n.paused||!0!==o)){n.paused||n.pause();try{s=!0,u()}catch(e){s=!1}return!0}},h(!0)}return eM.on(ok.STATE_CHANGE,(function(){a(!0)})),a(!1),i}($k).then((e=>{Qk=e}))}(),!$k)throw new ON(wN.NOT_SUPPORTED,"can not create audio context");return $k}return $k}function nM(e){if(function(){if(null!==iM)return iM;const e=tM(),t=e.createBufferSource(),n=e.createGain(),i=e.createGain();t.connect(n),t.connect(i),t.disconnect(n);let r=!1;try{t.disconnect(n)}catch(e){r=!0}return t.disconnect(),iM=r,r}())return;const t=e.connect,n=e.disconnect;e.connect=(n,i,r)=>{var o;return e._inputNodes||(e._inputNodes=[]),Ui(o=e._inputNodes).call(o,n)||(n instanceof AudioNode?(e._inputNodes.push(n),t.call(e,n,i,r)):t.call(e,n,i)),e},e.disconnect=(i,r,o)=>{n.call(e),i?SD(e._inputNodes,i):e._inputNodes=[];for(const n of e._inputNodes)t.call(e,n)}}let iM=null;function rM(e,t){let n=!1;const i=1/t;if(xP("DISABLE_WEBAUDIO")){const t=window.setInterval((()=>{n?window.clearInterval(t):e(performance.now()/1e3)}),1e3*i)}else{const t=tM();let r=t.createGain();r.gain.value=0,r.connect(t.destination);const o=()=>{if(n)return void(r=null);const s=t.createOscillator();s.onended=o,s.connect(r),s.start(0),s.stop(t.currentTime+i),e(t.currentTime)};o()}return()=>{n=!0}}let oM=class{constructor(){Hk(this,"context",void 0),Hk(this,"analyserNode",void 0),Hk(this,"sourceNode",void 0),this.context=tM(),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4}updateSource(e){if(e!==this.sourceNode){if(this.sourceNode)try{this.sourceNode.disconnect(this.analyserNode)}catch(e){}this.sourceNode=e,null==e||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode)return 0;if(!this.context||eN()||EN()||"running"!==this.context.state&&this.context.resume(),!this.analyserNode)return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const t=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(t);for(let n=0;n<e.length;++n)e[n]=t[n]/128-1}const t=sr(e).call(e,((e,t)=>e+t*t),0)/e.length;return Math.max(10*Math.log10(t)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,t;null===(e=this.sourceNode)||void 0===e||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,null===(t=this.sourceNode)||void 0===t||t.connect(this.analyserNode)}catch(e){SL.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}},sM=class extends YN{get processSourceNode(){return this.sourceNode}set processedNode(e){var t;if(!this.isDestroyed&&this._processedNode!==e){try{var n;null===(n=this.sourceNode)||void 0===n||n.disconnect(this.outputNode)}catch(e){}null===(t=this._processedNode)||void 0===t||t.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),Hk(this,"outputNode",void 0),Hk(this,"outputTrack",void 0),Hk(this,"isPlayed",!1),Hk(this,"sourceNode",void 0),Hk(this,"context",void 0),Hk(this,"audioBufferNode",void 0),Hk(this,"destNode",void 0),Hk(this,"audioOutputLevel",0),Hk(this,"volumeLevelAnalyser",void 0),Hk(this,"_processedNode",void 0),Hk(this,"playNode",void 0),Hk(this,"isDestroyed",!1),Hk(this,"onNoAudioInput",void 0),Hk(this,"isNoAudioInput",!1),Hk(this,"_noAudioInputCount",0),this.context=tM(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),nM(this.outputNode),this.volumeLevelAnalyser=new oM}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=e=>{this.emit(Ok.ON_AUDIO_BUFFER,function(e){for(let t=0;t<e.outputBuffer.numberOfChannels;t+=1){const n=e.outputBuffer.getChannelData(t);for(let e=0;e<n.length;e+=1)n[e]=0}return e.inputBuffer}(e))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!JL().webAudioMediaStreamDest)throw new ON(wN.NOT_SUPPORTED,"your browser is not support audio processor");return this.destNode&&this.outputTrack||(this.destNode=this.context.createMediaStreamDestination(),this.outputNode.connect(this.destNode),this.outputTrack=this.destNode.stream.getAudioTracks()[0]),this.outputTrack}play(e){"running"!==this.context.state&&RD((()=>{eM.emit("autoplay-failed")})),this.isPlayed=!0,this.playNode=e||this.context.destination,this.outputNode.connect(this.playNode)}stop(){if(this.isPlayed)try{this.outputNode.disconnect(this.playNode)}catch(e){}this.isPlayed=!1}getAccurateVolumeLevel(){return this.volumeLevelAnalyser.getVolumeLevel()}async checkHasAudioInput(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;eN()||EN()?"suspended"===this.context.state&&this.context.resume():"running"!==this.context.state&&this.context.resume();const t=this.volumeLevelAnalyser.getAnalyserNode();let n;t.getFloatTimeDomainData?(n=new Float32Array(t.fftSize),t.getFloatTimeDomainData(n)):(n=new Uint8Array(t.fftSize),t.getByteTimeDomainData(n));let i=!1;for(let e=0;e<n.length;e++)0!==n[e]&&(i=!0);return i?(this.isNoAudioInput=!1,!0):(await LD(200),await this.checkHasAudioInput(e?e+1:1)&&i)}getAudioVolume(){return this.outputNode.gain.value}setVolume(e){this.outputNode.gain.setValueAtTime(e,this.context.currentTime)}destroy(){this.disconnect(),this.stop(),this.isDestroyed=!0,this.onNoAudioInput=void 0}disconnect(){var e,t;null===(e=this.processedNode)||void 0===e||e.disconnect(),null===(t=this.sourceNode)||void 0===t||t.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?null===(e=this.processedNode)||void 0===e||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}},aM=class extends sM{get isFreeze(){return!1}constructor(e,t,n){var i;if(super(),Hk(this,"sourceNode",void 0),Hk(this,"track",void 0),Hk(this,"clonedTrack",void 0),Hk(this,"audioElement",void 0),Hk(this,"isCurrentTrackCloned",!1),Hk(this,"isRemoteTrack",!1),Hk(this,"originVolumeLevelAnalyser",void 0),Hk(this,"rebuildWebAudio",(async()=>{if(SL.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&await this.checkHasAudioInput(),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void SL.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then((()=>SL.info("resume success"))),SL.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const e=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?e.stop():this.isCurrentTrackCloned=!0;const t=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(t),nM(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const n=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(n,this.context.currentTime),nM(this.outputNode),this.emit(Ok.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=t,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),"audio"!==e.kind)throw new ON(wN.UNEXPECTED_ERROR);this.track=e;const r=new MediaStream([this.track]);if(this.isRemoteTrack=!!t,this.sourceNode=this.context.createMediaStreamSource(r),nM(this.sourceNode),n){const e=n.clone();e.enabled=!0,this.clonedTrack=e,SL.debug("create an unmuted track ".concat(e.id," from the original track ").concat(n.id," to get the volume"));const t=this.context.createMediaStreamSource(new MediaStream([e]));nM(t),this.originVolumeLevelAnalyser=new oM,this.originVolumeLevelAnalyser.updateSource(t)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=r;const o=GO();t&&o.os===VO.IOS&&Number(null===(i=o.osVersion)||void 0===i?void 0:i.split(".")[0])<15&&(eM.on(ok.STATE_CHANGE,(()=>{"suspended"===this.context.state?document.body.addEventListener("click",this.rebuildWebAudio,!0):"running"===this.context.state&&this.rebuildWebAudio()})),this.checkHasAudioInput().then((e=>{e||document.body.addEventListener("click",this.rebuildWebAudio,!0)})))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const t=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(t),nM(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(Ok.UPDATE_SOURCE),this.audioElement.srcObject=t}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),eM.off("state-change",this.rebuildWebAudio),null===(e=this.originVolumeLevelAnalyser)||void 0===e||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const t=e.clone();t.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=t),SL.debug("create an unmuted track ".concat(t.id," from the original track ").concat(e.id," to get the volume"));const n=this.context.createMediaStreamSource(new MediaStream([t]));nM(n),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(n)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}};async function cM(e,t,n){const i=(e,t)=>e?"number"!=typeof e?e.max||e.exact||e.ideal||e.min||t:e:t,r={audio:!!n&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e,maxHeight:i(t.height,1080),maxWidth:i(t.width,1920)}}};return t.frameRate&&"number"!=typeof t.frameRate?(r.video.mandatory.maxFrameRate=t.frameRate.max,r.video.mandatory.minFrameRate=t.frameRate.min):"number"==typeof t.frameRate&&(r.video.mandatory.maxFrameRate=t.frameRate),await navigator.mediaDevices.getUserMedia(r)}async function dM(e,t){const n=await lM(e.mediaSource),i=await function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new cp(((n,i)=>{const r=document.createElement("div");r.innerText="share screen",r.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom:  solid 1px #B9B8B9;");const o=document.createElement("div");o.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const s=document.createElement("div");s.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",s.setAttribute("style","height: 12%;");const a=document.createElement("div");a.setAttribute("style","width: 100%; height: 80%; background: #FFF; border:  solid 1px #CBCBCB; display: flex; flex-wrap: wrap; justify-content: space-around; overflow-y: scroll; padding: 0 15px; box-sizing: border-box;");const c=document.createElement("div");c.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const d=document.createElement("button");d.innerHTML="cancel",d.setAttribute("style","width: 85px;"),d.onclick=()=>{document.body.removeChild(h);const e=new Error("NotAllowedError");e.name="NotAllowedError",i(e)};let l=t;const u=document.createElement("div");if(t){const e=document.createElement("input");e.setAttribute("type","checkbox");const t=document.createElement("span");e.setAttribute("style","margin-right: 6px;"),t.innerText="Share audio",e.checked=l,e.onchange=()=>{l=e.checked},u.appendChild(e),u.appendChild(t)}c.appendChild(u),c.appendChild(d),o.appendChild(s),o.appendChild(a),o.appendChild(c);const h=document.createElement("div");h.setAttribute("style","position: fixed; z-index: 99999999; top: 50%; left: 50%; width: 620px; height: 525px; background: #ECECEC; border-radius: 4px; -webkit-transform: translate(-50%,-50%); transform: translate(-50%,-50%);"),h.appendChild(r),h.appendChild(o),document.body.appendChild(h),e.map((e=>{if(e.id){const t=document.createElement("div");t.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let i=e.thumbnail;try{i.getSize().width>1920&&(i=i.resize({width:1920}))}catch(e){throw e&&e.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),e}t.innerHTML='<div style="height: 120px; display: table-cell; vertical-align: middle;"><img style="width: 100%; background: #333333; box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2);" src='+i.toDataURL()+' /></div><span style="\theight: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+e.name.replace(/[\u00A0-\u9999<>\&]/g,(function(e){return"&#"+e.charCodeAt(0)+";"}))+"</span>",t.onclick=()=>{document.body.removeChild(h),n({sourceId:e.id,audio:l})},a.appendChild(t)}}))}))}(n,t),r=i.sourceId,o=i.audio;return await cM(r,e,o)}async function lM(e){let t=["window","screen"];"application"!==e&&"window"!==e||(t=["window"]),"screen"===e&&(t=["screen"]);const n=JN();if(!n)throw console.error("failed to fetch electron, please mount it to window"),new ON(wN.ELECTRON_IS_NULL);let i=null;try{var r;i=(null===(r=n.desktopCapturer)||void 0===r?void 0:r.getSources({types:t}))||n.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:t})}catch(e){i=null}i&&i.then||(i=new cp(((e,i)=>{n.desktopCapturer.getSources({types:t},((t,n)=>{t?i(t):e(n)}))})));try{return await i}catch(e){throw new ON(wN.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,e.toString())}}const uM=new JD("safari");let hM=!1,pM=!1;async function _M(e,t){let n=0,i=null;for(;n<2;)try{i=await EM(e,t,n>0);break}catch(e){if(e instanceof ON)throw SL.error("[".concat(t,"] ").concat(e.toString())),e;const i=mM(e.name||e.code||e,e.message);if(i.code===wN.MEDIA_OPTION_INVALID){SL.debug("[".concat(t,"] detect media option invalid, retry")),n+=1,await LD(500);continue}throw SL.error("[".concat(t,"] ").concat(i.toString())),i}if(!i)throw new ON(wN.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return i}async function EM(e,t,n){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new ON(wN.NOT_SUPPORTED,"can not find getUserMedia");n&&(e.video&&(delete e.video.width,delete e.video.height),e.screen&&(delete e.screen.width,delete e.screen.height));const i=JL(),r=new MediaStream;if(e.audioSource&&r.addTrack(e.audioSource),e.videoSource&&r.addTrack(e.videoSource),!e.audio&&!e.video&&!e.screen)return SL.debug("Using Video Source/ Audio Source"),r;if(e.screen)if(JN())e.screen.sourceId?fM(r,await cM(e.screen.sourceId,e.screen,!!e.screenAudio)):fM(r,await dM(e.screen,!!e.screenAudio));else if(JO()&&e.screen.extensionId&&e.screen.mandatory){if(!i.getStreamFromExtension)throw new ON(wN.NOT_SUPPORTED,"This browser does not support screen sharing");SL.debug("[".concat(t,'] Screen access on chrome stable, looking for extension"'));const n=await(s=e.screen.extensionId,a=t,new cp(((e,t)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},(n=>{if(!n||!n.streamId)return SL.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),n),void t(new ON(wN.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));e(n.streamId)}))}catch(e){SL.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),e.toString()),t(new ON(wN.CHROME_PLUGIN_NOT_INSTALL))}})));e.screen.mandatory.chromeMediaSourceId=n,fM(r,await navigator.mediaDevices.getUserMedia({video:{mandatory:e.screen.mandatory}}))}else if(i.getDisplayMedia){var o;e.screen.mediaSource&&Sk(e.screen.mediaSource);const n={width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate,displaySurface:null!==(o=e.screen.displaySurface)&&void 0!==o?o:"screen"===e.screen.mediaSource?"monitor":e.screen.mediaSource},i=e.screen,s=i.selfBrowserSurface,a=i.surfaceSwitching,c=i.systemAudio,d=i.preferCurrentTab,l=i.windowAudio,u=i.monitorTypeSurfaces,h={selfBrowserSurface:s,surfaceSwitching:a,systemAudio:c,preferCurrentTab:d,windowAudio:l,monitorTypeSurfaces:u};!s&&delete h.selfBrowserSurface,!a&&delete h.surfaceSwitching,!c&&delete h.systemAudio,!d&&delete h.preferCurrentTab,!l&&delete h.windowAudio,!u&&delete h.monitorTypeSurfaces,SL.debug("[".concat(t,"] getDisplayMedia:"),JSON.stringify({video:n,audio:e.screenAudio,controls:h})),fM(r,await navigator.mediaDevices.getDisplayMedia(Xk({video:n,audio:e.screenAudio},h)))}else{if(!$O())throw SL.error("[".concat(t,"] This browser does not support screenSharing")),new ON(wN.NOT_SUPPORTED,"This browser does not support screen sharing");{e.screen.mediaSource&&Sk(e.screen.mediaSource);const n={video:{mediaSource:e.screen.mediaSource,width:e.screen.width,height:e.screen.height,frameRate:e.screen.frameRate}};SL.debug("[".concat(t,"] getUserMedia: ").concat(JSON.stringify(n))),fM(r,await navigator.mediaDevices.getUserMedia(n))}}var s,a;if(!e.video&&!e.audio)return r;let c={video:e.video,audio:e.audio},d=xP("MEDIA_DEVICE_CONSTRAINTS");if(d)try{"string"==typeof d&&(d=JSON.parse(d)),c=BD(c,d)}catch(e){}SL.debug("[".concat(t,"] GetUserMedia"),JSON.stringify(c)),GO();let l,u=null;(zO()||eN()||YO())&&(u=await uM.lock());try{l=await navigator.mediaDevices.getUserMedia(c)}catch(e){throw u&&u(),e}return c.audio&&(hM=!0),c.video&&(pM=!0),fM(r,l),u&&u(),r}function mM(e,t){switch(e){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new ON(wN.MEDIA_OPTION_INVALID,"".concat(e,": ").concat(t));case"NotFoundError":case"DevicesNotFoundError":return new ON(wN.DEVICE_NOT_FOUND,"".concat(e,": ").concat(t));case"NotSupportedError":return new ON(wN.NOT_SUPPORTED,"".concat(e,": ").concat(t));case"NotReadableError":return new ON(wN.NOT_READABLE,"".concat(e,": ").concat(t));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new ON(wN.PERMISSION_DENIED,"".concat(e,": ").concat(t));case"ConstraintNotSatisfiedError":return new ON(wN.CONSTRAINT_NOT_SATISFIED,"".concat(e,": ").concat(t));default:return SL.error("getUserMedia unexpected error",e),new ON(wN.UNEXPECTED_ERROR,"".concat(e,": ").concat(t))}}function fM(e,t){const n=e.getVideoTracks()[0],i=e.getAudioTracks()[0],r=t.getVideoTracks()[0],o=t.getAudioTracks()[0];o&&(i&&e.removeTrack(i),e.addTrack(o)),r&&(n&&e.removeTrack(n),e.addTrack(r))}const gM=new class extends YN{get state(){return this._state}set state(e){e!==this._state&&(this.emit(xk.STATE_CHANGE,e),this._state=e)}constructor(){super(),Hk(this,"_state",Vk.IDLE),Hk(this,"isAccessMicrophonePermission",!1),Hk(this,"isAccessCameraPermission",!1),Hk(this,"lastAccessMicrophonePermission",!1),Hk(this,"lastAccessCameraPermission",!1),Hk(this,"checkdeviceMatched",!1),Hk(this,"deviceInfoMap",new Map),this.init().then((()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval((()=>{(xP("ENUMERATE_DEVICES_INTERVAL")||(TN()||KO()===VO.HARMONY_OS)&&SN())&&this.updateDevicesInfo()}),xP("ENUMERATE_DEVICES_INTERVAL_TIME"))})).catch((e=>SL.error(e.toString())))}async enumerateDevices(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)throw new ON(wN.NOT_SUPPORTED,"enumerateDevices() not supported.");const i=await navigator.mediaDevices.enumerateDevices(),r=this.checkMediaDeviceInfoIsOk(i);let o=!this.isAccessMicrophonePermission&&e,s=!this.isAccessCameraPermission&&t;r.audio&&(o=!1),r.video&&(s=!1);let a=null,c=null,d=null;if(!n&&(o||s)){if(uM.isLocked&&(SL.debug("[device manager] wait GUM lock"),(await uM.lock())(),SL.debug("[device manager] GUM unlock")),hM&&(o=!1,this.isAccessMicrophonePermission=!0),pM&&(s=!1,this.isAccessCameraPermission=!0),SL.debug("[device manager] check media device permissions",e,t,o,s),o&&s){try{d=await navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(e){const t=mM(e.name||e.code||e,e.message);if(t.code===wN.PERMISSION_DENIED)throw t;SL.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(o){try{a=await navigator.mediaDevices.getUserMedia({audio:e})}catch(e){const t=mM(e.name||e.code||e,e.message);if(t.code===wN.PERMISSION_DENIED)throw t;SL.warning("getUserMedia failed in getDevices",t)}this.isAccessMicrophonePermission=!0}else if(s){try{c=await navigator.mediaDevices.getUserMedia({video:t})}catch(e){const t=mM(e.name||e.code||e,e.message);if(t.code===wN.PERMISSION_DENIED)throw t;SL.warning("getUserMedia failed in getDevices",t)}this.isAccessCameraPermission=!0}SL.debug("[device manager] mic permission",e,"cam permission",t)}try{const e=await navigator.mediaDevices.enumerateDevices();return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,e}catch(e){return a&&a.getTracks().forEach((e=>e.stop())),c&&c.getTracks().forEach((e=>e.stop())),d&&d.getTracks().forEach((e=>e.stop())),a=null,c=null,d=null,new ON(wN.ENUMERATE_DEVICES_FAILED,e.toString()).throw()}}async getRecordingDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audioinput"===e.kind))}async getCamerasDevices(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!1,!0,e)).filter((e=>"videoinput"===e.kind))}async getSpeakers(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return(await this.enumerateDevices(!0,!1,e)).filter((e=>"audiooutput"===e.kind))}searchDeviceIdByName(e){let t=null;return this.deviceInfoMap.forEach((n=>{n.device.label===e&&(t=n.device.deviceId)})),t}async getDeviceById(e){const t=(await this.enumerateDevices(!0,!0,!0)).find((t=>t.deviceId===e));if(!t)throw new ON(wN.DEVICE_NOT_FOUND,"deviceId: ".concat(e));return t}async init(){this.state=Vk.INITING;try{await this.updateDevicesInfo(),this.state=Vk.INITEND}catch(e){if(this.state=Vk.IDLE,!("boolean"==typeof isSecureContext?isSecureContext:"https:"===location.protocol||"file:"===location.protocol||"localhost"===location.hostname||"127.0.0.1"===location.hostname||"::1"===location.hostname))throw new ON(wN.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.");throw SL.warning("Device Detection functionality cannot start properly.",e.toString()),e}}async updateDevicesInfo(){const e=await this.enumerateDevices(!0,!0,!0),t=Date.now(),n=[];if(e[0]&&e[0].label&&!1===this.checkdeviceMatched){this.checkdeviceMatched=!0;const t=e.find((e=>"audioinput"===e.kind&&"default"===e.deviceId)),n=e.find((e=>"audiooutput"===e.kind&&"default"===e.deviceId));t&&n?n.groupId===t.groupId?SL.debug("[device-check] default input ".concat(t.label," and output ").concat(n.label," is the same group")):SL.debug("[device-check] default input ".concat(t.label," and output ").concat(n.label," is not the same group")):SL.debug("[device-check] default input or output not found")}const i=this.checkMediaDeviceInfoIsOk(e);if(e.forEach((e=>{if(!e.deviceId)return;const i=this.deviceInfoMap.get("".concat(e.kind,"_").concat(e.deviceId));if("ACTIVE"!==(i?i.state:"INACTIVE")){const i={initAt:t,updateAt:t,device:e,state:"ACTIVE"};this.deviceInfoMap.set("".concat(e.kind,"_").concat(e.deviceId),i),n.push(i)}i&&(i.updateAt=t)})),this.deviceInfoMap.forEach(((e,i)=>{"ACTIVE"===e.state&&e.updateAt!==t&&(e.state="INACTIVE",n.push(e))})),this.state!==Vk.INITEND)return i.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(i.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));n.forEach((e=>{switch(e.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(xk.RECORDING_DEVICE_CHANGED,e);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(xk.CAMERA_DEVICE_CHANGED,e);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(xk.PLAYOUT_DEVICE_CHANGED,e)}})),i.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),i.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)}checkMediaDeviceInfoIsOk(e){const t=e.filter((e=>"audioinput"===e.kind)),n=e.filter((e=>"videoinput"===e.kind)),i={audio:!1,video:!1};for(const e of t)if(e.label&&e.deviceId){i.audio=!0;break}for(const e of n)if(e.label&&e.deviceId){i.video=!0;break}return i}};let SM=!1;const TM=new class extends YN{constructor(){super(...arguments),Hk(this,"onAutoplayFailed",void 0),Hk(this,"onAudioAutoplayFailed",void 0)}};function RM(){if(SM)return xP("FLS_AUTOPLAY_EMITS")?(TM.onAutoplayFailed&&TM.onAutoplayFailed(),TM.emit("autoplay-failed")):void 0;{const e=t=>{t.preventDefault(),function(){try{const e=tM();"running"!==e.state&&e.resume().catch((e=>{var t;SL.warning("resume web audio context on autoplay gesture failed",(null==e||null===(t=e.toString)||void 0===t?void 0:t.call(e))||e)}))}catch(t){var e;SL.warning("create web audio context on autoplay gesture failed",(null==t||null===(e=t.toString)||void 0===e?void 0:e.call(t))||t)}}(),SM=!1,RN()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};SM=!0,RN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),SL.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),TM.onAutoplayFailed?TM.onAutoplayFailed():TM.onAudioAutoplayFailed?SL.warning("AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.\n\n  Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."):SL.warning("We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.\n\n  It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.\n\n  Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web ."),TM.emit("autoplay-failed")}}function vM(e,t,n,i){if(!e)return;const r=HL.getBaseInfoBySessionId(e);if(!r)return;const o=r.info,s=Date.now(),a=Xk(Xk({},o),{},{vid:void 0===o.vid?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:TM.onAutoplayFailed||TM.onAudioAutoplayFailed?1:-1,errorMsg:n,mediaType:t,trackId:i,extend:void 0});HL.send({type:IL.AUTOPLAY_FAILED,data:a},!0)}const yM=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],CM=new class{constructor(){Hk(this,"onAutoplayFailed",void 0),Hk(this,"elementMap",new Map),Hk(this,"elementStateMap",new Map),Hk(this,"elementsNeedToResume",[]),Hk(this,"sinkIdMap",new Map),Hk(this,"elementIdMap",new WeakMap),Hk(this,"autoResumeAfterInterruption",(e=>cp.all(Array.from(this.elementMap.entries()).map((async t=>{let n=Jk(t,2),i=n[0],r=n[1];const o=this.elementStateMap.get(i),s=r.srcObject.getAudioTracks()[0],a=s&&s.readyState;if(SL.debug("resume after interrupted, ele: ".concat(o," audio: ").concat(a," ").concat(e)),"live"===a){if(e)return r.pause(),r.play();if("running"===eM.curState)return hN()?(r.pause(),r.play()):o&&"paused"===o?r.play():void 0}}))))),Hk(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{Array.from(this.elementMap.entries()).forEach((e=>{let t=Jk(e,2);t[0];let n=t[1];const i=n.srcObject.getAudioTracks()[0];i&&"live"===i.readyState&&(SL.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),n.pause(),n.play())}))})),this.autoResumeAudioElement(),eM.on(ok.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),eM.on(ok.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),eM.on(ok.STATE_CHANGE,(()=>{eN()&&"suspended"===eM.prevState&&"running"===eM.curState&&this.autoResumeAfterInterruption()}))}async setSinkID(e,t){const n=this.elementMap.get(e);if(this.sinkIdMap.set(e,t),n)try{await n.setSinkId(t)}catch(e){throw new ON(wN.PERMISSION_DENIED,"can not set sink id: "+e.toString())}}play(e,t,n,i){if(this.elementMap.has(t))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([e]),this.elementIdMap.set(r,{id:t}),this.bindAudioElementEvents(t,r),this.elementMap.set(t,r),this.elementStateMap.set(t,Fk.INIT),this.setVolume(t,n);const o=this.sinkIdMap.get(t);if(o)try{r.setSinkId(o).catch((e=>{SL.warning("[".concat(t,"] set sink id failed"),e.toString())}))}catch(e){SL.warning("[".concat(t,"] set sink id failed"),e.toString())}const s=r.play();s&&s.then&&s.catch((e=>{i&&vM(i,"audio",e.message,t),SL.warning("audio element play warning",e.toString()),this.elementMap.has(t)&&"NotAllowedError"===e.name&&(SL.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),RD((()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),RM()})))}))}updateTrack(e,t){const n=this.elementMap.get(e);n&&(n.srcObject=new MediaStream([t]))}isPlaying(e){return this.elementMap.has(e)&&"playing"===this.elementStateMap.get(e)}setVolume(e,t){const n=this.elementMap.get(e);n&&(t=Math.max(0,Math.min(100,t)),n.volume=t/100)}getVolume(e){const t=this.elementMap.get(e);return t?t.volume:0}stop(e){const t=this.elementMap.get(e);if(this.sinkIdMap.delete(e),!t)return;const n=this.elementsNeedToResume.indexOf(t);this.elementsNeedToResume.splice(n,1),t.srcObject=null,t.remove(),this.elementMap.delete(e),this.elementStateMap.delete(e)}reuseTrackId(e,t){if(e===t)return;const n=this.elementMap.get(e);if(!n)return;this.elementMap.has(t)&&this.stop(t),this.elementMap.delete(e),this.elementMap.set(t,n);const i=this.elementStateMap.get(e);this.elementStateMap.delete(e),void 0!==i&&this.elementStateMap.set(t,i);const r=this.sinkIdMap.get(e);void 0!==r&&(this.sinkIdMap.delete(e),this.sinkIdMap.set(t,r));const o=this.elementIdMap.get(n);o&&(o.id=t)}bindAudioElementEvents(e,t){yM.forEach((n=>{t.addEventListener(n,(n=>{var i,r;const o=null!==(i=null===(r=this.elementIdMap.get(t))||void 0===r?void 0:r.id)&&void 0!==i?i:e,s=this.elementStateMap.get(o),a="pause"===n.type?"paused":n.type;if(SL.debug("[".concat(o,"] audio-element-status change ").concat(s," => ").concat(a)),"error"===n.type){const e=null==t?void 0:t.error;e&&SL.error("[".concat(o,"] media error, code: ").concat(e.code,", message: ").concat(e.message))}this.elementStateMap.set(o,a)}))}))}getPlayerState(e){return this.elementStateMap.get(e)||"uninit"}autoResumeAudioElement(){const e=()=>{this.elementsNeedToResume.forEach((e=>{e.play().then((e=>{SL.debug("Auto resume audio element success")})).catch((e=>{SL.warning("Auto resume audio element failed!",e)}))})),this.elementsNeedToResume=[]};new cp((e=>{document.body?e():window.addEventListener("load",(()=>e()))})).then((()=>{RN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0))}))}};function bM(){return function(e,t,n){const i=n.value;return"function"==typeof i&&(n.value=function(){this._isClosed&&new ON(wN.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",SL);for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];const r=i.apply(this,t);return r instanceof cp?new cp(((e,t)=>{r.then(e).catch(t)})):r}),n}}let IM=class extends YN{constructor(e){super(),Hk(this,"name","VideoProcessorDestination"),Hk(this,"ID","0"),Hk(this,"_source",void 0),Hk(this,"videoContext",void 0),Hk(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new ON(wN.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new ON(wN.NOT_SUPPORTED,"VideoProcessor cannot unpipe to any other Processor")}enable(){}disable(){}updateInput(e){if(e.context!==this.videoContext)throw new Error("ProcessorContext passed to VideoTrack.processorDestination doesn't match it's belonging VideoTrack's context.\nProbably you are making pipeline like this:\nvideoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).");e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(Mk.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(Mk.ON_TRACK,void 0)}},AM=class extends YN{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t){super(),Hk(this,"constraintsMap",new Map),Hk(this,"statsRegistry",[]),Hk(this,"usageRegistry",[]),Hk(this,"trackId",void 0),Hk(this,"direction",void 0),Hk(this,"_chained",!1),this.trackId=e,this.direction=t}async getConstraints(){return await dD(this,Uk.REQUEST_CONSTRAINTS)}async requestApplyConstraints(e,t){var n;return SL.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),lD(this,Uk.REQUEST_UPDATE_CONSTRAINTS,Array.from(fp(n=this.constraintsMap).call(n)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return SL.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),lD(this,Uk.REQUEST_UPDATE_CONSTRAINTS,Array.from(fp(t=this.constraintsMap).call(t)))}registerStats(e,t,n){this.statsRegistry.find((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:n})}unregisterStats(e,t){const n=this.statsRegistry.findIndex((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t));-1!==n&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const t of this.statsRegistry){const n=t.processorID,i=t.processorName,r=t.type,o=t.cb;try{const t=o();e.push({processorID:n,processorName:i,type:r,stats:t})}catch(e){SL.error(new ON(wN.UNEXPECTED_ERROR,e.message))}}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const t of this.usageRegistry){const n=t.cb;try{let t=n();t instanceof cp&&(t=await t),e.push(Xk(Xk({},t),{},{direction:this.direction}))}catch(e){SL.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}},wM=class extends YN{constructor(e){super(),Hk(this,"name","AudioProcessorDestination"),Hk(this,"ID","0"),Hk(this,"inputTrack",void 0),Hk(this,"inputNode",void 0),Hk(this,"audioProcessorContext",void 0),Hk(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new ON(wN.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new ON(wN.NOT_SUPPORTED,"AudioProcessor cannot unpipe to any other Processor")}enable(){}disable(){}reset(){this.inputTrack=void 0,this.inputNode=void 0,this.audioProcessorContext.chained=!1,this.emit(Mk.ON_TRACK,void 0),this.emit(Mk.ON_NODE,void 0)}updateInput(e){if(e.context!==this.audioProcessorContext)throw new Error("ProcessorContext passed to AudioTrack.processorDestination doesn't match it's belonging AudioTrack's context.\n        Probably you are making pipeline like this: audioTrack1.pipe(processor).pipe(audioTrack2.processorDestination).");e.track&&this.inputTrack!==e.track&&(this.audioProcessorContext.chained=!0,this.inputTrack=e.track,this.emit(Mk.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(Mk.ON_NODE,this.inputNode))}},OM=class extends YN{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,t,n){super(),Hk(this,"constraintsMap",new Map),Hk(this,"statsRegistry",[]),Hk(this,"audioContext",void 0),Hk(this,"trackId",void 0),Hk(this,"direction",void 0),Hk(this,"usageRegistry",[]),Hk(this,"_chained",!1),this.audioContext=e,this.trackId=t,this.direction=n}async getConstraints(){return dD(this,Uk.REQUEST_CONSTRAINTS)}getAudioContext(){return this.audioContext}async requestApplyConstraints(e,t){var n;return SL.info("processor ".concat(t.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(t,e),lD(this,Uk.REQUEST_UPDATE_CONSTRAINTS,Array.from(fp(n=this.constraintsMap).call(n)))}async requestRevertConstraints(e){var t;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),lD(this,Uk.REQUEST_UPDATE_CONSTRAINTS,Array.from(fp(t=this.constraintsMap).call(t)))}registerStats(e,t,n){this.statsRegistry.find((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t))||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:t,cb:n})}unregisterStats(e,t){const n=this.statsRegistry.findIndex((n=>n.processorID===e.ID&&n.processorName===e.name&&n.type===t));-1!==n&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const t of this.statsRegistry){const n=t.processorID,i=t.processorName,r=t.type,o=t.cb;try{const t=o();e.push({processorID:n,processorName:i,type:r,stats:t})}catch(e){SL.error(new ON(wN.UNEXPECTED_ERROR,e.message))}}return e}registerUsage(e,t){this.usageRegistry.find((t=>t.processorID===e.ID&&t.processorName===e.name))||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:t})}unregisterUsage(e){const t=this.usageRegistry.findIndex((t=>t.processorID===e.ID&&t.processorName===e.name));-1!==t&&this.usageRegistry.splice(t,1)}async gatherUsage(){const e=[];if(!this.chained)return[];for(const t of this.usageRegistry){const n=t.cb;try{let t=n();t instanceof cp&&(t=await t),e.push(Xk(Xk({},t),{},{direction:this.direction}))}catch(e){SL.error("gather extension usage error",e)}}return e}getDirection(){return this.direction}},NM=class extends YN{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),Hk(this,"context",void 0),Hk(this,"processSourceNode",void 0),Hk(this,"outputTrack",void 0),Hk(this,"processedNode",void 0),Hk(this,"clonedTrack",void 0),Hk(this,"outputNode",void 0),this.outputNode=new DM}setVolume(){}createOutputTrack(){throw new ON(wN.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}},DM=class{disconnect(){}connect(){}};function PM(e){return new cp(((t,n)=>{let i=!1;const r=document.createElement("video");r.setAttribute("autoplay",""),r.setAttribute("muted",""),r.muted=!0,r.autoplay=!0,r.setAttribute("playsinline",""),r.setAttribute("style","position: fixed; top: 0; left: 0; width: 1px; height: 1px"),document.body.appendChild(r);const o=eN()?"canplay":"playing";r.addEventListener(o,(()=>{const e=r.videoWidth,n=r.videoHeight;!e&&$O()||(i=!0,r.srcObject=null,r.remove(),t([e,n]))})),r.srcObject=new MediaStream([e]),r.play().catch(UD),setTimeout((()=>{i||(r.srcObject=null,r.remove(),t([r.videoWidth,r.videoHeight]))}),4e3)}))}function LM(e){const t={};e.facingMode&&(t.facingMode=e.facingMode),e.cameraId&&(t.deviceId={exact:e.cameraId});const n=pk(e.encoderConfig);return null!=n.width&&(t.width=n.width),null!=n.height&&(t.height=n.height),!fN()&&n.frameRate&&(t.frameRate=n.frameRate),QO()&&"object"==typeof t.frameRate&&(t.frameRate.max=60),$O()&&(t.frameRate={ideal:30,max:30}),t}function kM(e){const t={};return fN()||(void 0!==e.AGC&&(t.autoGainControl=e.AGC),void 0!==e.AEC&&(t.echoCancellation=e.AEC),void 0!==e.ANS&&(t.noiseSuppression=e.ANS,JO()&&e.ANS&&(t.googHighpassFilter=e.ANS))),t}function MM(e){const t=kM(e);if(e.encoderConfig){const n=fk(e.encoderConfig);t.channelCount=n.stereo?2:1,t.sampleRate=n.sampleRate,t.sampleSize=n.sampleSize}return e.microphoneId&&(t.deviceId={exact:e.microphoneId}),TN()&&(t.sampleRate=void 0),t}const UM=e=>{const t=e._encoderConfig;if(!t)return;const n=e.getMediaStreamTrackSettings(),i=n.frameRate,r=n.width,o=n.height;let s=t.frameRate,a=void 0===s?i:s,c=t.width,d=void 0===c?r:c,l=t.height,u=void 0===l?o:l;if(!a||!d||!u)return;d=GD(d),u=GD(u),a=GD(a);const h=function(e,t,n){const i=200*Math.pow(n/15,.6)*Math.pow(e*t/640/360,.75);return{min:Math.floor(i),max:Math.floor(4*i)}}(d,u,a),p=h.max,_=h.min,E=t||{},m=E.bitrateMax,f=E.bitrateMin,g=E.minDownscaleWidth,S=E.minDownscaleHeight;m||SL.debug("calculate bitrate: [w: ".concat(d,", h: ").concat(u,", fps: ").concat(a,"] => [brMax: ").concat(m,", brMin: ").concat(f,"]"));const T=xP("ENCODER_CONFIG_LIMIT").maxFramerate;return T&&"number"==typeof T&&(a=Math.min(a,T)),{width:d,height:u,frameRate:a,bitrateMax:m||p,bitrateMin:f||_,scaleResolutionDownBy:1,scale:0,minDownscaleWidth:g,minDownscaleHeight:S}},VM=async(e,t,n)=>await(async(e,t,n)=>{const i=function(e){const t=[];for(let n=0;n<e.length;n+=2)t.push(parseInt(e.slice(n,n+2),16));return Uint8Array.from(t)}(HD(""+t+n)).slice(0,16),r=i.slice(0,12),o=await window.crypto.subtle.importKey("raw",i,"AES-GCM",!0,["encrypt"]);return new Uint8Array(await window.crypto.subtle.encrypt({name:"AES-GCM",iv:r},o,e))})(e.buffer,t,n),xM=e=>{const t=document.createElement("canvas");return t.width=2,t.height=2,new cp(((n,i)=>{t.toBlob((async e=>{if(t.remove(),e){const i=await FM(e);n({buffer:i,width:t.width,height:t.height})}else i(new ON(wN.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,1)}))},FM=async e=>{const t=await e.arrayBuffer();return new Uint8Array(t)};var BM,jM,GM,WM,KM,HM,YM,XM,JM,zM,ZM,qM,QM,$M,eU,tU,nU,iU,rU,oU,sU,aU,cU,dU,lU,uU,hU,pU,_U,EU,mU,fU,gU,SU,TU,RU,vU,yU,CU,bU;let IU=(BM=KL({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),jM=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),GM=bM(),WM=zD("LocalAudioTrack","_enabledMutex"),KM=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),HM=bM(),YM=zD("LocalAudioTrack","_enabledMutex"),XM=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),JM=bM(),zM=bM(),ZM=bM(),qM=KL({argsMap:e=>[e.getTrackId()]}),QM=bM(),$M=KL({argsMap:e=>[e.getTrackId()]}),eU=bM(),tU=KL({argsMap:e=>[e.getTrackId()]}),nU=KL({argsMap:(e,t)=>[e.getTrackId(),t.name]}),iU=KL({argsMap:e=>[e.getTrackId()]}),Wk((rU=class extends Zk{get _source(){return this.initWebAudio()}set _source(e){this._trackSource=e}get processorContext(){return this._processorContext||(this._processorContext=this.initProcessor().processorContext),this._processorContext}get processorDestination(){return this._processorDestination||(this._processorDestination=this.initProcessor().processorDestination),this._processorDestination}get isPlaying(){return this._useAudioElement?CM.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(e,t,n,i){super(e,n),Hk(this,"trackMediaType",wk.AUDIO),Hk(this,"_encoderConfig",void 0),Hk(this,"_trackSource",void 0),Hk(this,"metadata",[]),Hk(this,"_enabled",!0),Hk(this,"_volume",100),Hk(this,"_useAudioElement",!0),Hk(this,"_bypassWebAudio",!1),Hk(this,"processor",void 0),Hk(this,"_processorContext",void 0),Hk(this,"_processorDestination",void 0),Hk(this,"_getOriginVolumeLevel",void 0),Hk(this,"_usePipeMode",!1),Hk(this,"_useExtensionMode",!1),Hk(this,"_extensionManager",void 0),this._encoderConfig=t,this._getOriginVolumeLevel=!!i,this._trackSource=new NM,xP("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),xP("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),zO()&&!$k?setTimeout((()=>this.initWebAudio())):this.initWebAudio()}setVolume(e){PN(e,"volume",0,1e3),this._volume=e,this._source.setVolume(e/100),this._useAudioElement&&CM.setVolume(this.getTrackId(),e);try{if(this._bypassWebAudio)return void SL.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,lD(this,Tk.NEED_REPLACE_TRACK,this).then((()=>{SL.debug("[".concat(this.getTrackId(),"] replace web audio track success"))})).catch((e=>{SL.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),e)})))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}async setPlaybackDevice(e){if(!this._useAudioElement||!zL())throw new ON(wN.NOT_SUPPORTED,"your browser does not support setting the audio output device");await CM.setSinkID(this.getTrackId(),e)}async setEnabled(e,t,n){return this._setEnabled(e,t,n)}async _setEnabled(e,t,n){if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(SL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){this._originMediaStreamTrack.enabled=!0;try{n||(this._enabled=!0),await lD(this,Tk.NEED_ENABLE_TRACK,this),SL.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(e," success"))}catch(e){throw n||(this._enabled=!1),SL.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}}else{this._originMediaStreamTrack.enabled=!1,n||(this._enabled=!1);try{await lD(this,Tk.NEED_DISABLE_TRACK,this)}catch(e){throw n||(this._enabled=!0),SL.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}}}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,SL.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await lD(this,Tk.NEED_MUTE_TRACK,this):await lD(this,Tk.NEED_UNMUTE_TRACK,this))}getStats(){bD((()=>{SL.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")}),"localAudioTrackGetStatsWarning");return uD(this,Tk.GET_STATS)||Xk({},Nk)}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Ok.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Ok.ON_AUDIO_BUFFER),this._source.on(Ok.ON_AUDIO_BUFFER,(t=>e(t)))}play(){SL.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(SL.debug("[".concat(this.getTrackId(),"] start audio playback in element")),CM.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){SL.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?CM.stop(this.getTrackId()):this._source.stop()}close(){super.close(),this._processorDestination&&this.unbindProcessorDestinationEvents(this._processorDestination),this._processorContext&&this.unbindProcessorContextEvents(this._processorContext),this.unpipe(),this._processorDestination&&this._processorDestination._source&&this._processorDestination._source.unpipe(),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),this._source.destroy()}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];SL.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&CM.updateTrack(this.getTrackId(),this._mediaStreamTrack)}async _updateOriginMediaStreamTrack(e,t){this._originMediaStreamTrack!==e&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),t&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:e,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await lD(this,Tk.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(e))}renewMediaStreamTrack(e){return cp.resolve(void 0)}_ensureExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createAudioExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,lD(this,Tk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,lD(this,Tk.NEED_REPLACE_TRACK,this))}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new ON(wN.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&SL.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}addReferenceTrack(e){if(!this._extensionManager)throw new ON(wN.INVALID_OPERATION,"Call useExtension() before addReferenceTrack().");this._extensionManager.addReferenceTrack(e),SL.info("[".concat(this.getTrackId(),"] addReferenceTrack"))}removeReferenceTrack(e){return!!this._extensionManager&&this._extensionManager.removeReferenceTrack(e)}pipe(e){if(this._useExtensionMode)throw new ON(wN.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this._bypassWebAudio)throw new ON(wN.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===e)return e;if(e._source)throw new ON(wN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,this._usePipeMode=!1,t.reset()}bindProcessorDestinationEvents(e){e.on(Mk.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),await lD(this,Tk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await lD(this,Tk.NEED_REPLACE_TRACK,this))})),e.on(Mk.ON_NODE,(e=>{this._source.processedNode=e}))}unbindProcessorDestinationEvents(e){e.removeAllListeners(Mk.ON_TRACK),e.removeAllListeners(Mk.ON_NODE)}bindProcessorContextEvents(e){e.on(Uk.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(e){e.removeAllListeners(Uk.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof NM&&(this._trackSource=new aM(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const e=new OM(this._source.context,this.getTrackId(),"local"),t=new wM(e);return this._processorContext=e,this._processorDestination=t,this.bindProcessorContextEvents(e),this.bindProcessorDestinationEvents(t),this._source.on(Ok.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:e})})),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(CM.stop(this.getTrackId()),this._source.play()),lD(this,Tk.NEED_REPLACE_MIXING_TRACK,this).then((()=>{SL.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))})).catch((e=>{SL.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),e)}))),{processorContext:e,processorDestination:t}}}).prototype,"setVolume",[BM],Object.getOwnPropertyDescriptor(rU.prototype,"setVolume"),rU.prototype),Wk(rU.prototype,"setPlaybackDevice",[jM,GM],Object.getOwnPropertyDescriptor(rU.prototype,"setPlaybackDevice"),rU.prototype),Wk(rU.prototype,"setEnabled",[WM,KM,HM],Object.getOwnPropertyDescriptor(rU.prototype,"setEnabled"),rU.prototype),Wk(rU.prototype,"setMuted",[YM,XM,JM],Object.getOwnPropertyDescriptor(rU.prototype,"setMuted"),rU.prototype),Wk(rU.prototype,"getStats",[zM],Object.getOwnPropertyDescriptor(rU.prototype,"getStats"),rU.prototype),Wk(rU.prototype,"setAudioFrameCallback",[ZM],Object.getOwnPropertyDescriptor(rU.prototype,"setAudioFrameCallback"),rU.prototype),Wk(rU.prototype,"play",[qM,QM],Object.getOwnPropertyDescriptor(rU.prototype,"play"),rU.prototype),Wk(rU.prototype,"stop",[$M,eU],Object.getOwnPropertyDescriptor(rU.prototype,"stop"),rU.prototype),Wk(rU.prototype,"close",[tU],Object.getOwnPropertyDescriptor(rU.prototype,"close"),rU.prototype),Wk(rU.prototype,"pipe",[nU],Object.getOwnPropertyDescriptor(rU.prototype,"pipe"),rU.prototype),Wk(rU.prototype,"unpipe",[iU],Object.getOwnPropertyDescriptor(rU.prototype,"unpipe"),rU.prototype),rU),AU=(oU=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),sU=bM(),aU=zD("MicrophoneAudioTrack","_enabledMutex"),cU=KL({argsMap:(e,t,n)=>[e.getTrackId(),t,n]}),dU=bM(),lU=KL({argsMap:e=>[e.getTrackId()]}),Wk((uU=class extends IU{get __className__(){return"MicrophoneAudioTrack"}constructor(e,t,n,i){super(e,t.encoderConfig?fk(t.encoderConfig):{},i,xP("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),Hk(this,"_config",void 0),Hk(this,"_deviceName","default"),Hk(this,"_constraints",void 0),Hk(this,"_originalConstraints",void 0),Hk(this,"_enabled",!0),this._config=t,this._constraints=n,this._originalConstraints=n,this._deviceName=e.label,"boolean"==typeof t.bypassWebAudio&&(this._bypassWebAudio=t.bypassWebAudio),(hN()||pN())&&eM.bindInterruptDetectorTrack(this)}async setDevice(e){if(SL.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const t=await gM.getDeviceById(e),n={};n.audio=Xk({},this._constraints),n.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let i=null;try{i=await _M(n,this.getTrackId())}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),i=await _M({audio:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(i.getAudioTracks()[0],!1),this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await gM.getDeviceById(e);this._deviceName=t.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}SL.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))}async setEnabled(e,t,n){if(t)return SL.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),await super._setEnabled(e);if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(SL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),xP("AUTO_RESET_AUDIO_ROUTE")&&(eN()||EN())){const t=navigator.audioSession;t&&(e||(t.type="playback"),t.type="auto")}if(!e){var i;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),null===(i=this._source.clonedTrack)||void 0===i||i.stop(),n||(this._enabled=!1);try{await lD(this,Tk.NEED_DISABLE_TRACK,this)}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setEnabled false failed"),e.toString()),e}return}const r=Xk({},this._constraints),o=gM.searchDeviceIdByName(this._deviceName);o&&!r.deviceId&&(r.deviceId=o);try{n||(this._enabled=!0);const e=await _M({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!1),await lD(this,Tk.NEED_ENABLE_TRACK,this)}catch(e){throw n||(this._enabled=!1),SL.error("[".concat(this.getTrackId(),"] setEnabled true failed"),e.toString()),e}SL.info("[".concat(this.getTrackId(),"] setEnabled success"))}close(){super.close(),(hN()||pN())&&eM.unbindInterruptDetectorTrack(this),gk.some((e=>function(e){return"__className__"in e&&"MicrophoneAudioTrack"===e.__className__}(e)))||Qk&&Qk()&&(HL.reportApiInvoke(null,{name:"BG_AUDIO_TAG_RESTART",options:{},tag:ZN.TRACER}).onSuccess(),SL.debug("restart background audio tag success"))}onTrackEnded(){if((eN()||EN())&&this._enabled&&!this._isClosed&&eM.duringInterruption){const e=async()=>{eM.off(ok.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(SL.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};eM.on(ok.IOS_INTERRUPTION_END,e)}else SL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ik.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,n=gM.searchDeviceIdByName(this._deviceName);if(n&&!t.deviceId&&(t.deviceId=n),this._constraints=t,this._enabled){this._originMediaStreamTrack.stop();const e=await _M({audio:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getAudioTracks()[0],!0)}}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(Uk.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,n)=>{try{const n=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(n),t()}catch(e){n(e)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(Uk.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[oU,sU],Object.getOwnPropertyDescriptor(uU.prototype,"setDevice"),uU.prototype),Wk(uU.prototype,"setEnabled",[aU,cU,dU],Object.getOwnPropertyDescriptor(uU.prototype,"setEnabled"),uU.prototype),Wk(uU.prototype,"close",[lU],Object.getOwnPropertyDescriptor(uU.prototype,"close"),uU.prototype),uU),wU=(hU=KL({argsMap:(e,t)=>[e.getTrackId(),t,e.duration]}),pU=bM(),_U=KL({argsMap:e=>[e.getTrackId()]}),EU=bM(),mU=KL({argsMap:e=>[e.getTrackId()]}),fU=bM(),gU=KL({argsMap:e=>[e.getTrackId()]}),SU=bM(),TU=KL({argsMap:e=>[e.getTrackId()]}),RU=bM(),vU=KL({argsMap:e=>[e.getTrackId()]}),yU=KL({argsMap:e=>[e.getTrackId()]}),CU=bM(),Wk((bU=class extends IU{get __className__(){return"BufferSourceAudioTrack"}constructor(e,t,n,i){super(t.createOutputTrack(),n,i),Hk(this,"source",void 0),Hk(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=e,this._bufferSource=t,this._bufferSource.on(Ok.AUDIO_SOURCE_STATE_CHANGE,(e=>{this.safeEmit(Ik.SOURCE_STATE_CHANGE,e)}));try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(e){e&&this._bufferSource.updateOptions(e),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(e){this._bufferSource.seekAudioBuffer(e)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(e){PN(e,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(e)}}).prototype,"startProcessAudioBuffer",[hU,pU],Object.getOwnPropertyDescriptor(bU.prototype,"startProcessAudioBuffer"),bU.prototype),Wk(bU.prototype,"pauseProcessAudioBuffer",[_U,EU],Object.getOwnPropertyDescriptor(bU.prototype,"pauseProcessAudioBuffer"),bU.prototype),Wk(bU.prototype,"seekAudioBuffer",[mU,fU],Object.getOwnPropertyDescriptor(bU.prototype,"seekAudioBuffer"),bU.prototype),Wk(bU.prototype,"resumeProcessAudioBuffer",[gU,SU],Object.getOwnPropertyDescriptor(bU.prototype,"resumeProcessAudioBuffer"),bU.prototype),Wk(bU.prototype,"stopProcessAudioBuffer",[TU,RU],Object.getOwnPropertyDescriptor(bU.prototype,"stopProcessAudioBuffer"),bU.prototype),Wk(bU.prototype,"close",[vU],Object.getOwnPropertyDescriptor(bU.prototype,"close"),bU.prototype),Wk(bU.prototype,"setAudioBufferPlaybackSpeed",[yU,CU],Object.getOwnPropertyDescriptor(bU.prototype,"setAudioBufferPlaybackSpeed"),bU.prototype),bU),OU=class e extends IU{get __className__(){return"MixingAudioTrack"}get isActive(){for(const e of this.trackList)if(e._enabled&&!e._isClosed&&!e.muted)return!0;return!1}constructor(){const e=tM().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,kD(8,"track-mix-")),Hk(this,"trackList",void 0),Hk(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(e){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return-1!==this.trackList.indexOf(e)}addAudioTrack(e){-1===this.trackList.indexOf(e)?(SL.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):SL.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(-1!==this.trackList.indexOf(e)){SL.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(e){}SD(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach((t=>{t._encoderConfig&&((t._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=t._encoderConfig.bitrate),(t._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=t._encoderConfig.sampleRate),(t._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=t._encoderConfig.sampleSize),t._encoderConfig.stereo&&(e.stereo=!0))})),this._encoderConfig=e}_updateRtpTransceiver(t){this._rtpTransceiver!==t&&(this._rtpTransceiver=t,this.trackList.forEach((n=>{n instanceof e?n.emit(bk.TRANSCEIVER_UPDATED,t):n._updateRtpTransceiver(t)})))}},NU=class extends sM{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(Ok.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Hk(this,"audioBuffer",void 0),Hk(this,"sourceNode",void 0),Hk(this,"startPlayTime",0),Hk(this,"startPlayOffset",0),Hk(this,"pausePlayTime",0),Hk(this,"options",void 0),Hk(this,"currentLoopCount",0),Hk(this,"currentPlaybackSpeed",100),Hk(this,"_currentState","stopped"),this.audioBuffer=e,this.options=t,this.startPlayOffset=this.options.startPlayTime||0}createWebAudioDiagram(){return this.context.createGain()}get duration(){return this.audioBuffer?this.audioBuffer.duration:0}get playbackSpeed(){return this.currentPlaybackSpeed}get currentTime(){return this.audioBuffer?"stopped"===this.currentState?0:"paused"===this.currentState?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){"stopped"===this.currentState?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):SL.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&"playing"===this.currentState&&(this.pausePlayTime=this.currentTime,this.sourceNode.onended=null,this.sourceNode.stop(),this.sourceNode.buffer=null,this.sourceNode=this.createSourceNode(),this.currentState="paused")}seekAudioBuffer(e){this.sourceNode&&(this.sourceNode.onended=null,"playing"===this.currentState&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),"playing"===this.currentState?(this.startPlayOffset=e,this.startSourceNode()):"paused"===this.currentState&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){"paused"===this.currentState&&this.sourceNode&&(this.startPlayOffset=this.pausePlayTime,this.pausePlayTime=0,this.startSourceNode(),this.currentState="playing")}stopProcessAudioBuffer(){if(this.sourceNode){this.sourceNode.onended=null;try{this.sourceNode.stop()}catch(e){}this.reset()}}destroy(){this.audioBuffer=null,super.destroy()}setAudioBufferPlaybackSpeed(e){this.sourceNode&&("playing"===this.currentState&&(this.startPlayOffset=this.currentTime,this.startPlayTime=this.context.currentTime),this.sourceNode.playbackRate.value=e/100),this.currentPlaybackSpeed=e}startSourceNode(){this.sourceNode&&this.sourceNode.buffer&&(this.sourceNode.start(0,this.startPlayOffset),this.startPlayTime=this.context.currentTime,this.sourceNode.onended=this.handleSourceNodeEnded.bind(this))}createSourceNode(){const e=this.context.createBufferSource();return e.buffer=this.audioBuffer,e.loop=!!this.options.loop,e.connect(this.outputNode),e.playbackRate.value=this.currentPlaybackSpeed/100,e}handleSourceNodeEnded(){if(this.currentLoopCount+=1,this.options.cycle&&this.options.cycle>this.currentLoopCount)return this.startPlayOffset=0,this.sourceNode=void 0,void this.startProcessAudioBuffer();this.reset()}reset(){this.startPlayOffset=this.options.startPlayTime||0,this.currentState="stopped",this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=void 0),this.currentLoopCount=0}};const DU=new Map;function PU(e,t){if(0===e.length||0===t.length)return 1/0;const n=KD(e),i=KD(t);return Math.floor(i/n)}let LU=class{get rendFrameRate(){const e=Math.max(1,PU(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._isInPage?this._videoElementStatus:Fk.DESTROYED}set videoElementStatus(e){e!==this._videoElementStatus&&(SL.debug("[".concat(this.trackId,"] video-element-status change ").concat(this._videoElementStatus," => ").concat(e)),this._videoElementStatus=e)}get videoState(){return this._videoState}set videoState(e){var t;e!==this._videoState&&(this._videoState=e,null===(t=this.onVideoStateChanged)||void 0===t||t.call(this,this.videoState))}constructor(e){Hk(this,"trackId",void 0),Hk(this,"config",void 0),Hk(this,"onFirstVideoFrameDecoded",void 0),Hk(this,"onFirstVideoFrameRender",void 0),Hk(this,"onVideoBufferReady",void 0),Hk(this,"onVideoStateChanged",void 0),Hk(this,"freezeTimeCounterList",[]),Hk(this,"renderFreezeAccTime",0),Hk(this,"renderFreezeAccTime2",0),Hk(this,"totalFreezeTime",0),Hk(this,"isKeepLastFrame",!1),Hk(this,"isDestroyed",!1),Hk(this,"timeUpdatedCount",0),Hk(this,"freezeTime",0),Hk(this,"playbackTime",0),Hk(this,"lastTimeUpdatedTime",0),Hk(this,"autoplayFailed",!1),Hk(this,"videoTrack",void 0),Hk(this,"videoElement",void 0),Hk(this,"cacheVideoElement",void 0),Hk(this,"cancelRVFId",void 0),Hk(this,"internal",!1),Hk(this,"_render_interframe_delays",[]),Hk(this,"_render_interframe_delays_sizes",[]),Hk(this,"_videoState",Bk.VideoStateStopped),Hk(this,"videoElementCheckInterval",void 0),Hk(this,"videoElementFreezeTimeout",void 0),Hk(this,"_videoElementStatus",Fk.NONE),Hk(this,"_isInPage",!0),Hk(this,"isGettingVideoDimensions",!1),Hk(this,"startGetVideoDimensions",(()=>{const e=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return SL.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(e,500)};!this.isGettingVideoDimensions&&e()})),Hk(this,"autoResumeAfterInterruption",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&"running"===eM.curState&&(SL.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(HO())),_N()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),Hk(this,"handleVideoEvents",(e=>{switch(e.type){case"play":case"playing":"play"===e.type&&SL.debug("[".concat(this.trackId,"] video element status: play")),this.startGetVideoDimensions(),this.videoElementStatus=Fk.PLAYING;break;case"loadeddata":if(this.videoState=Bk.VideoStateStarting,this.onFirstVideoFrameRender&&this.onFirstVideoFrameRender(),this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(e){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=Fk.CANPLAY;break;case"stalled":this.videoElementStatus=Fk.STALLED;break;case"suspend":this.videoElementStatus=Fk.SUSPEND;break;case"pause":this.videoElementStatus=Fk.PAUSED,eN()||EN()||zO()&&this.autoplayFailed||!this.videoTrack||"live"!==this.videoTrack.readyState||(SL.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=Fk.WAITING;break;case"abort":this.videoElementStatus=Fk.ABORT;break;case"ended":this.videoElementStatus=Fk.ENDED;break;case"emptied":this.videoElementStatus=Fk.EMPTIED;break;case"error":{const e=this.videoElement.error;e&&(this.videoElementStatus=Fk.ERROR,SL.error("[".concat(this.trackId,"] media error: ").concat(e.message," (").concat(e.code,")")));break}case"timeupdate":{const e=performance.now();if(this.timeUpdatedCount+=1,this.onVideoBufferReady&&this.timeUpdatedCount>xP("BUFFER_READY_FRAMES")&&this.onVideoBufferReady(),this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=e);const t=e-this.lastTimeUpdatedTime,n=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=e,BV.lastVisibleTime<BV.lastHiddenTime||n<BV.lastHiddenTime||n<BV.lastVisibleTime)return;if(this.isSkipCalcRenderFreezeTime())return;for(t>xP("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=t),this.playbackTime+=t;this.playbackTime>=6e3;){this.playbackTime-=6e3;const e=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(e),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}})),Hk(this,"autoResumeAfterInterruptionOnIOS15_16",(()=>{this.videoTrack&&"live"===this.videoTrack.readyState&&(SL.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(HO())),_N()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))})),this.trackId=e.trackId,this.config=e,e.element instanceof HTMLVideoElement?this.videoElement=e.element:this.videoElement=document.createElement("video"),eM.on(ok.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),eM.on(ok.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return null!==(e=this.videoElement.parentElement)&&void 0!==e?e:void 0}updateConfig(e){this.config=e,this.trackId=e.trackId,e.element!==this.videoElement&&(this.destroy(),this.videoElement=e.element),this.videoTrack&&this.initVideoElement()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.initVideoElement())}play(e){const t=this.videoElement.play();t&&t.catch&&t.catch((t=>{e&&vM(e,"video",t.message,this.trackId),"NotAllowedError"===t.name?(SL.warning("detected video element autoplay failed",t),this.autoplayFailed=!0,this.handleAutoPlayFailed()):SL.warning("[".concat(this.trackId,"] play warning: "),t)}));const n=GO();if(("Safari"===n.name&&15===Number(n.version)||hN())&&t&&t.then){const e=()=>{this.config.mirror&&!this.config.noStyle&&(this.videoElement.style.transform="rotateY(180deg)")};t.then(e).catch(e)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const t=e.getContext("2d");if(!t)return SL.error("create canvas context failed!"),new ImageData(2,2);t.drawImage(this.videoElement,0,0,e.width,e.height);const n=t.getImageData(0,0,e.width,e.height);return e.remove(),n}async getCurrentFrameToUint8Array(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;const n=document.createElement("canvas");n.width=this.videoElement.videoWidth,n.height=this.videoElement.videoHeight;const i=n.getContext("2d");return i?(i.drawImage(this.videoElement,0,0,n.width,n.height),new cp(((i,r)=>{n.toBlob((async e=>{if(n.remove(),e){const t=await FM(e);i({buffer:t,width:n.width,height:n.height})}else r(new ON(wN.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,t<0?.1:t>1?1:t)}))):await xM(e)}destroy(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.isDestroyed=!0,eM.off(ok.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),eM.off(ok.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),e?this.videoElement.pause():this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=Bk.VideoStateStopped}initVideoElement(){if(this._videoElementStatus!==Fk.NONE&&this._videoElementStatus!==Fk.DESTROYED||(this.videoElementStatus=Fk.INIT),!this.videoElementCheckInterval&&(kU.forEach((e=>{this.videoElement.addEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval=window.setInterval((()=>{this._isInPage=function(e){return e!==document.body&&document.body.contains(e)}(this.videoElement)}),1e3),xP("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,t;let n;const i=()=>{"visible"===document.visibilityState&&(document.removeEventListener("visibilitychange",i),this.videoElementFreezeTimeout=window.setTimeout(r,xP("VIDEO_FREEZE_DURATION")))},r=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===Bk.VideoStateDecoding&&("visible"===document.visibilityState?this.videoState=Bk.VideoStateFrozen:document.addEventListener("visibilitychange",i))},o=(e,t)=>{if(this.videoElementStatus===Fk.PLAYING){if(n){const e=t.presentationTime-n.presentationTime,i=t.presentedFrames-n.presentedFrames;this._render_interframe_delays_sizes.push(i),this._render_interframe_delays.push(e);const o=KD(this._render_interframe_delays_sizes),s=o-this._render_interframe_delays_sizes[0];if(o>30&&s>5&&(this._render_interframe_delays_sizes.shift(),this._render_interframe_delays.shift()),this.videoState===Bk.VideoStateStarting&&(this.videoState=Bk.VideoStateDecoding),this.videoState===Bk.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(r,xP("VIDEO_FREEZE_DURATION"))),e<xP("VIDEO_FREEZE_DURATION")&&this.videoState===Bk.VideoStateFrozen&&(this.videoState=Bk.VideoStateDecoding),e>xP("VIDEO_FREEZE_DURATION")&&BV.lastVisibleTime>=BV.lastHiddenTime&&n.timestamp>BV.lastVisibleTime&&n.timestamp>BV.lastHiddenTime){const t=Math.min(66,PU(this._render_interframe_delays_sizes,this._render_interframe_delays)),n=Math.max(0,e-(i-1)*t),r=n>t?n:0;this.renderFreezeAccTime2+=r,this.totalFreezeTime+=r,this.renderFreezeAccTime+=e}}n=Xk(Xk({},t),{},{timestamp:e})}else this.isSkipCalcRenderFreezeTime()&&(n=Xk(Xk({},t),{},{timestamp:e}));var i,s;xP("ENABLE_VIDEO_FRAME_CALLBACK")&&(this.cancelRVFId=null===(i=(s=this.videoElement).requestVideoFrameCallback)||void 0===i?void 0:i.call(s,o))};this.cancelRVFId=null===(e=(t=this.videoElement).requestVideoFrameCallback)||void 0===e?void 0:e.call(t,o)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),TN()&&!xP("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const n=GO();this.config.noStyle||("Safari"===n.name&&15===Number(n.version)||hN()||!this.config.mirror||(this.videoElement.style.transform="rotateY(180deg)"),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover"),this.videoElement.setAttribute("muted",""),this.videoElement.muted=!0,this.videoElement.srcObject&&this.videoElement.srcObject instanceof MediaStream?this.videoElement.srcObject.getVideoTracks()[0]!==this.videoTrack&&(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,$O()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,$O()&&this.videoElement.load());const i=this.videoElement.play();void 0!==i&&i.catch((e=>{SL.debug("[".concat(this.trackId,"] playback interrupted"),e.toString())}))}resetVideoElement(){var e,t;kU.forEach((e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)})),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.cancelRVFId&&this.videoElement&&(null===(e=(t=this.videoElement).cancelVideoFrameCallback)||void 0===e||e.call(t,this.cancelRVFId),this.cancelRVFId=void 0),this.videoElementStatus=Fk.NONE}isSkipCalcRenderFreezeTime(){return this.videoElementStatus===Fk.DESTROYED||this.internal}handleAutoPlayFailed(){const e=t=>{t.preventDefault(),this.videoElement.play().then((()=>{SL.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))})).catch((e=>{SL.error(e)})),this.autoplayFailed=!1,RN()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};RN()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),RM()}};const kU=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];let MU=class extends LU{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];super(e),Hk(this,"container",void 0),Hk(this,"slot",void 0),this.slot=e.element,this.internal=t,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const t=e.element;var n;!this.internal||this.slot?(t!==this.slot&&(this.destroy(),this.slot=t),this.createElements()):(this.slot=t,t&&this.container?(this.internal=!1,this.container.id="agora-video-player-".concat(this.trackId),this.videoElement.id="video_".concat(this.trackId),this.config.fit?this.videoElement.style.objectFit=this.config.fit:this.videoElement.style.objectFit="cover",null===(n=this.slot)||void 0===n||n.appendChild(this.container)):this.createElements())}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var t;null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameToUint8Array(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return null!==(t=this.container)&&void 0!==t&&t.contains(this.videoElement)?await super.getCurrentFrameToUint8Array(e,n):await xM(e)}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{var e;this.container.remove(),null===(e=this.slot)||void 0===e||e.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){var e;this.container||(this.container=document.createElement("div")),this.container.id="agora-video-player-".concat(this.trackId),this.container.style.width="100%",this.container.style.height="100%",this.container.style.position="relative",this.container.style.overflow="hidden",this.videoTrack?(this.container.style.backgroundColor="black",xP("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),null===(e=this.slot)||void 0===e||e.appendChild(this.container)}mountedVideoElement(){var e;!this.container||null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)||this.container.appendChild(this.videoElement),super.initVideoElement(),this.videoElement.id="video_".concat(this.trackId),this.videoElement.className="agora_video_player",this.videoElement.style.width="100%",this.videoElement.style.height="100%",this.videoElement.style.position="absolute",this.videoElement.style.left="0",this.videoElement.style.top="0"}unmountedVideoElement(){var e;if(null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(e){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;null!==(e=this.container)&&void 0!==e&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}};var UU,VU,xU,FU,BU,jU,GU,WU,KU,HU,YU,XU,JU,zU,ZU,qU,QU,$U,eV,tV,nV,iV,rV,oV,sV,aV,cV,dV,lV,uV,hV,pV,_V,EV,mV,fV,gV,SV;let TV=(UU=KL({argsMap:(e,t,n)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",n]}),VU=bM(),xU=KL({argsMap:e=>[e.getTrackId()]}),FU=zD("LocalVideoTrack","_enabledMutex"),BU=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),jU=bM(),GU=zD("LocalVideoTrack","_enabledMutex"),WU=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),KU=bM(),HU=KL({argsMap:(e,t)=>[e.getTrackId(),t,e._saveEncodeBitrateRatio]}),YU=bM(),XU=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),JU=bM(),zU=bM(),ZU=KL({argsMap:(e,t,n)=>[e.getTrackId(),t,n]}),qU=bM(),QU=bM(),$U=bM(),eV=KL({argsMap:e=>[e.getTrackId()]}),tV=bM(),nV=bM(),iV=bM(),rV=bM(),oV=bM(),sV=KL({argsMap:(e,t)=>[e.getTrackId(),t.name]}),aV=KL({argsMap:e=>[e.getTrackId()]}),cV=KL({argsMap:e=>[e.getTrackId()]}),dV=KL({argsMap:(e,t,n)=>[e.getTrackId(),t.label,n]}),lV=class e extends Zk{get videoHeight(){if(zO()){const e=this._mediaStreamTrack.getSettings().height;return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(zO()){const e=this._mediaStreamTrack.getSettings().width;return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==Fk.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,t,n,i,r,o){if(super(e,r),Hk(this,"trackMediaType",wk.VIDEO),Hk(this,"_player",void 0),Hk(this,"isUseScaleResolutionDownBy",!1),Hk(this,"_videoVisibleTimer",null),Hk(this,"_previousVideoVisibleStatus",void 0),Hk(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),Hk(this,"_encoderConfig",void 0),Hk(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),Hk(this,"_optimizationMode",void 0),Hk(this,"_saveEncodeBitrateRatio",1),Hk(this,"_videoHeight",void 0),Hk(this,"_videoWidth",void 0),Hk(this,"_forceBitrateLimit",void 0),Hk(this,"_enabled",!0),Hk(this,"_processorDestination",void 0),Hk(this,"_processorContext",void 0),Hk(this,"_usePipeMode",!1),Hk(this,"_useExtensionMode",!1),Hk(this,"_extensionManager",void 0),zO()){const t=e.getSettings(),n=t.width,i=t.height;this._videoWidth=n,this._videoHeight=i}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=n,this._optimizationMode=i,this._hints=o||[],t&&-1!==this._hints.indexOf(Rk.CUSTOM_TRACK)?this._encoderConfig=vD(t):this._encoderConfig=t,-1===this._hints.indexOf(Rk.SCREEN_TRACK))this.updateBitrateFromProfile();else if(iN(xO.CHROME,115)&&-1!==KO().indexOf("Windows")){const t=function(e,t){if("VideoFrame"in window&&"TransformStream"in window&&JL().supportWebRTCInsertableStream){const n=new MediaStreamTrackProcessor(e),i=new MediaStreamTrackGenerator({kind:"video"});let r,o,s=Date.now();const a=()=>{c&&(clearInterval(c),c=void 0),r&&(r.close(),r=void 0),e.stop(),o=void 0,i.removeEventListener("ended",a)};let c=window.setInterval((()=>{if(o&&r&&Date.now()-s>(null!=t?t:1e3))try{"live"===i.readyState?o.enqueue(r.clone()):a()}catch(e){a()}}),null!=t?t:1e3);const d=new TransformStream({transform:(e,t)=>{"live"===i.readyState?(o=t,s=Date.now(),void 0===r?(r=e,t.enqueue(e.clone())):(t.enqueue(r),r=e)):e.close()}});return i.addEventListener("ended",a),n.readable.pipeThrough(d).pipeTo(i.writable),i}}(e);t&&(SL.info("local screen video track begin to inject frame"),this._mediaStreamTrack=t)}t&&-1!==this._hints.indexOf(Rk.CUSTOM_TRACK)&&this.setEncoderConfiguration(t),this._processorContext=new AM(this.getTrackId(),"local"),this._processorDestination=new IM(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("string"==typeof e){const t=document.getElementById(e);t?e=t:(SL.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}SL.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const n=Xk(Xk(Xk({},this._getDefaultPlayerConfig()),t),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(n):(e instanceof HTMLVideoElement?this._player=new LU(n):this._player=new MU(n),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Ik.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),xP("CHECK_VIDEO_VISIBLE_INTERVAL"))}stop(){this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(),this._player=void 0,SL.debug("[".concat(this.getTrackId(),"] stop video playback")))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(SL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{await lD(this,Tk.NEED_DISABLE_TRACK,this)}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}return t||(this._enabled=!1),void SL.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{await lD(this,Tk.NEED_ENABLE_TRACK,this)}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setEnabled to true error"),e.toString()),e}SL.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}async setMuted(e){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,SL.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?await lD(this,Tk.NEED_MUTE_TRACK,this):await lD(this,Tk.NEED_UNMUTE_TRACK,this))}async setSaveEncodeBitrateRatio(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this._saveEncodeBitrateRatio;if(1!==this._saveEncodeBitrateRatio&&this._encoderConfig&&this._encoderConfig.bitrateMax&&this._encoderConfig.bitrateMin){this._encoderConfig.bitrateMin=Math.floor(this._encoderConfig.bitrateMin*e),this._encoderConfig.bitrateMax=Math.floor(this._encoderConfig.bitrateMax*e),SL.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{await lD(this,Tk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(SL)}}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new ON(wN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=pk(e),xP("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),e.width||e.height||e.frameRate){const t=LM({encoderConfig:e});(zO()||eN()||EN())&&(t.deviceId=void 0),SL.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(t));try{await this._originMediaStreamTrack.applyConstraints(t),this.updateMediaStreamTrackResolution()}catch(e){const t=new ON(wN.UNEXPECTED_ERROR,e.toString());throw SL.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}}this._encoderConfig=e,-1===this._hints.indexOf(Rk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await lD(this,Tk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(SL)}}getStats(){bD((()=>{SL.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")}),"localVideoTrackGetStatsWarning");return uD(this,Tk.GET_STATS)||Xk({},Dk)}async setBeautyEffect(e){SL.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}async getCurrentFrameImage(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,t):await xM(e)}async findClosestProfile(){const e=this.getMediaStreamTrackSettings(),t=e.width,n=e.height,i=e.frameRate,r=this._encoderConfig||{},o=r.width,s=r.height,a=r.frameRate,c=GD(this._videoWidth||t||o||0),d=GD(this._videoHeight||n||s||0),l=function(e,t,n){if(!Array.isArray(xP("VIDEO_ENCODER_CONFIG_LIST")))return!1;if(0===xP("VIDEO_ENCODER_CONFIG_LIST").length)return!1;const i=Math.min(e,t);return!(i>=480)&&Xk(Xk({},xP("VIDEO_ENCODER_CONFIG_LIST").find((e=>e.height>i))),{},{frameRate:n})}(c,d,GD(i||a||15));if(l)return SL.debug("[".concat(this.getTrackId(),"] find closest profile, ").concat(c,"x").concat(d," => ").concat(JSON.stringify(l))),this.setEncoderConfiguration(l)}async setBitrateLimit(e){SL.debug("[".concat(this.getTrackId(),"] set bitrate limit, ").concat(JSON.stringify(e))),e&&(this._forceBitrateLimit=e,this._encoderConfig&&(this._encoderConfig.bitrateMax?this._encoderConfig.bitrateMax=this._encoderConfig.bitrateMax<e.max_bitrate?this._encoderConfig.bitrateMax:e.max_bitrate:this._encoderConfig.bitrateMax=e.max_bitrate,this._encoderConfig.bitrateMin,this._encoderConfig.bitrateMin=e.min_bitrate))}async setOptimizationMode(e){if("motion"!==e&&"detail"!==e&&"balanced"!==e)return void SL.error(wN.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const t=this._optimizationMode;try{this._optimizationMode=e,await lD(this,Tk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(e){throw this._optimizationMode=t,SL.error("[".concat(this.getTrackId(),"] set optimization mode failed"),e.toString()),e}SL.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))}setScalabiltyMode(e){if(1===e.numSpatialLayers&&1!==e.numTemporalLayers)return SL.error(wN.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,SL.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){PM(this._originMediaStreamTrack).then((e=>{let t=Jk(e,2),n=t[0],i=t[1];this._videoHeight=i,this._videoWidth=n})).catch(UD)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}async setSenderConfiguration(e){if(!this._enabled)throw new ON(wN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");SL.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=pk(e),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate?this._forceBitrateLimit.max_bitrate:e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate?this._forceBitrateLimit.min_bitrate:e.bitrateMin),this._encoderConfig=e,-1===this._hints.indexOf(Rk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await lD(this,Tk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(SL)}}updateBitrateFromProfile(){if(!this._encoderConfig)return;const e=this.getMediaStreamTrackSettings(),t=e.width,n=e.height,i=e.frameRate;if(!t||!n||!i)return;const r=this._encoderConfig,o=r.bitrateMax,s=r.bitrateMin;if(null==s||null==o){const e=function(e,t,n,i,r){const o=xP("BITRATE_ADAPTER_TYPE");if("DEFAULT_BITRATE"===o)return{min:i,max:r};if(void 0===r){const s=Math.floor(200*Math.pow(n/15,.6)*Math.pow(e*t/640/360,.75));r="STANDARD_BITRATE"===o?4*s:2*s,i=null!=i?i:s}else i=null!=i?i:Math.floor(r/10);return{min:i,max:r}}(t,n,i,s,o),r=e.max,a=e.min;if(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=r,xP("VIDEO_STANDARD_BITRATE_VERSION")&&null==s&&null==o){const e=Jk(function(e,t,n){const i=4*Math.floor(2e5*Math.pow(n/15,.6)*Math.pow(e*t/230400,.75)),r=e*t,o=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),s=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]);let a=fp(o).call(o).next().value,c=1;if(o.has(r))a=o.get(r);else{var d;const e=t_(d=Array.from(o.entries())).call(d,((e,t)=>Jk(e,1)[0]-Jk(t,1)[0])),t=e.find((e=>Jk(e,1)[0]>r));if(t){const n=e.indexOf(t);if(n>0){const i=e[n-1],o=(r-i[0])/(t[0]-i[0]);a=i[1]+o*(t[1]-i[1])}else a=t[1]}else a=e[e.length-1][1]}if(s.has(r))c=s.get(r);else{var l;const e=t_(l=Array.from(s.entries())).call(l,((e,t)=>Jk(e,1)[0]-Jk(t,1)[0])),t=e.find((e=>Jk(e,1)[0]>r));if(t){const n=e.indexOf(t);if(n>0){const i=e[n-1],o=(r-i[0])/(t[0]-i[0]);c=i[1]+o*(t[1]-i[1])}else c=t[1]}else c=e[e.length-1][1]}const u=xP("VIDEO_NEW_BITRATE_RATIO");u&&u>0&&(a=u/100);const h=Math.floor(i*a),p=Math.floor(65e4*Math.pow(e*t/230400,.5)*Math.pow(n/15,.69));let _=h;const E=xP("VIDEO_STANDARD_BITRATE_VERSION");return E&&E>0&&(1===E?_=i:2===E?_=h:3===E&&(_=p)),[Math.floor(_/1e3),c]}(t,n,i),2),r=e[0],o=e[1];this._encoderConfig.bitrateMax=r,this._encoderConfig.bitrateMin=a?Math.min(a,r):r,this._saveEncodeBitrateRatio=o,SL.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(t,", h: ").concat(n,", fps: ").concat(i,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else SL.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(t,", h: ").concat(n,", fps: ").concat(i,"] => [brMax: ").concat(r,", brMin: ").concat(a,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var e,t;const n=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),i={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==n?void 0:n.parentElement},r=i.element,o=i.slot;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=GN.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=HL.reportApiInvoke(null,{tag:ZN.TRACER,name:zN.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new ON(wN.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}async renewMediaStreamTrack(e){}_ensureVideoExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createVideoExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),lD(this,Tk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),lD(this,Tk.NEED_REPLACE_TRACK,this))},this._extensionManager.onEmpty=()=>{this._useExtensionMode=!1,this._extensionManager=void 0}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new ON(wN.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureVideoExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&SL.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}pipe(e){if(this._useExtensionMode)throw new ON(wN.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this.processor===e)return e;if(e._source)throw new ON(wN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,this._usePipeMode=!1,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe(),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1)}clone(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;t&&(i=Xk(Xk({},i),pk(t))),i=yD(i);const r=kD(8,"track-video-cloned-"),o=new e(n?this._mediaStreamTrack.clone():this._mediaStreamTrack,i,yD(this._scalabilityMode),this._optimizationMode,r,yD(this._hints));return t&&i&&o.setEncoderConfiguration(i),SL.debug("clone video track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(n)),o}async replaceTrack(e,t){if(!(e instanceof MediaStreamTrack))throw new ON(wN.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if("video"!==e.kind)throw new ON(wN.INVALID_PARAMS,"track should be a video MediaStreamTrack");await this._updateOriginMediaStreamTrack(e,t,!0),this.updateMediaStreamTrackResolution()}sendSeiData(e){if(bD((()=>{HL.reportApiInvoke(null,{name:zN.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:ZN.TRACER}).onSuccess("")}),this._mediaStreamTrack.id||this.getTrackId()),!xP("ENABLE_VIDEO_SEI")||!xP("ENABLE_ENCODED_TRANSFORM"))return void SL.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new ON(wN.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const t=this.getRTCRtpTransceiver();if(!t)return void SL.warning("Video track is not published, SEI can not be send");const n=t.sender.getParameters();if(0===n.codecs.length)return;const i=n.codecs[0].mimeType.toLocaleLowerCase();"video/h264"===i||"video/h265"===i?this.safeEmit("sei-to-send",e):SL.warning("SEI is not supported by ".concat(i))}bindProcessorDestinationEvents(){this.processorDestination.on(Mk.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),await lD(this,Tk.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),await lD(this,Tk.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Mk.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(Uk.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(Uk.REQUEST_CONSTRAINTS)}},Wk(lV.prototype,"play",[UU,VU],Object.getOwnPropertyDescriptor(lV.prototype,"play"),lV.prototype),Wk(lV.prototype,"stop",[xU],Object.getOwnPropertyDescriptor(lV.prototype,"stop"),lV.prototype),Wk(lV.prototype,"setEnabled",[FU,BU,jU],Object.getOwnPropertyDescriptor(lV.prototype,"setEnabled"),lV.prototype),Wk(lV.prototype,"setMuted",[GU,WU,KU],Object.getOwnPropertyDescriptor(lV.prototype,"setMuted"),lV.prototype),Wk(lV.prototype,"setSaveEncodeBitrateRatio",[HU,YU],Object.getOwnPropertyDescriptor(lV.prototype,"setSaveEncodeBitrateRatio"),lV.prototype),Wk(lV.prototype,"setEncoderConfiguration",[XU,JU],Object.getOwnPropertyDescriptor(lV.prototype,"setEncoderConfiguration"),lV.prototype),Wk(lV.prototype,"getStats",[zU],Object.getOwnPropertyDescriptor(lV.prototype,"getStats"),lV.prototype),Wk(lV.prototype,"setBeautyEffect",[ZU,qU],Object.getOwnPropertyDescriptor(lV.prototype,"setBeautyEffect"),lV.prototype),Wk(lV.prototype,"getCurrentFrameData",[QU],Object.getOwnPropertyDescriptor(lV.prototype,"getCurrentFrameData"),lV.prototype),Wk(lV.prototype,"getCurrentFrameImage",[$U],Object.getOwnPropertyDescriptor(lV.prototype,"getCurrentFrameImage"),lV.prototype),Wk(lV.prototype,"findClosestProfile",[eV,tV],Object.getOwnPropertyDescriptor(lV.prototype,"findClosestProfile"),lV.prototype),Wk(lV.prototype,"setBitrateLimit",[nV],Object.getOwnPropertyDescriptor(lV.prototype,"setBitrateLimit"),lV.prototype),Wk(lV.prototype,"setOptimizationMode",[iV],Object.getOwnPropertyDescriptor(lV.prototype,"setOptimizationMode"),lV.prototype),Wk(lV.prototype,"setScalabiltyMode",[rV],Object.getOwnPropertyDescriptor(lV.prototype,"setScalabiltyMode"),lV.prototype),Wk(lV.prototype,"updateMediaStreamTrackResolution",[oV],Object.getOwnPropertyDescriptor(lV.prototype,"updateMediaStreamTrackResolution"),lV.prototype),Wk(lV.prototype,"pipe",[sV],Object.getOwnPropertyDescriptor(lV.prototype,"pipe"),lV.prototype),Wk(lV.prototype,"unpipe",[aV],Object.getOwnPropertyDescriptor(lV.prototype,"unpipe"),lV.prototype),Wk(lV.prototype,"close",[cV],Object.getOwnPropertyDescriptor(lV.prototype,"close"),lV.prototype),Wk(lV.prototype,"replaceTrack",[dV],Object.getOwnPropertyDescriptor(lV.prototype,"replaceTrack"),lV.prototype),lV),RV=(uV=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),hV=bM(),pV=zD("CameraVideoTrack","_enabledMutex"),_V=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),EV=bM(),mV=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),fV=bM(),gV=KL({argsMap:e=>[e.getTrackId()]}),SV=class e extends TV{get __className__(){return"CameraVideoTrack"}constructor(e,t,n,i,r,o){super(e,pk(t.encoderConfig),i,r,o),Hk(this,"_config",void 0),Hk(this,"_originalConstraints",void 0),Hk(this,"_constraints",void 0),Hk(this,"_enabled",!0),Hk(this,"_deviceName","default"),Hk(this,"tryResumeVideoForIOS15_16WeChat",(async()=>{(hN()||pN())&&!function(){const e=GO();if(e.os!==VO.IOS||!e.osVersion)return!1;const t=e.osVersion.split(".");return 15===Number(t[0])&&Number(t[1])>=2}()&&mN()&&this._enabled&&!this._isClosed&&(SL.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),await this.renewMediaStreamTrack())})),this._config=t,this._originalConstraints=n,this._constraints=n,this._deviceName=e.label,this._encoderConfig=pk(this._config.encoderConfig),eM.on(ok.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),eM.on(ok.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}async setDevice(e){return"string"==typeof e?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0}async _setDeviceById(e){if(SL.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const t=await gM.getDeviceById(e),n={};n.video=Xk({},this._constraints),n.video.deviceId={exact:e},n.video.facingMode=void 0,this._originMediaStreamTrack.stop();let i=null;try{i=await _M(n,this.getTrackId())}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setDevice failed"),e.toString()),i=await _M({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1),e}await this._updateOriginMediaStreamTrack(i.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}else try{const t=await gM.getDeviceById(e);this._deviceName=t.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setDevice error"),e.toString()),e}SL.info("[".concat(this.getTrackId(),"] setDevice success"))}async _setDeviceByFacingModel(e){SL.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const t={video:Xk(Xk({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let e=null;try{e=await _M(t,this.getTrackId())}catch(t){throw SL.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),t.toString()),e=await _M({video:this._constraints},this.getTrackId()),await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),t}await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=Xk({},t.video),SL.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))}async setEnabled(e,t){if(!t){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(SL.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const e=await _M({video:this._constraints},this.getTrackId());await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!1)}await lD(this,Tk.NEED_ENABLE_TRACK,this)}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setEnabled true error"),e.toString()),e}this.updateMediaStreamTrackResolution(),SL.info("[".concat(this.getTrackId(),"] setEnabled to true success")),t||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),t||(this._enabled=!1);try{await lD(this,Tk.NEED_DISABLE_TRACK,this)}catch(e){throw SL.error("[".concat(this.getTrackId(),"] setEnabled to false error"),e.toString()),e}SL.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}}async setEncoderConfiguration(e,t){if(!this._enabled)throw new ON(wN.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=pk(e),xP("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin),this._forceBitrateLimit&&(e.bitrateMax=this._forceBitrateLimit.max_bitrate||e.bitrateMax,e.bitrateMin=this._forceBitrateLimit.min_bitrate||e.bitrateMin);const n=vD(this._config);n.encoderConfig=e;const i=LM(n);(zO()||eN()||EN())&&(i.deviceId=void 0),SL.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(i));try{await this._originMediaStreamTrack.applyConstraints(i),this.updateMediaStreamTrackResolution()}catch(e){const t=new ON(wN.UNEXPECTED_ERROR,e.toString());throw SL.error("[".concat(this.getTrackId(),"] applyConstraints error"),t.toString()),t}this._config=n,this._constraints=i,this._originalConstraints=i,this._encoderConfig=e,-1===this._hints.indexOf(Rk.SCREEN_TRACK)&&this.updateBitrateFromProfile();try{await lD(this,Tk.NEED_UPDATE_VIDEO_ENCODER,this)}catch(e){return e.throw(SL)}}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((eN()||EN())&&this._enabled&&!this._isClosed&&eM.duringInterruption){const e=async()=>{eM.off(ok.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(SL.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),await this.setEnabled(!1),await this.setEnabled(!0))};eM.on(ok.IOS_INTERRUPTION_END,e)}else SL.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(Ik.TRACK_ENDED)}async renewMediaStreamTrack(e){const t=e||this._constraints,n=gM.searchDeviceIdByName(this._deviceName);if(n&&!t.deviceId&&(t.deviceId={exact:n}),this._enabled){const e=await _M({video:t},this.getTrackId());this._constraints=t,await this._updateOriginMediaStreamTrack(e.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}}close(){super.close(),eM.off(ok.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),eM.off(ok.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],i=this._encoderConfig;t&&(i=Xk(Xk({},i),pk(t))),i=yD(i);const r=kD(8,"track-cam-cloned-"),o=new e(n?this._mediaStreamTrack.clone():this._mediaStreamTrack,yD(Xk(Xk({},this._config),{},{encoderConfig:i})),yD(this._constraints),yD(this._scalabilityMode),this._optimizationMode,r);return t&&i&&o.setEncoderConfiguration(i),SL.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(n)),o}bindProcessorContextEvents(){this.processorContext.on(Uk.REQUEST_UPDATE_CONSTRAINTS,(async(e,t,n)=>{try{const n=Object.assign({},this._originalConstraints,...e);await this.renewMediaStreamTrack(n),t()}catch(e){n(e)}})),this.processorContext.on(Uk.REQUEST_CONSTRAINTS,(async e=>{e(this._originMediaStreamTrack.getSettings())}))}},Wk(SV.prototype,"setDevice",[uV,hV],Object.getOwnPropertyDescriptor(SV.prototype,"setDevice"),SV.prototype),Wk(SV.prototype,"setEnabled",[pV,_V,EV],Object.getOwnPropertyDescriptor(SV.prototype,"setEnabled"),SV.prototype),Wk(SV.prototype,"setEncoderConfiguration",[mV,fV],Object.getOwnPropertyDescriptor(SV.prototype,"setEncoderConfiguration"),SV.prototype),Wk(SV.prototype,"close",[gV],Object.getOwnPropertyDescriptor(SV.prototype,"close"),SV.prototype),SV);function vV(e){const t=kD(8,"track-cus-"),n=HL.reportApiInvoke(null,{id:t,tag:ZN.TRACER,name:zN.CREATE_CUSTOM_AUDIO_TRACK,options:[e]}),i=new IU(e.mediaStreamTrack,e.encoderConfig?fk(e.encoderConfig):{},t,!1);return SL.info("create custom audio track success with config",e,"trackId",i.getTrackId()),n.onSuccess(i.getTrackId()),i}function yV(e,t,n,i){n.optimizationMode&&(i&&i.width&&i.height?(n.encoderConfig=Xk(Xk({},i),{},{bitrateMin:i.bitrateMin,bitrateMax:i.bitrateMax}),"motion"!==n.optimizationMode&&"detail"!==n.optimizationMode||(t.contentHint=n.optimizationMode,t.contentHint===n.optimizationMode?SL.debug("[".concat(e,"] set content hint to"),n.optimizationMode):SL.debug("[".concat(e,"] set content hint failed")))):SL.warning("[".concat(e,"] can not apply optimization mode bitrate config, no encoderConfig")))}var CV,bV,IV,AV,wV,OV,NV,DV,PV,LV,kV,MV,UV;let VV=class extends zk{getUserId(){return this._userId}constructor(e,t,n,i){super(e,"track-".concat(e.kind,"-").concat(t,"-").concat(i.clientId,"_").concat(kD(5,""))),Hk(this,"_userId",void 0),Hk(this,"_uintId",void 0),Hk(this,"_isDestroyed",!1),Hk(this,"store",void 0),Hk(this,"processor",void 0),Hk(this,"processorContext",void 0),this._userId=t,this._uintId=n,this.store=i}_updateOriginMediaStreamTrack(e){this._originMediaStreamTrack=e,this._mediaStreamTrack=e,this._updatePlayerSource(),this.processor&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this.processorContext})}_destroy(){this._isDestroyed=!0,SL.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}},xV=(CV=KL({argsMap:(e,t,n)=>[e.getTrackId(),"string"==typeof t?t:t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",n]}),bV=KL({argsMap:e=>[e.getTrackId()]}),IV=KL({argsMap:(e,t)=>[e.getTrackId(),t.name]}),AV=KL({argsMap:e=>[e.getTrackId()]}),Wk((wV=class extends VV{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==Fk.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(e,t,n,i,r){super(e,t,n,i),Hk(this,"_videoVisibleTimer",null),Hk(this,"_previousVideoVisibleStatus",void 0),Hk(this,"_clearPreviousVideoVisibleStatus",(()=>this._previousVideoVisibleStatus=void 0)),Hk(this,"trackMediaType",wk.VIDEO),Hk(this,"_videoWidth",void 0),Hk(this,"_videoHeight",void 0),Hk(this,"_player",void 0),Hk(this,"_prePlayer",void 0),Hk(this,"processorDestination",void 0),Hk(this,"processorContext",void 0),Hk(this,"_usePipeMode",!1),Hk(this,"_useExtensionMode",!1),Hk(this,"_extensionManager",void 0),this._prePlayer=r,this.updateMediaStreamTrackResolution(),this.processorContext=new AM(this.getTrackId(),"remote"),this.processorDestination=new IM(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return bD((()=>{SL.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")}),"remoteVideoTrackGetStatsWarning"),uD(this,Tk.GET_STATS)||Xk({},kk)}play(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(this.safeEmit(Ak.PLAY_START),"string"==typeof e){const t=document.getElementById(e);t?e=t:(SL.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}SL.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(t));const n=Xk(Xk({fit:"cover"},t),{},{trackId:this.getTrackId(),element:e});if(this._player)this._player.updateConfig(n);else{let t=!1,i=!1;const r=this._prePlayer&&!this._prePlayer.isDestroyed&&e===this._prePlayer.config.element;this._prePlayer&&!r&&(this._prePlayer.destroy(),i=!0),r?(this._player=this._prePlayer,t=this._player.videoState>0,this._player.updateConfig(n)):this._player=e instanceof HTMLVideoElement?new LU(n):new MU(n),this._prePlayer=void 0,this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(Ak.FIRST_FRAME_DECODED),i&&this.safeEmit(Ak.FIRST_FRAME_RENDER)},this._player.onVideoStateChanged=e=>{this.safeEmit(Ak.VIDEO_STATE_CHANGED,e)},t&&(this._player.onFirstVideoFrameDecoded(),this._player.onVideoStateChanged(this._player.videoState))}this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval((()=>{try{const e=this.getVideoElementVisibleStatus();this.safeEmit(Ak.VIDEO_ELEMENT_VISIBLE_STATUS,e)}catch(e){}}),xP("CHECK_VIDEO_VISIBLE_INTERVAL")),this.safeEmit(Ak.PLAY_END)}stop(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._player&&(this._videoVisibleTimer&&(window.clearInterval(this._videoVisibleTimer),this._videoVisibleTimer=null),this._clearPreviousVideoVisibleStatus(),this._player.destroy(e),this._player=void 0,SL.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){PM(this._originMediaStreamTrack).then((e=>{let t=Jk(e,2),n=t[0],i=t[1];this._videoHeight=i,this._videoWidth=n})).catch(UD)}_updatePlayerSource(){SL.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var e,t;const n=null==this||null===(e=this._player)||void 0===e?void 0:e.getContainerElement(),i={track:this,element:null==this||null===(t=this._player)||void 0===t?void 0:t.getVideoElement(),slot:null==n?void 0:n.parentElement},r=i.element,o=i.slot;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const e=GN.checkOneElementVisible(r),t=Object.assign({},e);if(t.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=t.visible;const e=HL.reportApiInvoke(null,{tag:ZN.TRACER,name:zN.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});t.visible?e.onSuccess("Video is visible"):e.onSuccess("Invisible because of ".concat(t.reason))}return t}return}catch(e){throw new ON(wN.GET_VIDEO_ELEMENT_VISIBLE_ERROR,e.message)}}_ensureVideoExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createVideoExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())},this._extensionManager.onEmpty=()=>{this._useExtensionMode=!1,this._extensionManager=void 0}),this._extensionManager}useExtension(e,t){if(this._usePipeMode)throw new ON(wN.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureVideoExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e,t)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&SL.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}pipe(e){if(this._useExtensionMode)throw new ON(wN.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active. Call removeExtension() for all extensions first.");if(this.processor===e)return e;if(e._source)throw new ON(wN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),e}unpipe(){if(!this.processor)return;const e=this.processor;this.processor._source=void 0,this.processor=void 0,this._usePipeMode=!1,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Mk.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Mk.ON_TRACK)}_destroy(){this._prePlayer&&(this._prePlayer.destroy(),this._prePlayer=void 0),this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(e,t){this.emit(bk.SEI_RECEIVED,e,t)}}).prototype,"play",[CV],Object.getOwnPropertyDescriptor(wV.prototype,"play"),wV.prototype),Wk(wV.prototype,"stop",[bV],Object.getOwnPropertyDescriptor(wV.prototype,"stop"),wV.prototype),Wk(wV.prototype,"pipe",[IV],Object.getOwnPropertyDescriptor(wV.prototype,"pipe"),wV.prototype),Wk(wV.prototype,"unpipe",[AV],Object.getOwnPropertyDescriptor(wV.prototype,"unpipe"),wV.prototype),wV),FV=(OV=KL({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),NV=KL({argsMap:(e,t)=>[e.getTrackId(),t],throttleTime:300}),DV=KL({argsMap:(e,t)=>[e.getTrackId(),t]}),PV=KL({argsMap:e=>[e.getTrackId()]}),LV=KL({argsMap:e=>[e.getTrackId()]}),kV=KL({argsMap:(e,t)=>[e.getTrackId(),t.name]}),MV=KL({argsMap:e=>[e.getTrackId()]}),Wk((UV=class extends VV{get isPlaying(){return this._useAudioElement?CM.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(e,t,n,i){super(e,t,n,i),Hk(this,"trackMediaType",wk.AUDIO),Hk(this,"_source",void 0),Hk(this,"_useAudioElement",!0),Hk(this,"_volume",100),Hk(this,"processorContext",void 0),Hk(this,"processorDestination",void 0),Hk(this,"_usePipeMode",!1),Hk(this,"_useExtensionMode",!1),Hk(this,"_extensionManager",void 0),Hk(this,"_played",!1),Hk(this,"_bypassWebAudio",!1),xP("DISABLE_WEBAUDIO")?(this._source=new NM,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new aM(e,!0),xP("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(Ok.RECEIVE_TRACK_BUFFER,(()=>{this.safeEmit(Ak.FIRST_FRAME_DECODED)})),this.processorContext=new OM(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new wM(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Ok.UPDATE_SOURCE,(()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})}))}setAudioFrameCallback(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4096;if(!e)return this._source.removeAllListeners(Ok.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(t),this._source.removeAllListeners(Ok.ON_AUDIO_BUFFER),this._source.on(Ok.ON_AUDIO_BUFFER,(t=>e(t)))}setVolume(e){this._volume=e,this._useAudioElement?CM.setVolume(this.getTrackId(),e):this._source.setVolume(e/100)}setAmplifiedVolume(e){this._useAudioElement&&this._played&&(CM.stop(this.getTrackId()),this._source.play()),this._useAudioElement=!1,e=Math.min(e,xP("MAX_WEBAUDIO_VOLUME")),this._volume=e,this._source.setVolume(e/100)}async setPlaybackDevice(e){if(!this._useAudioElement||!zL())throw new ON(wN.NOT_SUPPORTED,"your browser does not support setting the audio output device");await CM.setSinkID(this.getTrackId(),e)}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getVolume(){return this._useAudioElement?CM.getVolume(this.getTrackId()):this._source instanceof aM?this._source.getAudioVolume():0}getStats(){return bD((()=>{SL.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")}),"remoteAudioTrackGetStatsWarning"),uD(this,Tk.GET_STATS)||Xk({},Pk)}play(){if(SL.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement)SL.debug("[".concat(this.getTrackId(),"] use audio element to play")),CM.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0);else{var e;SL.debug("[".concat(this.getTrackId(),"] use audio context to play"));const t=null===(e=this._source.context)||void 0===e?void 0:e.state;t&&"running"!==t&&vM(this.store.sessionId||null,"audio","AudioContext state is ".concat(t),this.getTrackId()),this._source.play()}}stop(){SL.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?CM.stop(this.getTrackId()):this._source.stop()}_reusePreAudioElement(e,t){this._played=t,this._useAudioElement?(CM.reuseTrackId(e,this.getTrackId()),this._updatePlayerSource()):(CM.stop(e),this._updatePlayerSource(),t&&this._source.play()),this.setVolume(this._volume)}_destroy(){super._destroy(),this._played=!1,this._extensionManager&&(this._extensionManager.destroy(),this._extensionManager=void 0,this._useExtensionMode=!1),this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];SL.debug("[".concat(this.getTrackId(),"] update player source track")),e&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&CM.updateTrack(this.getTrackId(),this._mediaStreamTrack)}_ensureAudioExtensionManager(e){return this._extensionManager||(this._extensionManager=e.createAudioExtensionManager(this),this._extensionManager.onOutputTrackChanged=e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}),this._extensionManager}useExtension(e){if(this._usePipeMode)throw new ON(wN.INVALID_OPERATION,"Cannot use useExtension() when pipe() mode is active. Call unpipe() first.");return this._ensureAudioExtensionManager(e),this._useExtensionMode=!0,this._extensionManager.useExtension(e)}removeExtension(e){if(!this._extensionManager)return!1;const t=this._extensionManager.removeExtension(e);return t&&SL.info("[".concat(this.getTrackId(),"] removeExtension: ").concat(e.name)),this._extensionManager.hasExtensions||(this._useExtensionMode=!1),t}addReferenceTrack(e){if(!this._extensionManager)throw new ON(wN.INVALID_OPERATION,"Call useExtension() before addReferenceTrack().");this._extensionManager.addReferenceTrack(e),SL.info("[".concat(this.getTrackId(),"] addReferenceTrack"))}removeReferenceTrack(e){return!!this._extensionManager&&this._extensionManager.removeReferenceTrack(e)}pipe(e){if(this._useExtensionMode)throw new ON(wN.INVALID_OPERATION,"Cannot use pipe() when useExtension() mode is active.");if(this._bypassWebAudio)throw new ON(wN.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===e)return e;if(e._source)throw new ON(wN.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),this._usePipeMode=!0,this.processor=e,this.processor._source=this,e.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),e}unpipe(){var e;if(this._bypassWebAudio)throw new ON(wN.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const t=this.processor;null===(e=this._source.processSourceNode)||void 0===e||e.disconnect(),this.processor._source=!1,this.processor=void 0,this._usePipeMode=!1,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(Mk.ON_TRACK,(async e=>{e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(Mk.ON_NODE,(e=>{this._source.processedNode=e;const t=!e;this._useAudioElement!==t&&(this._played?(this.stop(),this._useAudioElement=t,this.play()):this._useAudioElement=t)}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(Mk.ON_TRACK),this.processorDestination.removeAllListeners(Mk.ON_NODE)}}).prototype,"setVolume",[OV],Object.getOwnPropertyDescriptor(UV.prototype,"setVolume"),UV.prototype),Wk(UV.prototype,"setAmplifiedVolume",[NV],Object.getOwnPropertyDescriptor(UV.prototype,"setAmplifiedVolume"),UV.prototype),Wk(UV.prototype,"setPlaybackDevice",[DV],Object.getOwnPropertyDescriptor(UV.prototype,"setPlaybackDevice"),UV.prototype),Wk(UV.prototype,"play",[PV],Object.getOwnPropertyDescriptor(UV.prototype,"play"),UV.prototype),Wk(UV.prototype,"stop",[LV],Object.getOwnPropertyDescriptor(UV.prototype,"stop"),UV.prototype),Wk(UV.prototype,"pipe",[kV],Object.getOwnPropertyDescriptor(UV.prototype,"pipe"),UV.prototype),Wk(UV.prototype,"unpipe",[MV],Object.getOwnPropertyDescriptor(UV.prototype,"unpipe"),UV.prototype),UV);const BV=new class extends YN{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),Hk(this,"_lastHiddenTime",0),Hk(this,"_lastVisibleTime",0),Hk(this,"needUploadStats",[]),Hk(this,"isCollectingStats",!1),document.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),this.isCollectingStats&&this.needUploadStats.push("visible"===document.visibilityState?1:0),SL.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)}))}startCollectStats(){this.isCollectingStats=!0,this.needUploadStats.push("visible"===this.visibility?1:0)}stopCollectStats(){this.isCollectingStats=!1,this.needUploadStats.length=0}};let jV=class extends YN{constructor(e,t){super(),Hk(this,"trackMediaType",wk.DATA),Hk(this,"_version",1),Hk(this,"_type",3),Hk(this,"_config",void 0),Hk(this,"_originDataChannel",void 0),Hk(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),Hk(this,"_dataStreamPacketHandler",{serialize:e=>e,deserialize:e=>e}),Hk(this,"_datachannelEventMap",new Map),this._config=e,t&&(this._originDataChannel=t,this._bandDataChannelEvents(t)),this._initPacketHeader()}useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return xP("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.readyState)&&void 0!==e?e:"connecting"}get _originDataChannelId(){var e,t;return null!==(e=null===(t=this._originDataChannel)||void 0===t?void 0:t.id)&&void 0!==e?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}async _waitTillOpen(){return new cp(((e,t)=>{if(this._originDataChannel){"open"===this._originDataChannel.readyState&&e();const n=setTimeout((()=>{var e;t(new ON(wN.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat(null===(e=this._originDataChannel)||void 0===e?void 0:e.id)))}),1e4);this._originDataChannel.onopen=()=>{clearTimeout(n),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(n),new ON(wN.DATACHANNEL_CONNECTION_TIMEOUT)}}else t(new ON(wN.DATACHANNEL_CONNECTION_TIMEOUT,"cannot find dataChannel"))}))}_updateOriginDataChannel(e){this._originDataChannel=e,this._bandDataChannelEvents(e)}_initPacketHeader(){const e=new DataView(this._dataStreamPacketHeader);e.setUint16(0,this._version),e.setUint8(2,this._type),e.setUint8(3,this._config.id)}_bandDataChannelEvents(e){this._unbindDataChannelEvents(e),[Gk.OPEN,Gk.CLOSE,Gk.ERROR].forEach((t=>{const n=()=>{this.emit(t)};this._datachannelEventMap.set(t,n),e.addEventListener(t,n)}))}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach((t=>{let n=Jk(t,2),i=n[0],r=n[1];e.removeEventListener(i,r)})),this._datachannelEventMap.clear()}},GV=class extends jV{constructor(e){super(e),Hk(this,"_messageListener",void 0),this._messageListener=e=>{if(e.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const t=e.data.slice(0,this._dataStreamPacketHeader.byteLength),n=new DataView(t).getUint8(3);if(n!==this.id)return void(xP("SHOW_DATASTREAM2_LOG")&&SL.debug("invalid datachannel id: ".concat(n," !== ").concat(this.id)));let i=e.data.slice(this._dataStreamPacketHeader.byteLength);i=this._dataStreamPacketHandler.deserialize(i),this.emit(Gk.MESSAGE,i)}}_updateDataChannelConfig(e){this._config=e}_updateOriginDataChannel(e){super._updateOriginDataChannel(e),this._bandRemoteDataChannelEvents()}_close(){this._originDataChannel&&(this._originDataChannel.removeEventListener("message",this._messageListener),super._close())}_bandRemoteDataChannelEvents(){this._originDataChannel&&this._originDataChannel.addEventListener("message",this._messageListener)}},WV=class extends jV{send(e){if(this._originDataChannel){let t=e;t=this._dataStreamPacketHandler.serialize(e);const n=new Uint8Array(this._dataStreamPacketHeader.byteLength+t.byteLength);n.set(new Uint8Array(this._dataStreamPacketHeader),0),n.set(new Uint8Array(t),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(n.buffer)}}};function KV(){const e=new Blob([atob("ZnVuY3Rpb24gdCh0LGUsbil7cmV0dXJuKGU9ZnVuY3Rpb24odCl7dmFyIGU9ZnVuY3Rpb24odCxlKXtpZigib2JqZWN0IiE9dHlwZW9mIHR8fCF0KXJldHVybiB0O3ZhciBuPXRbU3ltYm9sLnRvUHJpbWl0aXZlXTtpZih2b2lkIDAhPT1uKXt2YXIgcj1uLmNhbGwodCxlfHwiZGVmYXVsdCIpO2lmKCJvYmplY3QiIT10eXBlb2YgcilyZXR1cm4gcjt0aHJvdyBuZXcgVHlwZUVycm9yKCJAQHRvUHJpbWl0aXZlIG11c3QgcmV0dXJuIGEgcHJpbWl0aXZlIHZhbHVlLiIpfXJldHVybigic3RyaW5nIj09PWU/U3RyaW5nOk51bWJlcikodCl9KHQsInN0cmluZyIpO3JldHVybiJzeW1ib2wiPT10eXBlb2YgZT9lOmUrIiJ9KGUpKWluIHQ/T2JqZWN0LmRlZmluZVByb3BlcnR5KHQsZSx7dmFsdWU6bixlbnVtZXJhYmxlOiEwLGNvbmZpZ3VyYWJsZTohMCx3cml0YWJsZTohMH0pOnRbZV09bix0fWZ1bmN0aW9uIGUodCxlKXt2YXIgbj1PYmplY3Qua2V5cyh0KTtpZihPYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKXt2YXIgcj1PYmplY3QuZ2V0T3duUHJvcGVydHlTeW1ib2xzKHQpO2UmJihyPXIuZmlsdGVyKChmdW5jdGlvbihlKXtyZXR1cm4gT2JqZWN0LmdldE93blByb3BlcnR5RGVzY3JpcHRvcih0LGUpLmVudW1lcmFibGV9KSkpLG4ucHVzaC5hcHBseShuLHIpfXJldHVybiBufWNvbnN0IG49InZpZGVvL2gyNjQiLHI9InZpZGVvL2gyNjUiO2Z1bmN0aW9uIGEodCxlLG4pe2NvbnN0IHI9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLGE9W107bGV0IG89MDtmb3IoO2EubGVuZ3RoPG47KW8rMzxuJiYwPT09cltvXSYmMD09PXJbbysxXSYmMz09PXJbbysyXSYmKDA9PT1yW28rM118fDE9PT1yW28rM118fDI9PT1yW28rM118fDM9PT1yW28rM10pPyhhLnB1c2gocltvXSxyW28rMV0scltvKzNdKSxvKz00KTooYS5wdXNoKHJbb10pLG8rKyk7cmV0dXJuIG5ldyBVaW50OEFycmF5KGEpfWZ1bmN0aW9uIG8odCxlKXtzd2l0Y2goZSl7Y2FzZSBuOnJldHVybiBmdW5jdGlvbih0KXtjb25zdCBlPW5ldyBEYXRhVmlldyh0LmRhdGEpO2xldCBuPTA7Zm9yKDtuKzQ8dC5kYXRhLmJ5dGVMZW5ndGg7KXtpZigwPT09ZS5nZXRVaW50OChuKzApJiYwPT09ZS5nZXRVaW50OChuKzEpJiYwPT09ZS5nZXRVaW50OChuKzIpJiYxPT09ZS5nZXRVaW50OChuKzMpJiY2PT09ZS5nZXRVaW50OChuKzQpKXtsZXQgcj1uKzYsbz0wLGk9MDtmb3IoOzI1NT09PShpPWUuZ2V0VWludDgocisrKSk7KW8rPTI1NTtvKz1pO2NvbnN0IHM9YSh0LmRhdGEscixvKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkocyl9bisrfXJldHVybiBudWxsfSh0KTtjYXNlIHI6cmV0dXJuIGZ1bmN0aW9uKHQpe2NvbnN0IGU9bmV3IERhdGFWaWV3KHQuZGF0YSk7bGV0IG49MDtmb3IoO24rNTx0LmRhdGEuYnl0ZUxlbmd0aDspe2lmKDA9PT1lLmdldFVpbnQ4KG4rMCkmJjA9PT1lLmdldFVpbnQ4KG4rMSkmJjA9PT1lLmdldFVpbnQ4KG4rMikmJjE9PT1lLmdldFVpbnQ4KG4rMykmJjc4PT09ZS5nZXRVaW50OChuKzQpJiYxPT09ZS5nZXRVaW50OChuKzUpJiYxMDE9PT1lLmdldFVpbnQ4KG4rNikpe2xldCByPW4rNyxvPTAsaT0wO2Zvcig7MjU1PT09KGk9ZS5nZXRVaW50OChyKyspKTspbys9MjU1O28rPWk7Y29uc3Qgcz1hKHQuZGF0YSxyLG8pO3JldHVybiBuZXcgVWludDhBcnJheShzKX1uKyt9cmV0dXJuIG51bGx9KHQpO2RlZmF1bHQ6cmV0dXJuIG51bGx9fWZ1bmN0aW9uIGkodCl7Y29uc3QgZT10Lmxlbmd0aCxuPVtdO2xldCByPTA7Zm9yKDtyPGU7KXIrMjxlJiYwPT09dFtyXSYmMD09PXRbcisxXSYmKDA9PT10W3IrMl18fDE9PT10W3IrMl18fDI9PT10W3IrMl18fDM9PT10W3IrMl0pPyhuLnB1c2godFtyXSx0W3IrMV0sMyx0W3IrMl0pLHIrPTMpOihuLnB1c2godFtyXSkscisrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobil9ZnVuY3Rpb24gcyh0LGUsYSl7c3dpdGNoKGEpe2Nhc2UgbjpyZXR1cm4gZnVuY3Rpb24odCxlKXtjb25zdCBuPWkoZSkscj1uLmxlbmd0aCxhPU1hdGguZmxvb3Ioci8yNTUpLG89ciUyNTUscz1uZXcgVWludDhBcnJheSg2K2ErMStyKzErdC5ieXRlTGVuZ3RoKTtzWzBdPTAsc1sxXT0wLHNbMl09MCxzWzNdPTEsc1s0XT02LHNbNV09MTAxO2xldCBmPTA7Zm9yKDtmPGE7KXNbNitmXT0yNTUsZisrO3JldHVybiBzWzYrZl09byxmKysscy5zZXQobiw2K2YpLGYrPXIsc1s2K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNitmKSxzLmJ1ZmZlcn0odCxlKTtjYXNlIHI6cmV0dXJuIGZ1bmN0aW9uKHQsZSl7Y29uc3Qgbj1pKGUpLHI9bi5sZW5ndGgsYT1NYXRoLmZsb29yKHIvMjU1KSxvPXIlMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNythKzErcisxK3QuYnl0ZUxlbmd0aCk7c1swXT0wLHNbMV09MCxzWzJdPTAsc1szXT0xLHNbNF09Nzgsc1s1XT0xLHNbNl09MTAxO2xldCBmPTA7Zm9yKDtmPGE7KXNbNytmXT0yNTUsZisrO3JldHVybiBzWzcrZl09byxmKysscy5zZXQobiw3K2YpLGYrPXIsc1s3K2ZdPTEyOCxmKysscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNytmKSxzLmJ1ZmZlcn0odCxlKTtkZWZhdWx0OnJldHVybiBudWxsfX1mdW5jdGlvbiBmKHQpe2lmKHQubGVuZ3RoPDUpcmV0dXJuIiI7bGV0IGU9LTE7Zm9yKGxldCBuPTA7bjx0Lmxlbmd0aC0zO24rKyl7aWYoMD09PXRbbl0mJjA9PT10W24rMV0mJjE9PT10W24rMl0pe2U9bjticmVha31pZihuPHQubGVuZ3RoLTQmJjA9PT10W25dJiYwPT09dFtuKzFdJiYwPT09dFtuKzJdJiYxPT09dFtuKzNdKXtlPW47YnJlYWt9fWlmKC0xPT09ZSlyZXR1cm4iIjtjb25zdCBhPWUrKDA9PT10W2UrMl0/NDozKTtpZihhPj10Lmxlbmd0aClyZXR1cm4iIjtjb25zdCBvPXRbYV07aWYoMTI4Jm8pcmV0dXJuIiI7aWYoKG8+PjEmNjMpPj0zMilyZXR1cm4gcjtpZihhKzE8dC5sZW5ndGgpe2lmKDA9PSgyNDgmdFthKzFdKSlyZXR1cm4gcn1yZXR1cm4oMzEmbyk8PTMxP246IiJ9Y29uc3QgbD03MSx1PTEsYz0yLGc9MSxwPTI7dmFyIGQ9ZnVuY3Rpb24odCl7cmV0dXJuIHRbdC5BVURJT19MRVZFTD0xXT0iQVVESU9fTEVWRUwiLHRbdC5NRVRBREFUQT0yXT0iTUVUQURBVEEiLHRbdC5BVURJT182NF9CSVRfUFRTPTNdPSJBVURJT182NF9CSVRfUFRTIix0fShkfHx7fSk7ZnVuY3Rpb24gaCh0KXtsZXQgZT1hcmd1bWVudHMubGVuZ3RoPjEmJnZvaWQgMCE9PWFyZ3VtZW50c1sxXSYmYXJndW1lbnRzWzFdO2NvbnN0IG49dC5nZXRVaW50OCgwKTtpZihuIT09bClyZXR1cm47Y29uc3Qgcj10LmdldFVpbnQxNigxKSxhPXUrYytyLG89bmV3IFVpbnQ4QXJyYXkodC5ieXRlTGVuZ3RoLWEpO28uc2V0KG5ldyBVaW50OEFycmF5KHQuYnVmZmVyLGEsdC5ieXRlTGVuZ3RoLWEpKTtjb25zdCBpPXttOm4sdGx2TGVuOnIsdGx2OltdLGZyYW1lOm99O2xldCBzPXUrYztmb3IoO3M8YTspe2NvbnN0IG49dC5nZXRVaW50OChzKSxyPXQuZ2V0VWludDE2KHMrZyksYT1nK3A7aWYobj09PWQuQVVESU9fTEVWRUwpe2xldCBvPXQuZ2V0VWludDgocythKTtmb3IobGV0IGU9MTtlPHI7ZSsrKW89bzw8OHx0LmdldFVpbnQ4KHMrYStlKTtpLnRsdi5wdXNoKHt0YWc6bixsZW5ndGg6cix2YWx1ZTplPzEyN15vPj4xOjEyNyZvfSl9ZWxzZSBpZihuPT09ZC5NRVRBREFUQXx8bj09PWQuQVVESU9fNjRfQklUX1BUUyl7Y29uc3QgZT1uZXcgVWludDhBcnJheShyKTtmb3IobGV0IG49MDtuPHI7bisrKWVbbl09dC5nZXRVaW50OChzK2Erbik7aS50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOnIsdmFsdWU6ZX0pfXMrPWErcn1yZXR1cm4gaX1zZWxmLm9ucnRjdHJhbnNmb3JtPW49Pntjb25zdCByPW4udHJhbnNmb3JtZXIsYT1bXSxpPVtdO2xldCB5PW51bGw7ci5vcHRpb25zLnBvcnQub25tZXNzYWdlPXQ9Pnt0LmRhdGEuc2VpJiZhLnB1c2godC5kYXRhLnNlaSksdC5kYXRhLm1ldGFkYXRhJiZpLnB1c2godC5kYXRhLm1ldGFkYXRhKX0sc2VsZi5wb3N0TWVzc2FnZSgic3RhcnRlZCIpO2NvbnN0IFU9ci5yZWFkYWJsZS5nZXRSZWFkZXIoKSx2PXIud3JpdGFibGUuZ2V0V3JpdGVyKCk7InNlaS1yeCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiBuKHIpe1UucmVhZCgpLnRoZW4oKGE9PntpZighYS5kb25lKXtpZihhLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IG49ZihuZXcgVWludDhBcnJheShhLnZhbHVlLmRhdGEpKSxpPW8oYS52YWx1ZSxuKTtpZihpJiZyLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7c2VpOmkscnRwVGltZXN0YW1wOmEudmFsdWUudGltZXN0YW1wfSksIXkpe2NvbnN0IG49YS52YWx1ZS5nZXRNZXRhZGF0YSgpfHx7fTt5PWZ1bmN0aW9uKG4pe2Zvcih2YXIgcj0xO3I8YXJndW1lbnRzLmxlbmd0aDtyKyspe3ZhciBhPW51bGwhPWFyZ3VtZW50c1tyXT9hcmd1bWVudHNbcl06e307ciUyP2UoT2JqZWN0KGEpLCEwKS5mb3JFYWNoKChmdW5jdGlvbihlKXt0KG4sZSxhW2VdKX0pKTpPYmplY3QuZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9ycz9PYmplY3QuZGVmaW5lUHJvcGVydGllcyhuLE9iamVjdC5nZXRPd25Qcm9wZXJ0eURlc2NyaXB0b3JzKGEpKTplKE9iamVjdChhKSkuZm9yRWFjaCgoZnVuY3Rpb24odCl7T2JqZWN0LmRlZmluZVByb3BlcnR5KG4sdCxPYmplY3QuZ2V0T3duUHJvcGVydHlEZXNjcmlwdG9yKGEsdCkpfSkpfXJldHVybiBufSh7dHlwZTphLnZhbHVlLnR5cGUscnRwVGltZXN0YW1wOmEudmFsdWUudGltZXN0YW1wLHBheWxvYWRUeXBlOm4ucGF5bG9hZFR5cGV8fDAsc3NyYzpuLnN5bmNocm9uaXphdGlvblNvdXJjZXx8MCxsZW5ndGg6YS52YWx1ZS5kYXRhLmJ5dGVMZW5ndGh9LCJtaW1lVHlwZSJpbiBuP3ttaW1lVHlwZTpuLm1pbWVUeXBlfTp7fSksci5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2ZpcnN0RnJhbWVJbmZvOnl9KX19di53cml0ZShhLnZhbHVlKSxyLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxuKHIpfX0pKX0ocik6InNlaS10eCI9PT1yLm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KGUpe1UucmVhZCgpLnRoZW4oKG49PntpZighbi5kb25lKXtpZihuLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZihuZXcgVWludDhBcnJheShuLnZhbHVlLmRhdGEpKSxlPWEuc2hpZnQoKTtpZihlKXtjb25zdCByPXMobi52YWx1ZS5kYXRhLGUsdCk7ciYmKG4udmFsdWUuZGF0YT1yKX19di53cml0ZShuLnZhbHVlKSxlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSx0KGUpfX0pKX0ocik6ImF1ZGlvLW1ldGFkYXRhLXJ4Ij09PXIub3B0aW9ucy5uYW1lP2Z1bmN0aW9uIHQoZSl7VS5yZWFkKCkudGhlbigobj0+e2lmKCFuLmRvbmUpe2lmKG4udmFsdWUgaW5zdGFuY2VvZiBSVENFbmNvZGVkQXVkaW9GcmFtZSl7Y29uc3QgdD1uZXcgRGF0YVZpZXcobi52YWx1ZS5kYXRhKSxyPXQuZ2V0VWludDgoMCk7bGV0IGE7aWYoMCE9KDEyOCZyKSYmNzEhPT1yKXtjb25zdCBlPWZ1bmN0aW9uKHQpe2lmKHQuYnl0ZUxlbmd0aDw9MClyZXR1cm5bXTtjb25zdCBlPVtdO2xldCBuPTA7Zm9yKDtuPHQuYnl0ZUxlbmd0aDspe2NvbnN0IHI9KDEyOCZ0LmdldFVpbnQ4KG4pKT4+NyxhPTEyNyZ0LmdldFVpbnQ4KG4pO2lmKCEociYmbis0PD10LmJ5dGVMZW5ndGgpKXtuKys7YnJlYWt9e2NvbnN0IHI9dC5nZXRVaW50MzIobiwhMSksbz0oMTY3NzYxOTImcik+PjEwLGk9MTAyMyZyO2UucHVzaCh7cHQ6YSx0c19vZmZzZXQ6byxsZW5ndGg6aSxkYXRhOm5ldyBVaW50OEFycmF5fSksbis9NH19bGV0IHI9dC5ieXRlTGVuZ3RoLW47Zm9yKGNvbnN0IGEgb2YgZSl7aWYoYS5sZW5ndGg+cilyZXR1cm4gY29uc29sZS53YXJuKCJCcm9rZW4gcmVkIHBheWxvYWQiKSxbXTthLmxlbmd0aD4wJiYoYS5kYXRhPW5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLGEubGVuZ3RoKSxuKz1hLmxlbmd0aCxyLT1hLmxlbmd0aCl9aWYocj4wKXtjb25zdCBhPXtwdDplLmxlbmd0aD4wP2VbZS5sZW5ndGgtMV0ucHQ6MCx0c19vZmZzZXQ6MCxsZW5ndGg6cixkYXRhOm5ldyBVaW50OEFycmF5KHQuYnVmZmVyLHQuYnl0ZU9mZnNldCtuLHIpfTtlLnB1c2goYSl9cmV0dXJuIGV9KHQpO2lmKGUubGVuZ3RoPjApe2NvbnN0IHQ9ZnVuY3Rpb24odCl7bGV0IGU9MDtmb3IobGV0IG49MDtuPHQubGVuZ3RoO24rKyllKz1uPHQubGVuZ3RoLTE/NDoxLGUrPXRbbl0ubGVuZ3RoO2NvbnN0IG49bmV3IFVpbnQ4QXJyYXkoZSk7bGV0IHI9MDtmb3IobGV0IGU9MDtlPHQubGVuZ3RoO2UrKylpZihlPHQubGVuZ3RoLTEpe2NvbnN0IGE9KDIxNDc0ODM2NDh8KDEyNyZ0W2VdLnB0KTw8MjR8KDI2MjE0MyZ0W2VdLnRzX29mZnNldCk8PDEwfDEwMjMmdFtlXS5sZW5ndGgpPj4+MDtuW3IrK109YT4+MjQmMjU1LG5bcisrXT1hPj4xNiYyNTUsbltyKytdPWE+PjgmMjU1LG5bcisrXT0yNTUmYX1lbHNlIG5bcisrXT0xMjcmdFtlXS5wdDtmb3IoY29uc3QgZSBvZiB0KW4uc2V0KGUuZGF0YSxyKSxyKz1lLmxlbmd0aDtyZXR1cm4gbn0oZS5tYXAoKHQ9Pntjb25zdCBlPW5ldyBVaW50OEFycmF5KHQubGVuZ3RoKTtlLnNldCh0LmRhdGEpO2NvbnN0IG49aChuZXcgRGF0YVZpZXcoZS5idWZmZXIpKTtyZXR1cm4gbnVsbCE9biYmbi5mcmFtZSYmKHQuZGF0YT1udWxsPT1uP3ZvaWQgMDpuLmZyYW1lKSxhPW4sdH0pKSk7bi52YWx1ZS5kYXRhPXQuYnVmZmVyfX1lbHNlIGE9aCh0KSxhJiYobi52YWx1ZS5kYXRhPWEuZnJhbWUuYnVmZmVyKTtpZihhKXtsZXQgdD1hLnRsdi5maW5kKCh0PT50LnRhZz09PWQuTUVUQURBVEEpKTtpZih0JiZ0LnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe21ldGFkYXRhOnQudmFsdWV9KSx0PWEudGx2LmZpbmQoKHQ9PnQudGFnPT09ZC5BVURJT182NF9CSVRfUFRTKSksdCYmdC52YWx1ZSBpbnN0YW5jZW9mIFVpbnQ4QXJyYXkmJjg9PXQudmFsdWUubGVuZ3RoKXtjb25zdCBuPW5ldyBEYXRhVmlldyh0LnZhbHVlLmJ1ZmZlcikuZ2V0QmlnVWludDY0KDAsITApO3QmJnQudmFsdWUgaW5zdGFuY2VvZiBVaW50OEFycmF5JiZlLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7cHRzOm59KX19fXYud3JpdGUobi52YWx1ZSksZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChlKX19KSl9KHIpOiJhdWRpby1tZXRhZGF0YS10eCI9PT1yLm9wdGlvbnMubmFtZSYmZnVuY3Rpb24gdChlKXtVLnJlYWQoKS50aGVuKChuPT57aWYoIW4uZG9uZSl7aWYoZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2dldE1ldGFkYXRhOiEwfSksbi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PWkuc2hpZnQoKTt0JiYobi52YWx1ZS5kYXRhPWZ1bmN0aW9uKHQsZSxuKXtjb25zdCByPW4uYnl0ZUxlbmd0aCxhPXIrZytwLG89dStjK2EsaT1uZXcgQXJyYXlCdWZmZXIodC5ieXRlTGVuZ3RoK28pLHM9bmV3IERhdGFWaWV3KGkpO3Muc2V0VWludDgoMCxsKSxzLnNldFVpbnQxNigxLGEpLHMuc2V0VWludDgoMyxlKSxzLnNldFVpbnQxNig0LHIpO2ZvcihsZXQgdD0wO3Q8cjt0Kyspcy5zZXRVaW50OCg2K3Qsblt0XSk7Y29uc3QgZj1uZXcgVWludDhBcnJheShzLmJ1ZmZlcik7cmV0dXJuIGYuc2V0KG5ldyBVaW50OEFycmF5KHQpLG8pLGYuYnVmZmVyfShuLnZhbHVlLmRhdGEsZC5BVURJT182NF9CSVRfUFRTLHQpKX12LndyaXRlKG4udmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfShyKX0sc2VsZi5wb3N0TWVzc2FnZSgicmVnaXN0ZXJlZCIpOwo=")],{type:"text/javascript"});return setTimeout((()=>xg.revokeObjectURL(e)),0),new Worker(xg.createObjectURL(e))}const HV=71,YV=1,XV=2,JV=1,zV=2;var ZV=function(e){return e[e.AUDIO_LEVEL=1]="AUDIO_LEVEL",e[e.METADATA=2]="METADATA",e[e.AUDIO_64_BIT_PTS=3]="AUDIO_64_BIT_PTS",e}(ZV||{});function qV(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=e.getUint8(0);if(n!==HV)return;const i=e.getUint16(1),r=YV+XV+i,o=new Uint8Array(e.byteLength-r);o.set(new Uint8Array(e.buffer,r,e.byteLength-r));const s={m:n,tlvLen:i,tlv:[],frame:o};let a=YV+XV;for(;a<r;){const n=e.getUint8(a),i=e.getUint16(a+JV),r=JV+zV;if(n===ZV.AUDIO_LEVEL){let o=e.getUint8(a+r);for(let t=1;t<i;t++)o=o<<8|e.getUint8(a+r+t);s.tlv.push({tag:n,length:i,value:t?127^o>>1:127&o})}else if(n===ZV.METADATA||n===ZV.AUDIO_64_BIT_PTS){const t=new Uint8Array(i);for(let n=0;n<i;n++)t[n]=e.getUint8(a+r+n);s.tlv.push({tag:n,length:i,value:t})}a+=r+i}return s}const QV=new Map;const $V=127,ex=1e-10,tx=139/13,nx=new Map;function ix(e,t,n){const i="".concat(e,"-").concat(t,"-").concat(n);let r=0;if(nx.has(i))r=nx.get(i);else{const o=.5;r=Math.log(function(e,t){const n=e-t;t<n&&(t=n);let i=1;for(let n=e,r=1;n>t;n--,r++)i=i*n/r;return i}(t,e))+e*Math.log(o)+(t-e)*Math.log(1-o)-Math.log(n)+n*e,nx.set(i,r)}return r<ex&&(r=ex),r}function rx(e,t,n){const i=t.length,r=e.length/i;let o=!1;for(let s=0,a=0;s<i;s++){let i=0;for(let t=a+r;a<t;a++)e[a]>n&&i++;t[s]!==i&&(t[s]=i,o=!0)}return o}window.cache=nx;let ox=0,sx=class{constructor(e){Hk(this,"id",void 0),Hk(this,"immediates",[]),Hk(this,"lastNonSilence",-1),Hk(this,"immediateSpeechActivityScore",ex),Hk(this,"lastLevelChangedTime",Date.now()),Hk(this,"levels",[]),Hk(this,"longs",[]),Hk(this,"longSpeechActivityScore",ex),Hk(this,"mediums",[]),Hk(this,"mediumSpeechActivityScore",ex),Hk(this,"minLevel",0),Hk(this,"nextMinLevel",0),Hk(this,"nextMinLevelWindowLength",0),Hk(this,"energyScore",0),this.id=e||"".concat(ox++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}computeImmediates(){const e=this.immediates,t=this.levels,n=this.minLevel+tx;let i=!1;for(let r=0;r<e.length;++r){let o=t[r];o<n&&(o=0);const s=Math.floor(o/tx);e[r]!==s&&(e[r]=s,i=!0)}return i}computeLongs(){return rx(this.mediums,this.longs,4)}computeMediums(){return rx(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=ix(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=ix(this.longs[0],10,47),this.longSpeechActivityScore>ex&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=ix(this.mediums[0],5,24)}evaluateSpeechActivityScores(e){this.computeImmediates()&&(this.evaluateImmediateSpeechActivityScore(),this.computeMediums()&&(this.evaluateMediumSpeechActivityScore(),this.computeLongs()&&this.evaluateLongSpeechActivityScore(e)))}getLastLevelChangedTime(){return this.lastLevelChangedTime}getLevels(){var e;return"[".concat(Sr(e=[...this.levels]).call(e).join(),"]")}getSpeechActivityScore(e){switch(e){case 0:return this.immediateSpeechActivityScore;case 1:return this.mediumSpeechActivityScore;case 2:return this.longSpeechActivityScore;default:throw new Error("interval "+e)}}levelChanged(e,t){if(this.lastLevelChangedTime<=t){this.lastLevelChangedTime=t;let n=e;return e<0&&(n=0),e>$V&&(n=$V),this.levels.unshift(n),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(n),n>=this.minLevel+tx?n:n/2}return-1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(0!==e){if(0===this.minLevel||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(0===this.nextMinLevel)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let e=Math.sqrt(this.minLevel*this.nextMinLevel);e<0?e=0:e>$V&&(e=$V),this.minLevel=e,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}},ax=class{constructor(e,t,n){Hk(this,"isDominant",void 0),Hk(this,"energyRanking",void 0),Hk(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=t,this.energyScore=n}},cx=class extends YN{constructor(e){super(),Hk(this,"dominantId",null),Hk(this,"lastDecisionTime",0),Hk(this,"lastLevelChangedTime",0),Hk(this,"lastLevelIdleTime",0),Hk(this,"relativeSpeechActivities",[]),Hk(this,"speakers",new Map),Hk(this,"enableSilence",!1),Hk(this,"timeoutToSilenceInterval",0),Hk(this,"decisionMaker",null),Hk(this,"loudest",[]),Hk(this,"numLoudestToTrack",3),Hk(this,"energyExpireTimeMs",250),Hk(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}setLoudestConfig(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:3,t=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,null!=t&&(this.energyExpireTimeMs=t),null!=n&&(this.energyAlphaPct=n),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some((t=>t.id===e))}levelChanged(e,t){const n=Date.now(),i=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<n&&(this.lastLevelChangedTime=n,this.maybeStartDecisionMaker());const r=i.levelChanged(t,n);return this.updateLoudestList(i,r,n)}runInDecisionMaker(e){return this.decisionMaker!==e||this.lastDecisionTime>0&&this.lastDecisionTime-this.lastLevelChangedTime>=15e3?-1:this._runInDecisionMaker()}decisionMakerExited(e){this.decisionMaker===e&&(this.decisionMaker=null)}destroy(){this.decisionMaker=null,this.loudest.length=0,this.speakers.clear(),this.removeAllListeners()}addSpeakers(e){e.forEach((e=>{this.speakers.has(e.id)||this.speakers.set(e.id,e)}))}removeSpeakers(e){e.forEach((e=>{this.speakers.delete(e.id)}))}getOrCreateSpeaker(e){let t=this.speakers.get(e);return t||(t=new sx(e),this.speakers.set(e,t),this.maybeStartDecisionMaker()),t}updateLoudestList(e,t,n){const i=e.id===this.dominantId;if(t<0){let t=0;for(;t<this.loudest.length&&this.loudest[t]!==e;)++t;return new ax(i,t,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*t+(100-this.energyAlphaPct)*e.energyScore+50)/100),0===this.numLoudestToTrack)return new ax(i,0,e.energyScore);const r=n-this.energyExpireTimeMs;let o=0;for(;o<this.loudest.length;){const t=this.loudest[o];if(t.getLastLevelChangedTime()<r&&this.loudest.length>=this.numLoudestToTrack)this.loudest.splice(o,1);else if(t.id!==e.id)++o;else if(this.loudest.splice(o,1),this.loudest.length<this.numLoudestToTrack)break}let s=0;for(;s<this.loudest.length&&!(this.loudest[s].energyScore<e.energyScore);)++s;return s<this.numLoudestToTrack&&(this.loudest.splice(s,0,e),this.loudest.length>this.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new ax(i,s,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new class{constructor(e){Hk(this,"algorithm",void 0),this.algorithm=e}execute(){let e=!this.algorithm;if(!e)try{const t=this.algorithm.runInDecisionMaker(this);t<=0?e=!0:setTimeout(this.execute.bind(this),t)}catch(t){e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}}(this),this.decisionMaker.execute())}makeDecision(e){let t=null,n=null;const i=this.speakers.size;let r=null;if(0===i)r=null;else if(1===i){var o;const t=fp(o=this.speakers).call(o).next().value;this.enableSilence&&t&&(r=t.id,t.evaluateSpeechActivityScores(e),e-t.lastNonSilence>this.timeoutToSilenceInterval&&(r=null))}else{let t=null==this.dominantId?null:this.speakers.get(this.dominantId);if(null==t){const e=this.speakers.entries().next();e.value&&(r=e.value[0],t=e.value[1])}else r=t.id;null!=t&&t.evaluateSpeechActivityScores(e);const n=this.relativeSpeechActivities;let i=2;for(const o of this.speakers.entries()){const s=Jk(o,2),a=s[0],c=s[1];if(c===t)continue;c.evaluateSpeechActivityScores(e);for(let e=0;e<n.length;++e){const i=null==t?ex:t.getSpeechActivityScore(e);n[e]=Math.log(c.getSpeechActivityScore(e)/i)}const d=n[0],l=n[1],u=n[2];d>3&&l>2&&u>0&&l>i&&(i=l,r=a)}this.enableSilence&&null!=t&&r===t.id&&e-t.lastNonSilence>this.timeoutToSilenceInterval&&(r=null)}null==r&&!this.enableSilence||r===this.dominantId||(t=this.dominantId,this.dominantId=r,n=this.dominantId),null==n&&!this.enableSilence||n===t||this.emit("ActiveSpeakerChanged",n)}_runInDecisionMaker(){const e=Date.now(),t=300-(e-this.lastLevelIdleTime);let n=0;t<=0?(0!==this.lastLevelIdleTime&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):n=t;let i=300-(e-this.lastDecisionTime);return i<=0&&(this.lastDecisionTime=e,this.makeDecision(e),i=300-(Date.now()-e)),i>0&&n>i&&(n=i),n}timeoutIdleLevels(e){const t=[];for(const i of fp(n=this.speakers).call(n)){var n;const r=e-i.getLastLevelChangedTime();36e5<r&&(null==this.dominantId||i.id!==this.dominantId)?t.push(i.id):300<r&&i.levelTimedOut()}t.forEach((e=>this.speakers.delete(e)))}};const dx=new Map;let lx=null,ux=null;const hx=3;let px=[];const _x=new Map,Ex=new Map;let mx,fx=class{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,t){Hk(this,"id",void 0),Hk(this,"track",void 0),Hk(this,"score",0),Hk(this,"active",!0),Hk(this,"muted",!1),Hk(this,"timer",0),Hk(this,"actives",0),Hk(this,"inactives",0),this.id=e,this.track=t,this.setActive(_x.size<3)}autoCheckActive(){this.autoSetActive(),this.autoAdjustActive(),this.resetTimer(),this.actives=0,this.inactives=0}autoSetActive(){const e=this.active;this.active=this.activeRate>=.8;const t=function(){const e=[],t=[];return Array.from(fp(_x).call(_x)).forEach((n=>{n.active?e.push(n):t.push(n)})),{actives:e,inactives:t}}(),n=t.actives,i=t.inactives;if(n.length>3){let e;n.forEach((t=>{(!e||e.score>t.score)&&(e=t)})),e&&e.setActive(!1)}if(n.length<3&&i.length>0){let t;i.forEach((e=>{(!t||t.score<e.score)&&e.id!==this.id&&(t=e)})),t&&e&&!this.active&&(t.samples>40&&t.activeRate-this.activeRate>.4?t.setActive(!0):this.active=!0)}this.setMuted(!this.active)}setActive(e){this.active=e,this.resetTimer(),this.setMuted(!e)}autoAdjustActive(){this.active?this.autoSwitchToInactive():this.autoSwitchToActive()}autoSwitchToActive(){const e=function(e){let t;return Array.from(fp(_x).call(_x)).forEach((n=>{!n.active||n.id===e||n.samples<40||(!t||n.score<t.score)&&(t=n)})),t}(this.id);e&&this.activeRate-e.activeRate>.4&&(e.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){const e=function(e){let t;return Array.from(fp(_x).call(_x)).forEach((n=>{n.active||n.id===e||n.samples<40||(!t||n.score>t.score)&&(t=n)})),t}(this.id);e&&e.activeRate-this.activeRate>.4&&(e.setActive(!0),this.setActive(!1))}addSample(e){e?this.actives+=1:this.inactives+=1,this.samples>66.66666666666667&&this.autoCheckActive()}setMuted(e){this.track&&(this.track.enabled=!e,this.muted=e)}resetTimer(){this.clearTimer(),this.timer=window.setTimeout((()=>{if(0!==this.samples)return this.samples<50?this.resetTimer():void this.autoCheckActive()}),1e3)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}};function gx(e){const t=_x.get(e);t&&(_x.delete(e),t.clearTimer())}const Sx=new Map,Tx=new Map;const Rx="video/h264",vx="video/h265";function yx(e,t,n){const i=new Uint8Array(e,t,n),r=[];let o=0;for(;r.length<n;)o+3<n&&0===i[o]&&0===i[o+1]&&3===i[o+2]&&(0===i[o+3]||1===i[o+3]||2===i[o+3]||3===i[o+3])?(r.push(i[o],i[o+1],i[o+3]),o+=4):(r.push(i[o]),o++);return new Uint8Array(r)}function Cx(e){const t=e.length,n=[];let i=0;for(;i<t;)i+2<t&&0===e[i]&&0===e[i+1]&&(0===e[i+2]||1===e[i+2]||2===e[i+2]||3===e[i+2])?(n.push(e[i],e[i+1],3,e[i+2]),i+=3):(n.push(e[i]),i++);return new Uint8Array(n)}function bx(e){if(e.length<5)return"";let t=-1;for(let n=0;n<e.length-3;n++){if(0===e[n]&&0===e[n+1]&&1===e[n+2]){t=n;break}if(n<e.length-4&&0===e[n]&&0===e[n+1]&&0===e[n+2]&&1===e[n+3]){t=n;break}}if(-1===t)return"";const n=t+(0===e[t+2]?4:3);if(n>=e.length)return"";const i=e[n];return 128&i?"":(i>>1&63)>=32||n+1<e.length&&0==(248&e[n+1])?vx:(31&i)<=31?Rx:""}const Ix=new Map;const Ax=new Map;!function(){const e=GO();XL.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),XL.getStreamFromExtension=e.name===xO.CHROME&&Number(e.version)>34,XL.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver)return!1;if(!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let t=!1;try{e.addTransceiver("audio"),t=!0}catch(e){}return e.close(),t}(),XL.supportMinBitrate=e.name===xO.CHROME||e.name===xO.EDGE,XL.supportSetRtpSenderParameters=function(){const e=GO();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!SN()||!(!zO()&&!YO())||e.name===xO.FIREFOX&&Number(e.version)>=64)}(),e.name===xO.SAFARI&&(Number(e.version)>=14?XL.supportDualStream=!0:XL.supportDualStream=!1),XL.webAudioMediaStreamDest=function(){const e=GO();return!(e.name===xO.SAFARI&&Number(e.version)<12)}(),XL.supportReplaceTrack=!!window.RTCRtpSender&&"function"==typeof RTCRtpSender.prototype.replaceTrack,XL.supportWebGL="undefined"!=typeof WebGLRenderingContext,XL.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,SN()||(XL.webAudioWithAEC=!0),XL.supportShareAudio=function(){const e=GO();return(e.os===VO.WIN_10||e.os===VO.WIN_81||e.os===VO.WIN_7||e.os===VO.LINUX||e.os===VO.MAC_OS||e.os===VO.CHROMIUM_OS)&&e.name===xO.CHROME&&Number(e.version)>=74}(),XL.supportDataChannel=!!(tN(76)||oN(68)||sN(14)),XL.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!$O()&&!!e&&e.prototype.setConfiguration instanceof Function}(),XL.supportWebRTCEncodedTransform=tN(87)||ZO()||oN(117),XL.supportWebRTCInsertableStream=function(){const e=GO();return(e.name===xO.CHROME||e.name===xO.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),XL.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,XL.supportWebCrypto="undefined"!=typeof window&&void 0!==window.crypto&&void 0!==window.crypto.subtle,XL.supportSuppressLocalAudioPlayback=ik(),XL.supportRestrictOwnAudio=rk(),RD((()=>{XL.supportDualStreamEncoding=function(){const e=GO();return!!xP("DISABLE_WEBAUDIO")||("Safari"===e.name&&Number(e.version)>=14||!!("Chrome"===e.name&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&xP("CHROME_DUAL_STREAM_USE_ENCODING")))}(),SL.debug("browser ua: ",navigator.userAgent),SL.info("browser info: ",e),SL.info("browser compatibility: ",XL)}))}();const wx=["CHINA","GLOBAL"];const Ox=[[0,1,2,3,4,5,5],[0,2,2,3,4,5,5],[0,3,3,3,4,5,5],[0,4,4,4,4,5,5],[0,5,5,5,5,5,5]],Nx=[],Dx=[];function Px(e,t){return!!t&&Nx.some((n=>n.uid===e&&n.channelName===t))}function Lx(){return Dx.length>0}var kx=dR.forEach,Mx=Yi("forEach")?[].forEach:function(e){return kx(this,e,arguments.length>1?arguments[1]:void 0)};Nn({target:"Array",proto:!0,forced:[].forEach!==Mx},{forEach:Mx});var Ux=ni("Array","forEach"),Vx=gi,xx=$e,Fx=l,Bx=Ux,jx=Array.prototype,Gx={DOMTokenList:!0,NodeList:!0},Wx=function(e){var t=e.forEach;return e===jx||Fx(jx,e)&&t===jx.forEach||xx(Gx,Vx(e))?Bx:t},Kx=n(Wx),Hx=Ze,Yx=Eo;Nn({target:"Object",stat:!0,forced:i((function(){Yx(1)}))},{keys:function(e){return Yx(Hx(e))}});var Xx=n($.Object.keys),Jx=n(or),zx=n(gr);function Zx(e,t,n,i,r){var o,s,a,c={};return Kx(o=Xx(i)).call(o,(function(e){c[e]=i[e]})),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=Jx(s=zx(a=BC(n).call(n)).call(a)).call(s,(function(n,i){return i(e,t,n)||n}),c),r&&void 0!==c.initializer&&(c.value=c.initializer?c.initializer.call(r):void 0,c.initializer=void 0),void 0===c.initializer&&(KA(e,t,c),c=null),c}let qx=function(e){return e[e.ACCESS_POINT=101]="ACCESS_POINT",e[e.UNILBS=201]="UNILBS",e[e.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",e}({}),Qx=function(e){return e[e.IIIEGAL_APPID=1]="IIIEGAL_APPID",e[e.IIIEGAL_UID=2]="IIIEGAL_UID",e[e.INTERNAL_ERROR=3]="INTERNAL_ERROR",e}({}),$x=function(e){return e[e.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",e[e.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",e[e.INTERNAL_ERROR=8]="INTERNAL_ERROR",e[e.NO_AUTHORIZED=9]="NO_AUTHORIZED",e[e.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",e[e.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",e[e.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",e[e.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",e[e.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",e[e.USER_OVERLOAD=16]="USER_OVERLOAD",e[e.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",e[e.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",e[e.REQ_DOWNGRADE_FALLBACK=27]="REQ_DOWNGRADE_FALLBACK",e}({}),eF=function(e){return e[e.NO_FLAG_SET=100]="NO_FLAG_SET",e[e.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",e[e.INVALID_FALG_SET=102]="INVALID_FALG_SET",e[e.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",e[e.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",e[e.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",e[e.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",e[e.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",e[e.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",e[e.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",e[e.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",e[e.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",e[e.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",e[e.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",e[e.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",e[e.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",e[e.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",e[e.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",e[e.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",e}({}),tF=function(e){return e[e.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",e[e.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",e[e.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",e[e.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",e[e.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",e[e.K_TICKET_INVALID=7]="K_TICKET_INVALID",e[e.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",e[e.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",e[e.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",e[e.K_UID_BANNED=14]="K_UID_BANNED",e[e.K_IP_BANNED=15]="K_IP_BANNED",e[e.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",e[e.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",e[e.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",e[e.K_VOS_FALLBACK=30]="K_VOS_FALLBACK",e[e.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",e[e.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",e[e.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",e[e.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",e[e.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",e[e.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",e[e.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",e[e.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",e[e.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",e[e.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",e[e.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",e[e.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",e[e.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",e[e.ERR_INVALID_UID=117]="ERR_INVALID_UID",e[e.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",e[e.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",e[e.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",e[e.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",e[e.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",e[e.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",e[e.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",e[e.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",e[e.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",e[e.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",e[e.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",e[e.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",e[e.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",e[e.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",e[e.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",e[e.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",e[e.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",e[e.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",e[e.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",e[e.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",e[e.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",e[e.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",e[e.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",e[e.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",e[e.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",e[e.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",e[e.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",e[e.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",e[e.ERR_TOO_MANY_MESSAGES=2033]="ERR_TOO_MANY_MESSAGES",e[e.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",e[e.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",e[e.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",e[e.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",e[e.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",e[e.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",e[e.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",e[e.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",e[e.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",e}({}),nF=function(e){return e.CONNECTING="connecting",e.CONNECTED="connected",e.RECONNECTING="reconnecting",e.CLOSED="closed",e}({}),iF=function(e){return e.WS_CONNECTED="ws_connected",e.WS_RECONNECTING="ws_reconnecting",e.WS_CLOSED="ws_closed",e.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",e.SHOULD_ENTER_RECONNECTING="should_enter_reconnecting",e.ON_BINARY_DATA="on_binary_data",e.REQUEST_RECOVER="request_recover",e.REQUEST_JOIN_INFO="request_join_info",e.REQUEST_JOIN_INFO_WITH_PRE_JOIN_RESPONSE="request_pre_join_response",e.REQUEST_REJOIN_INFO="req_rejoin_info",e.IS_P2P_DISCONNECTED="is_p2p_dis",e.DISCONNECT_P2P="dis_p2p",e.ABORT_P2P_EXECUTION="abort_p2p_execution",e.NEED_RENEW_SESSION="need-sid",e.REPORT_JOIN_GATEWAY="report_join_gateway",e.REQUEST_TIMEOUT="request_timeout",e.REQUEST_SUCCESS="request_success",e.JOIN_RESPONSE="join_response",e.PRE_CONNECT_PC="pre_connect_pc",e.DATACHANNEL_PRECONNECT="datachannel_preconnect",e.DATACHANNEL_CONNECTING="datachannel_connecting",e.DATACHANNEL_FAILBACK="datachannel_failback",e.P2P_CONNECTION="p2p_connection",e.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",e.P2P_SUBSCRIBE="p2p_subscribe",e.P2P_UNSUBSCRIBE="p2p_unsubscribe",e.P2P_EXCHANGE_SDP="p2p_exchange_sdp",e.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",e.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream",e.RECOVER_NOTIFICATION="recover_notification",e.VOS_FALLBACK="vos_fallback",e.VOS_FALLBACK_PROMISE="vos_fallback_promise",e}({}),rF=function(e){return e.PING="ping",e.PING_BACK="ping_back",e.JOIN="join_v3",e.REJOIN="rejoin_v3",e.LEAVE="leave",e.SET_CLIENT_ROLE="set_client_role",e.PUBLISH="publish",e.PUBLISH_DATASTREAM="publish_datastream",e.UNPUBLISH="unpublish",e.UNPUBLISH_DATASTREAM="unpublish_datastream",e.SUBSCRIBE="subscribe",e.PRE_SUBSCRIBE="pre_subscribe",e.SUBSCRIBE_DATASTREAM="subscribe_datastream",e.SUBSCRIBE_STREAMS="subscribe_streams",e.UNSUBSCRIBE="unsubscribe",e.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",e.UNSUBSCRIBE_STREAMS="unsubscribe_streams",e.SUBSCRIBE_CHANGE="subscribe_change",e.TRAFFIC_STATS="traffic_stats",e.RENEW_TOKEN="renew_token",e.SET_DUAL_STREAM_MODE="set_dual_stream_mode",e.SWITCH_VIDEO_STREAM="switch_video_stream",e.DEFAULT_VIDEO_STREAM="default_video_stream",e.SET_FALLBACK_OPTION="set_fallback_option",e.CONFIGURE="configure",e.GATEWAY_INFO="gateway_info",e.CONTROL="control",e.SEND_METADATA="send_metadata",e.DATA_STREAM="data_stream",e.PICK_SVC_LAYER="pick_svc_layer",e.RESTART_ICE="restart_ice",e.CONNECT_PC="connect_pc",e.SET_VIDEO_PROFILE="set_video_profile",e.SET_PARAMETER="set_parameter",e.SET_RTM2_FLAG="set_rtm2_flag",e.DOWNGRADE_CODEC="downgrade_codec",e}({}),oF=function(e){return e.WRTC_STATS="wrtc_stats",e.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",e.DENOISER_STATS="denoiser_stats",e.EXTENSION_USAGE_STATS="extension_usage_stats",e}({}),sF=function(e){return e.ON_USER_ONLINE="on_user_online",e.ON_USER_OFFLINE="on_user_offline",e.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",e.ON_PUBLISH_STREAM="on_publish_stream",e.ON_UPLINK_STATS="on_uplink_stats",e.ON_P2P_LOST="on_p2p_lost",e.ON_REMOVE_STREAM="on_remove_stream",e.ON_ADD_AUDIO_STREAM="on_add_audio_stream",e.ON_ADD_VIDEO_STREAM="on_add_video_stream",e.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",e.ON_USER_BANNED="on_user_banned",e.ON_USER_LICENSE_BANNED="on_user_license_banned",e.ON_NOTIFICATION="on_notification",e.ON_CRYPT_ERROR="on_crypt_error",e.MUTE_AUDIO="mute_audio",e.MUTE_VIDEO="mute_video",e.UNMUTE_AUDIO="unmute_audio",e.UNMUTE_VIDEO="unmute_video",e.ON_P2P_OK="on_p2p_ok",e.RECEIVE_METADATA="receive_metadata",e.ON_DATA_STREAM="on_data_stream",e.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",e.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",e.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",e.ENABLE_LOCAL_VIDEO="enable_local_video",e.DISABLE_LOCAL_VIDEO="disable_local_video",e.ENABLE_LOCAL_AUDIO="enable_local_audio",e.DISABLE_LOCAL_AUDIO="disable_local_audio",e.ON_PUBLISHED_USER_LIST="on_published_user_list",e.ENABLE_MULTI_STREAM="enable_multi_stream",e.ON_USER_LIST="on_user_list",e}({}),aF=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({}),cF=function(e){return e.CONNECTED="websocket:connected",e.RECONNECTING="websocket:reconnecting",e.WILL_RECONNECT="websocket:will_reconnect",e.SHOULD_ENTER_RECONNECTING="websocket:should_enter_reconnecting",e.CLOSED="websocket:closed",e.FAILED="websocket:failed",e.ON_MESSAGE="websocket:on_message",e.REQUEST_NEW_URLS="websocket:request_new_urls",e.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",e.ON_FALLBACK="websocket:on_fallback",e}({});function dF(e){if("string"!=typeof e||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(e))throw SL.error("Invalid Channel Name ".concat(e)),new YL(wN.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _,  {, }, |, ~, ,")}function lF(e){if(!(t=e,"number"==typeof t&&Math.floor(t)===t&&0<=t&&t<=4294967295||VN(e,1,255)))throw new YL(wN.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var t;"string"==typeof e&&SL.warn("You input a string as the user ID, to ensure better end-user experience, Agora highly suggests not using a string as the user ID.")}let uF=function(e){return e.TRANSCODE="mix_streaming",e.RAW="raw_streaming",e}({});const hF={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},pF={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function _F(e,t){kN(e.url,"".concat(t,".url"),1,1e3,!1),UN(e.x)||PN(e.x,"".concat(t,".x"),0,1e4),UN(e.y)||PN(e.y,"".concat(t,".y"),0,1e4),UN(e.width)||PN(e.width,"".concat(t,".width"),0,1e4),UN(e.height)||PN(e.height,"".concat(t,".height"),0,1e4),UN(e.zOrder)||PN(e.zOrder,"".concat(t,".zOrder"),0,255),UN(e.alpha)||PN(e.alpha,"".concat(t,".alpha"),0,1,!1)}const EF={audioBitrate:48,audioChannels:1,audioSampleRate:48e3,backgroundColor:0,height:360,lowLatency:!1,videoBitrate:400,videoCodecProfile:100,videoCodecType:1,videoFrameRate:15,videoGop:30,width:640,images:[],userConfigs:[],userConfigExtraInfo:""};let mF=function(e){return e.WARNING="@live_uap-warning",e.ERROR="@line_uap-error",e.PUBLISH_STREAM_STATUS="@live_uap-publish-status",e.WORKER_STATUS="@live_uap-worker-status",e.REQUEST_NEW_ADDRESS="@live_uap-request-address",e}({}),fF=function(e){return e.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",e}({}),gF=function(e){return e[e.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",e[e.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",e[e.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",e[e.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",e[e.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",e[e.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",e[e.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",e[e.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",e[e.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",e[e.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",e[e.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",e[e.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",e[e.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",e[e.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",e[e.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",e[e.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",e[e.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",e[e.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",e}({});function SF(e){if(!e.channelName)throw new YL(wN.INVALID_PARAMS,"invalid channelName in info");if("number"!=typeof e.uid)throw new YL(wN.INVALID_PARAMS,"invalid uid in info, uid must be a number");return e.token&&kN(e.token,"info.token",1,2047),lF(e.uid),dF(e.channelName),!0}let TF=function(e){return e[e.SetSdkProfile=0]="SetSdkProfile",e[e.SetSourceChannel=1]="SetSourceChannel",e[e.SetSourceUserId=2]="SetSourceUserId",e[e.SetDestChannel=3]="SetDestChannel",e[e.StartPacketTransfer=4]="StartPacketTransfer",e[e.StopPacketTransfer=5]="StopPacketTransfer",e[e.UpdateDestChannel=6]="UpdateDestChannel",e[e.Reconnect=7]="Reconnect",e[e.SetVideoProfile=8]="SetVideoProfile",e}({}),RF=function(e){return e.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",e.NETWORK_CONNECTED="NETWORK_CONNECTED",e.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",e.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",e.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",e.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",e.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",e.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",e.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",e.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",e}({}),vF=function(e){return e.RELAY_STATE_IDLE="RELAY_STATE_IDLE",e.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",e.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",e.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",e}({}),yF=function(e){return e.RELAY_OK="RELAY_OK",e.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",e.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",e.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",e}({}),CF=function(e){return e.High="high",e.Low="low",e.Audio="audio",e.Screen="screen",e.ScreenLow="screen_low",e}({}),bF=function(e){return e.DISCONNECT="disconnect",e.CONNECTION_STATE_CHANGE="connection-state-change",e.NETWORK_QUALITY="network-quality",e.STREAM_TYPE_CHANGE="stream-type-change",e.IS_P2P_DISCONNECTED="is-p2p-dis",e.DISCONNECT_P2P="dis-p2p",e.REQUEST_NEW_GATEWAY_LIST="req-gate-url",e.NEED_RENEW_SESSION="need-sid",e.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",e.JOIN_RESPONSE="join-response",e.RESET_CONNECTION_EVENTS="reset-connection-events",e.PRE_CONNECT_PC="pre-connect_pc",e.UPDATE_GATEWAY_CONFIG="update-gateway-config",e.VOS_FALLBACK="vos-fallback",e.VOS_FALLBACK_PROMISE="vos-fallback-promise",e.RESET_SIGNAL="reset-signal",e.DATACHANNEL_FAILBACK="datachannel-failback",e}({}),IF=function(e){return e.P2P_DISCONNECTED="P2P_DISCONNECTED",e.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",e.TIMEOUT="TIMEOUT",e.UNKNOWN_REASON="UNKNOWN_REASON",e}({}),AF=function(e){return e[e.Nothing=0]="Nothing",e[e.Audio=1]="Audio",e[e.LowVideo=2]="LowVideo",e[e.Video=4]="Video",e[e.Data=8]="Data",e[e.DataStream0=256]="DataStream0",e[e.DataStream1=512]="DataStream1",e[e.DataStream2=1024]="DataStream2",e[e.DataStream3=2048]="DataStream3",e[e.DataStream4=4096]="DataStream4",e[e.DataStream5=8192]="DataStream5",e[e.DataStream6=16384]="DataStream6",e[e.DataStream7=32768]="DataStream7",e}({}),wF=function(e){return e.CHINA="CHINA",e.ASIA="ASIA",e.NORTH_AMERICA="NORTH_AMERICA",e.EUROPE="EUROPE",e.JAPAN="JAPAN",e.INDIA="INDIA",e.KOREA="KOREA",e.HKMC="HKMC",e.US="US",e.OCEANIA="OCEANIA",e.SOUTH_AMERICA="SOUTH_AMERICA",e.AFRICA="AFRICA",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="EXTENSIONS",e}({});const OF=[wF.AFRICA,wF.ASIA,wF.CHINA,wF.EUROPE,wF.GLOBAL,wF.INDIA,wF.JAPAN,wF.NORTH_AMERICA,wF.OCEANIA,wF.OVERSEA,wF.SOUTH_AMERICA];let NF=function(e){return e.CHINA="CN",e.ASIA="AS",e.NORTH_AMERICA="NA",e.EUROPE="EU",e.JAPAN="JP",e.INDIA="IN",e.KOREA="KR",e.HKMC="HK",e.US="US",e.OCEANIA="OC",e.SOUTH_AMERICA="SA",e.AFRICA="AF",e.OVERSEA="OVERSEA",e.GLOBAL="GLOBAL",e.EXTENSIONS="GLOBAL",e}({});const DF={CHINA:{},ASIA:{CODE:NF.ASIA,WEBCS_DOMAIN:["ap-web-1-asia.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-asia.agora.io"],PROXY_CS:["proxy-ap-web-asia.agora.io"],CDS_AP:["cds-ap-web-asia.agora.io","cds-ap-web-asia2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-asia.agora.io","sua-ap-web-asia2.agora.io"],UAP_AP:["uap-ap-web-asia.agora.io","uap-ap-web-asia2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-asia.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-asia.agora.io"],LOG_UPLOAD_SERVER:["logservice-asia.agora.io"],PROXY_SERVER_TYPE3:["southeast-asia.webrtc-cloud-proxy.sd-rtn.com"]},NORTH_AMERICA:{CODE:NF.NORTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-north-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-north-america.agora.io"],PROXY_CS:["proxy-ap-web-america.agora.io"],CDS_AP:["cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],UAP_AP:["uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-north-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-north-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-north-america.agora.io"],PROXY_SERVER_TYPE3:["east-usa.webrtc-cloud-proxy.sd-rtn.com"]},EUROPE:{CODE:NF.EUROPE,WEBCS_DOMAIN:["ap-web-1-europe.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-europe.agora.io"],PROXY_CS:["proxy-ap-web-europe.agora.io"],CDS_AP:["cds-ap-web-europe.agora.io","cds-ap-web-europe2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-europe.agora.io","sua-ap-web-europe.agora.io"],UAP_AP:["uap-ap-web-europe.agora.io","uap-ap-web-europe2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-europe.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-europe.agora.io"],LOG_UPLOAD_SERVER:["logservice-europe.agora.io"],PROXY_SERVER_TYPE3:["europe.webrtc-cloud-proxy.sd-rtn.com"]},JAPAN:{CODE:NF.JAPAN,WEBCS_DOMAIN:["ap-web-1-japan.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-japan.agora.io"],PROXY_CS:["proxy-ap-web-japan.agora.io"],CDS_AP:["cds-ap-web-japan.agora.io","cds-ap-web-japan2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-japan.agora.io","sua-ap-web-japan2.agora.io"],UAP_AP:["uap-ap-web-japan.agora.io","uap-ap-web-japan2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-japan.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-japan.agora.io"],LOG_UPLOAD_SERVER:["logservice-japan.agora.io"],PROXY_SERVER_TYPE3:["japan.webrtc-cloud-proxy.sd-rtn.com"]},INDIA:{CODE:NF.INDIA,WEBCS_DOMAIN:["ap-web-1-india.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-india.agora.io"],PROXY_CS:["proxy-ap-web-india.agora.io"],CDS_AP:["cds-ap-web-india.agora.io","cds-ap-web-india2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-india.agora.io","sua-ap-web-india2.agora.io"],UAP_AP:["uap-ap-web-india.agora.io","uap-ap-web-india2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-india.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-india.agora.io"],LOG_UPLOAD_SERVER:["logservice-india.agora.io"],PROXY_SERVER_TYPE3:["india.webrtc-cloud-proxy.sd-rtn.com"]},KOREA:{CODE:NF.KOREA,WEBCS_DOMAIN:["ap-web-1-korea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-korea.agora.io"],PROXY_CS:["proxy-ap-web-korea.agora.io"],CDS_AP:["cds-ap-web-korea.agora.io","cds-ap-web-korea2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-korea.agora.io","sua-ap-web-korea2.agora.io"],UAP_AP:["uap-ap-web-korea.agora.io","uap-ap-web-korea2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-korea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-korea.agora.io"],LOG_UPLOAD_SERVER:["logservice-korea.agora.io"],PROXY_SERVER_TYPE3:["korea.webrtc-cloud-proxy.sd-rtn.com"]},HKMC:{CODE:NF.HKMC,WEBCS_DOMAIN:["ap-web-1-hkmc.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-hkmc.agora.io"],PROXY_CS:["proxy-ap-web-hkmc.agora.io"],CDS_AP:["cds-ap-web-hkmc.agora.io","cds-ap-web-hkmc2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-hkmc.agora.io","sua-ap-web-hkmc2.agora.io"],UAP_AP:["uap-ap-web-hkmc.agora.io","uap-ap-web-hkmc2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-hkmc.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-hkmc.agora.io"],LOG_UPLOAD_SERVER:["logservice-hkmc.agora.io"],PROXY_SERVER_TYPE3:["hkmc.webrtc-cloud-proxy.sd-rtn.com"]},US:{CODE:NF.US,WEBCS_DOMAIN:["ap-web-1-us.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-us.agora.io"],PROXY_CS:["proxy-ap-web-us.agora.io"],CDS_AP:["cds-ap-web-us.agora.io","cds-ap-web-us2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-us.agora.io","sua-ap-web-us2.agora.io"],UAP_AP:["uap-ap-web-us.agora.io","uap-ap-web-us2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-us.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-us.agora.io"],LOG_UPLOAD_SERVER:["logservice-us.agora.io"],PROXY_SERVER_TYPE3:["us.webrtc-cloud-proxy.sd-rtn.com"]},OVERSEA:{CODE:NF.OVERSEA,WEBCS_DOMAIN:["ap-web-1-oversea.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oversea.agora.io"],PROXY_CS:["proxy-ap-web-oversea.agora.io"],CDS_AP:["cds-ap-web-oversea.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oversea.agora.io"],UAP_AP:["uap-ap-web-oversea.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oversea.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oversea.agora.io"],LOG_UPLOAD_SERVER:["logservice-oversea.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.agora.io"]},GLOBAL:{CODE:NF.GLOBAL,WEBCS_DOMAIN:["webrtc2-ap-web-1.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-ap-web-3.agora.io"],PROXY_CS:["ap-proxy-1.agora.io","ap-proxy-2.agora.io"],CDS_AP:["cds-ap-web-1.agora.io","cds-ap-web-3.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-1.agora.io","sua-ap-web-3.agora.io"],UAP_AP:["uap-ap-web-1.agora.io","uap-ap-web-3.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2.agora.io"],LOG_UPLOAD_SERVER:["logservice.agora.io"],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy.sd-rtn.com"]},OCEANIA:{CODE:NF.OCEANIA,WEBCS_DOMAIN:["ap-web-1-oceania.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-oceania.agora.io"],PROXY_CS:["proxy-ap-web-oceania.agora.io"],CDS_AP:["cds-ap-web-oceania.agora.io","cds-ap-web-oceania2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-oceania.agora.io","sua-ap-web-oceania2.agora.io"],UAP_AP:["uap-ap-web-oceania.agora.io","uap-ap-web-oceania2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-oceania.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-oceania.agora.io"],LOG_UPLOAD_SERVER:["logservice-oceania.agora.io"],PROXY_SERVER_TYPE3:["oceania.webrtc-cloud-proxy.sd-rtn.com"]},SOUTH_AMERICA:{CODE:NF.SOUTH_AMERICA,WEBCS_DOMAIN:["ap-web-1-south-america.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-south-america.agora.io"],PROXY_CS:["proxy-ap-web-south-america.agora.io"],CDS_AP:["cds-ap-web-south-america.agora.io","cds-ap-web-south-america2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-south-america.agora.io","sua-ap-web-south-america2.agora.io"],UAP_AP:["uap-ap-web-south-america.agora.io","uap-ap-web-south-america2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-south-america.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-south-america.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-america.agora.io"],PROXY_SERVER_TYPE3:["south-america.webrtc-cloud-proxy.sd-rtn.com"]},AFRICA:{CODE:NF.AFRICA,WEBCS_DOMAIN:["ap-web-1-africa.agora.io"],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-africa.agora.io"],PROXY_CS:["proxy-ap-web-africa.agora.io"],CDS_AP:["cds-ap-web-africa.agora.io","cds-ap-web-africa2.agora.io"],ACCOUNT_REGISTER:["sua-ap-web-africa.agora.io","sua-ap-web-africa2.agora.io"],UAP_AP:["uap-ap-web-africa.agora.io","uap-ap-web-africa2.agora.io"],EVENT_REPORT_DOMAIN:["statscollector-1-africa.agora.io"],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-africa.agora.io"],LOG_UPLOAD_SERVER:["logservice-south-africa.agora.io"],PROXY_SERVER_TYPE3:["africa.webrtc-cloud-proxy.sd-rtn.com"]},EXTENSIONS:{}};OP&&(DF.CHINA={CODE:NF.CHINA,WEBCS_DOMAIN:["webrtc2-2.ap.sd-rtn.com"],WEBCS_DOMAIN_BACKUP_LIST:["webrtc2-4.ap.sd-rtn.com"],PROXY_CS:["proxy-web.ap.sd-rtn.com"],CDS_AP:["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],ACCOUNT_REGISTER:["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],UAP_AP:["uap-web-2.ap.sd-rtn.com","uap-web-4.ap.sd-rtn.com"],EVENT_REPORT_DOMAIN:["web-3.statscollector.sd-rtn.com"],EVENT_REPORT_BACKUP_DOMAIN:["web-4.statscollector.sd-rtn.com"],LOG_UPLOAD_SERVER:["logservice-china.agora.io"],PROXY_SERVER_TYPE3:["east-cn.webrtc-cloud-proxy.sd-rtn.com"]});let PF=function(e){return e.UPDATE_BITRATE_LIMIT="update_bitrate_limit",e.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",e.UPDATE_REMOTE_VIDEO_STREAM_TYPE="update_remote_video_stream_type",e.FALLBACK_TO_HLS="fallback_to_hls",e.UPDATE_VOS_CONFIGURE="update_vos_configure",e}({});function LF(e){return!!e&&(!(!e.uplink||!e.id)&&(void 0!==e.uplink.max_bitrate&&void 0!==e.uplink.min_bitrate))}class kF extends YN{constructor(e,t){super(),zA(this,"onICEConnectionStateChange",void 0),zA(this,"onConnectionStateChange",void 0),zA(this,"onDTLSTransportStateChange",void 0),zA(this,"onDTLSTransportError",void 0),zA(this,"onICETransportStateChange",void 0),zA(this,"onFirstAudioReceived",void 0),zA(this,"onFirstVideoReceived",void 0),zA(this,"onFirstAudioDecoded",void 0),zA(this,"onFirstVideoDecoded",void 0),zA(this,"onFirstVideoRender",void 0),zA(this,"onFirstVideoBufferReady",void 0),zA(this,"onFirstVideoDecodedTimeout",void 0),zA(this,"onAudioMetadata",void 0),zA(this,"onAudioPts",void 0),zA(this,"onSelectedLocalCandidateChanged",void 0),zA(this,"onSelectedRemoteCandidateChanged",void 0),zA(this,"onICECandidateError",void 0),zA(this,"getLocalVideoStats",void 0)}}class MF extends kF{constructor(e,t){super(e,t),zA(this,"establishPromise",void 0)}}let UF=function(e){return e.VIDEO="video",e.AUDIO="audio",e}({}),VF=function(e){return e.UDP_RELAY="udp_relay",e.UDP_TCP_RELAY="udp_tcp_relay",e.TCP_RELAY="tcp_relay",e.RELAY="relay",e}({}),xF=function(e){return e[e.FIRST_CONNECTION=0]="FIRST_CONNECTION",e[e.UDP_TCP_RESTART=1]="UDP_TCP_RESTART",e[e.RELAY_RESTART=2]="RELAY_RESTART",e[e.TCP_RESTART=3]="TCP_RESTART",e[e.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",e[e.OLD_RESTART=11]="OLD_RESTART",e[e.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED",e}({});const FF=["disconnected","failed"];let BF=function(e){return e.LocalVideoTrack="videoTrack",e.LocalAudioTrack="audioTrack",e.LocalVideoLowTrack="videoLowTrack",e}({}),jF=function(e){return e.New="new",e.Connected="connected",e.Reconnecting="reconnecting",e.Disconnected="disconnected",e}({}),GF=function(e){return e.AudioMetadata="audioMetadata",e.AudioPts="audioPts",e.StateChange="stateChange",e.IceConnectionStateChange="iceConnectionStateChange",e.RequestMuteLocal="requestMuteLocal",e.RequestUnmuteLocal="requestUnmuteLocal",e.RequestRePublish="requestRePublish",e.RequestRePublishDataChannel="requestRePublishDataChannel",e.RequestReSubscribe="requestReSubscribe",e.RequestUploadStats="requestUploadStats",e.RequestUpload="requestUpload",e.MediaReconnectStart="MediaReconnectStart",e.MediaReconnectEnd="MediaReconnectEnd",e.NeedSignalRTT="NeedSignalRTT",e.RequestRestartICE="RequestRestartIce",e.PeerConnectionStateChange="PeerConnectionStateChange",e.RequestReconnect="RequestReconnect",e.RequestReconnectPC="RequestReconnectPC",e.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",e.P2PLost="P2PLost",e.UpdateVideoEncoder="UpdateVideoEncoder",e.ConnectionTypeChange="ConnectionTypeChange",e.RequestLowStreamParameter="RequestLowStreamParameter",e.QueryClientConnectionState="QueryClientConnectionState",e.LocalCandidate="LocalCandidate",e.RequestP2PMuteLocal="requestP2PMuteLocal",e.RequestP2PUnPublish="RequestP2PUnPublish",e.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",e.RequestP2PMuteRemote="RequestP2PMuteRemote",e.RequestP2PRestartICE="RequestP2PRestartICE",e.FirstVideoPreRender="FirstVideoPreRender",e.FirstVideoBufferReady="FirstVideoBufferReady",e}({}),WF=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),KF=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),HF=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),YF=function(e){return e.NETWORK_ERROR="NETWORK_ERROR",e.SERVER_ERROR="SERVER_ERROR",e.MULTI_IP="MULTI_IP",e.TIMEOUT="TIMEOUT",e.OFFLINE="OFFLINE",e.LEAVE="LEAVE",e.P2P_FAILED="P2P_FAILED",e.FALLBACK="FALLBACK",e}({}),XF=function(e){return e.CONNECTED="transmitter:connected",e.RECONNECTING="transmitter:reconnecting",e.WILL_RECONNECT="transmitter:will_reconnect",e.CLOSED="transmitter:closed",e.FAILED="transmitter:failed",e.ON_MESSAGE="transmitter:on_message",e.REQUEST_NEW_URLS="transmitter:request_new_urls",e.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",e.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",e.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",e.FAILBACK="transmitter:failback",e.PRE_CONNECT_PC="transmitter:pre_connect_pc",e}({}),JF=function(e){return e.CAMERA_CHANGED="camera-changed",e.MICROPHONE_CHANGED="microphone-changed",e.PLAYBACK_DEVICE_CHANGED="playback-device-changed",e.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",e.AUTOPLAY_FAILED="autoplay-failed",e.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",e.SECURITY_POLICY_VIOLATION="security-policy-violation",e}({}),zF=function(e){return e.CONNECTING="CONNECTING",e.RECONNECTING="RECONNECTING",e.CONNECTED="CONNECTED",e.CLOSED="CLOSED",e}({}),ZF=function(e){return e.CONNECTION_STATE_CHANGE="connection-state-change",e.STATE_CHANGE="state-change",e.INSPECT_RESULT="inspect-result",e.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",e.REQUEST_NEW_WORKER_URL="request-new-worker-url",e}({}),qF=function(e){return e[e.CONNECT_AP=0]="CONNECT_AP",e[e.AP_CONNECTED=1]="AP_CONNECTED",e[e.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",e[e.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",e[e.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",e[e.CONNECT_WORKER=5]="CONNECT_WORKER",e[e.WORKER_CONNECTED=6]="WORKER_CONNECTED",e[e.CLOSED=7]="CLOSED",e}({}),QF=function(e){return e.CALL="call",e.CANDIDATE="candidate",e.PUBLISH="publish",e.UNPUBLISH="unpublish",e.CONTROL="control",e.RESTART_ICE="restart_ice",e.ACK="ack",e.RESPONSE="response",e.JOIN="join",e.CHECK="check",e}({}),$F=function(e){return e.ABORT="abort",e}({}),eB=function(e){return e.MUTE_LOCAL_AUDIO="mute_local_audio",e.MUTE_LOCAL_VIDEO="mute_local_video",e.UNMUTE_LOCAL_AUDIO="unmute_local_audio",e.UNMUTE_LOCAL_VIDEO="unmute_local_video",e}({}),tB=function(e){return e.P2P_TOKEN_TIMEOUT="p2p_token_timeout",e.P2P_TOKEN_CHANGED="p2p_token_changed",e}({});const nB={[qx.ACCESS_POINT]:{[eF.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[eF.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[eF.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[eF.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[eF.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[eF.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[eF.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[qx.UNILBS]:{[$x.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[$x.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[$x.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[$x.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[$x.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[$x.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[$x.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[$x.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[$x.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[$x.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[$x.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[$x.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1},[$x.REQ_DOWNGRADE_FALLBACK]:{desc:"request downgrade fallback",retry:!1}},[qx.STRING_UID_ALLOCATOR]:{[Qx.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[Qx.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[Qx.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function iB(e){const t=nB[Math.floor(e/1e4)];if(!t)return{desc:"unknown error",retry:!1};const n=t[e%1e4];if(!n){if(Math.floor(e/1e4)===qx.ACCESS_POINT){const t=e%1e4;if("1"===t.toString()[0])return{desc:e.toString(),retry:!1};if("2"===t.toString()[0])return{desc:e.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return n}const rB={[tF.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[tF.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[tF.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[tF.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[tF.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[tF.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[tF.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[tF.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[tF.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[tF.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[tF.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[tF.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[tF.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[tF.K_VOS_FALLBACK]:{desc:"K_VOS_FALLBACK",action:"tryNext"},[tF.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[tF.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[tF.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[tF.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[tF.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[tF.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[tF.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[tF.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[tF.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[tF.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[tF.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[tF.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[tF.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[tF.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[tF.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[tF.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[tF.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[tF.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[tF.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[tF.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[tF.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[tF.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[tF.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[tF.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[tF.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[tF.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[tF.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[tF.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[tF.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[tF.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[tF.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[tF.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[tF.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[tF.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[tF.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[tF.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[tF.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[tF.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[tF.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[tF.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[tF.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[tF.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[tF.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[tF.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[tF.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[tF.ERR_TOO_MANY_MESSAGES]:{desc:"ERR_TOO_MANY_MESSAGES",action:"tryNext"},[tF.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[tF.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[tF.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[tF.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[tF.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[tF.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function oB(e){const t=rB[e];return t||{desc:"UNKNOWN_ERROR_".concat(e),action:"failed"}}function sB(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function aB(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?sB(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sB(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function cB(e,t){if("string"==typeof e)return e;const n=e.proxy,i=e.host,r=e.port;if(t){const e=xP("JOIN_GATEWAY_FALLBACK_PORT")||443;return 443===e?"wss://".concat(i,"/ws/?p=").concat(Number(r)+150):"wss://".concat(i,":").concat(e,"/ws/?p=").concat(Number(r)+150)}return n?"wss://".concat(n,"/ws/?h=").concat(i,"&p=").concat(r):"wss://".concat(i,":").concat(r)}const dB=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,lB=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,uB=/wss:\/\/(.+):([0-9]+)\/?/,hB=/wss:\/\/(.[^\/]+)\/?/;let pB=0;class _B{constructor(e,t){zA(this,"id",0),zA(this,"store",void 0),zA(this,"recordIndex",void 0),zA(this,"websockets",[]),zA(this,"try443PortDuration",2e3),zA(this,"forceCloseWSDuration",5e3),zA(this,"try443PortTimeout",null),zA(this,"forceCloseTimeout",null),zA(this,"isTry443PortFailed",!1),zA(this,"isNormalPortFailed",!1),zA(this,"useDoubleDomain",!1),zA(this,"useProxy",!1),zA(this,"startTime",Date.now()),this.id=++pB,this.try443PortDuration=xP("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=t}closeAllWebsockets(){this.websockets.forEach((e=>{e.onopen=null,e.onclose=null,e.onmessage=null,e.close()})),this.websockets.length=0}clearTimeout(){this.forceCloseTimeout&&clearTimeout(this.forceCloseTimeout),this.try443PortTimeout&&clearTimeout(this.try443PortTimeout),this.forceCloseTimeout=null,this.try443PortTimeout=null}logger(){var e;const t=Date.now()-this.startTime;for(var n=arguments.length,i=new Array(n),r=0;r<n;r++)i[r]=arguments[r];SL.debug("[choose-best-ws ".concat(null===(e=this.store)||void 0===e?void 0:e.clientId," ").concat(this.id,"] ").concat(t,"ms:"),...i)}createWebSocket(e,t,n){this.logger("createWebSocket:",e,{isTry443Port:t,hasTimeoutDetection:n});const i=xP("GATEWAY_DOMAINS"),r=Date.now(),o=[],s=i.find((t=>{var n;return Ui(n=e.host).call(n,t)}));s||(this.useDoubleDomain=!1);const a=[];if(this.useDoubleDomain)i.forEach((n=>{a.push(cB(aB(aB({},e),{},{host:e.host.replace(s,n)}),t))}));else{const n=aB({},e);if(t&&s){const e=i.find((e=>e!==s));e&&(n.host=n.host.replace(s,e))}a.push(cB(n,t))}try{a.forEach((e=>{const t=new WebSocket(e);t.binaryType="arraybuffer",o.push(t),this.logger("ws is connecting:",t.url)}))}catch(i){if(this.logger("ws create failed"),o.forEach((e=>e.close())),o.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,t,n);if(!t&&443!==Number(e.port))return this.createWebSocket(e,!0,n);throw new YL(wN.WS_ERR,"init websocket failed! Error: ".concat(i.toString()))}const c=LO();this.store&&this.store.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},this.recordIndex),o.forEach((e=>{e.onopen=()=>{this.logger("onopen: ws ".concat(e.url," open cost ").concat(Date.now()-r,"ms")),this.websockets.forEach((t=>{t!==e&&(t.onopen=null,t.onclose=null,t.onmessage=null,t.close(),this.logger("close backup websocket: ".concat(t.url)))})),this.websockets.length=0,c.resolve(e)},e.onclose=n=>{this.logger("onclose: ws ".concat(e.url," closed cost ").concat(Date.now()-r,"ms state: ").concat(e.readyState));const i=o.every((e=>e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING));this.logger("".concat(t?"443":"47xx"," websocket closed, all failed: ").concat(i)),i&&(t||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(n.reason)),c.reject({code:n.code,reason:IF.A_ROUND_WS_FAILED})):!t&&i&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),l()),t?this.isTry443PortFailed=i:this.isNormalPortFailed=i},e.onmessage=t=>this.logger("".concat(e.url," onmessage: ").concat(t.data))})),this.websockets.push(...o);const d=()=>{this.websockets.forEach((e=>e.readyState!==WebSocket.OPEN&&e.close()))},l=()=>{if(c.isResolved)return d();GO().os===VO.MAC_OS&&$O()&&d(),this.createWebSocket(e,!0,!0).then((e=>{c.resolve(e)})).catch((e=>{this.isNormalPortFailed&&c.reject(e),this.logger("try 443 port to create ws failed")})),this.forceCloseTimeout=window.setTimeout((()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",c.isResolved),this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration)};return n||(()=>{if(t||this.useProxy)return this.logger("add 5s timeout at ".concat(t?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout((()=>{this.forceCloseTimeout=null,d()}),this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout((()=>{this.logger("2s timeout, isWebsocket created: ",c.isResolved),this.try443PortTimeout=null,l()}),this.try443PortDuration)})(),c.promise}chooseBestWebsocket(e,t,n,i){return this.useDoubleDomain=!!t,"string"==typeof e&&(e=function(e){let t,n,i;var r=KC(e.match(dB)||[],4);if(t=r[1],n=r[2],i=r[3],!t){var o=KC(e.match(lB)||[],3);n=o[1],i=o[2]}if(!n||!i){var s=KC(e.match(uB)||[],3);n=s[1],i=s[2]}return n&&i||(n=KC(e.match(hB)||[],2)[1]),n||SL.warning("un-destructible url: ",e),{proxy:t,host:n,port:i||"443"}}(e)),this.recordIndex=i,this.useProxy=!!e.proxy,n&&this.useProxy&&(SL.warn("cannot use 443 only when use proxy"),n=!1),this.createWebSocket(e,!!n,!1).finally((()=>this.clearTimeout()))}}function EB(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class mB extends YN{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reportUrl(){return"connected"===this._state&&this.websocket?this.websocket.url:this._lastAttemptedUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Ui(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get isFirstJoin(){return this.queryReconnectingWhenConnecting}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(cF.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(cF.CONNECTED):"closed"===this._state?this.emit(cF.CLOSED):"failed"===this._state&&this.emit(cF.FAILED))}resetReconnectCount(e){SL.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]&&arguments[4],o=arguments.length>5?arguments[5]:void 0;super(),zA(this,"_websocketUrl",null),zA(this,"_lastAttemptedUrl",null),zA(this,"connectionID",0),zA(this,"currentURLIndex",0),zA(this,"urls",[]),zA(this,"_reconnectMode","tryNext"),zA(this,"reconnectReason",void 0),zA(this,"_initMutex",void 0),zA(this,"name",void 0),zA(this,"_state","closed"),zA(this,"reconnectInterrupter",void 0),zA(this,"websocket",void 0),zA(this,"retryConfig",void 0),zA(this,"reconnectCount",0),zA(this,"forceCloseTimeout",5e3),zA(this,"queryReconnectingWhenConnecting",!1),zA(this,"onlineReconnectListener",void 0),zA(this,"useCompress",void 0),zA(this,"tryDoubleDomain",!1),zA(this,"use443PortOnly",!1),zA(this,"wsInflateLength",0),zA(this,"wsDeflateLength",0),zA(this,"closeEstablishingWs",(()=>{})),zA(this,"store",void 0),zA(this,"joinGatewayRecordIndex",void 0),this.store=o,this.name=e,this.retryConfig=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?EB(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):EB(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},t),this.useCompress=n,this.tryDoubleDomain=i,this.use443PortOnly=r,this._initMutex=new JD("websocket",o?o.clientId:void 0);const s=t.timeout,a=t.timeoutFactor,c=Math.max(300,Math.floor(3*s/5)),d=Math.max(1.2,Math.floor(8*a)/10);aD.ONLINE&&(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d),pD.on(cD.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===aD.ONLINE?(this.retryConfig.timeout=c,this.retryConfig.timeoutFactor=d):(this.retryConfig.timeout=s,this.retryConfig.timeoutFactor=a))}))}getConnection(){return this.websocket||void 0}disableQueryReconnectingWhenConnecting(){this.queryReconnectingWhenConnecting=!1}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const i=await this._initMutex.lock();this._lastAttemptedUrl=null,this._reconnectMode="tryNext",this.forceCloseTimeout=t,this.queryReconnectingWhenConnecting=!0===n.queryReconnectingWhenConnecting,this.urls=e,this.state="connecting";try{var r;const e=LO(),t=this.urls[this.currentURLIndex];null===(r=this.store)||void 0===r||r.beforeConnect(),this.createWebSocketConnection(t).then(e.resolve).catch(e.reject),this.once(cF.CLOSED,(()=>{e.reject(new ON(wN.WS_DISCONNECT))})),this.once(cF.CONNECTED,e.resolve),await e.promise}catch(e){}finally{i()}}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this.reconnectInterrupter&&this.reconnectInterrupter(),this.websocket){this.websocket.onclose=null,this.websocket.onopen=null,this.websocket.onmessage=null;const e=this.websocket;t?setTimeout((()=>e.close()),500):e.close(),this.websocket=void 0,this._websocketUrl=null}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,t){if(!this.websocket)return void SL.warning("[".concat(this.name,"] can not reconnect, no websocket"));void 0!==e&&(this.reconnectMode=e),SL.debug("[".concat(this.name,"] reconnect is triggered initiative")),"number"==typeof this.joinGatewayRecordIndex&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(t)]},this.joinGatewayRecordIndex);const n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.bind(this.websocket)({code:9999,reason:t})}sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new ON(wN.WS_ABORT,"websocket is not ready");try{t||(e=JSON.stringify(e)),this.websocket.send(e)}catch(e){throw new ON(wN.WS_ERR,"send websocket message error"+e.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,t=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:t}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}async createWebSocketConnection(e){var t;const n=LO();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const i=e=>{var t;null===(t=this.store)||void 0===t||t.signalChannelOpen(),SL.debug("[".concat(this.name,"] websocket opened:"),e),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},r=async e=>{var t;if(SL.debug("[".concat(this.name,"] websocket close ").concat(null===(t=this.websocket)||void 0===t?void 0:t.url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new ON(wN.WS_DISCONNECT,"websocket close: ".concat(e.code))),this.close();else{const t=this.queryReconnectingWhenConnecting;this.disableQueryReconnectingWhenConnecting();const i=t&&("connecting"===this.state||"connected"===this.state)&&!0===uD(this,cF.SHOULD_ENTER_RECONNECTING,e.reason);("connected"===this.state||i)&&(this.reconnectReason=e.reason,this.state="reconnecting");const r=uD(this,cF.WILL_RECONNECT,this.reconnectMode,e.reason)||this.reconnectMode,o=await this.reconnectWithAction(r);if("closed"===this.state)return void SL.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!o)return n.reject(new ON(wN.WS_DISCONNECT,"websocket reconnect failed: ".concat(e.code))),this.close(!0);n.resolve()}},o=e=>{this.emit(cF.ON_MESSAGE,e)},s=e=>{SL.warn("[".concat(this.connectionID,"] ws open error ").concat(e))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),xP("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=xP("GATEWAY_WSS_ADDRESS")),SL.debug("[".concat(this.name,"] start connect, url:"),e);const a=null===(t=this.store)||void 0===t?void 0:t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var c;const t=cB(e);this._websocketUrl=t,this._lastAttemptedUrl=t;const n=await this.chooseBestWebsocketConnection(e);this.websocket=n,i&&i(this.websocket.url),this.websocket.onclose=r,this.websocket.onmessage=o,this.websocket.onerror=s,null===(c=this.store)||void 0===c||c.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this.joinGatewayRecordIndex=a}catch(e){const t="closed"===this.state,i=e instanceof ON,o=i&&e.code===wN.WS_ABORT,s=i&&e.code===wN.WS_ERR,c=i?e.message:e&&(e.reason||e.toString());SL.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(c)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:o?"aborted":"error",errors:[e]},a),t||s?(n.reject(t?new ON(wN.WS_DISCONNECT,"websocket is closed: ".concat(c)):new ON(wN.WS_ERR,"init websocket failed: ".concat(c))),s&&SL.error("[".concat(this.name,"] init websocket failed: ").concat(c))):r&&r(e)}return n.promise}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount)return!1;if(0===this.urls.length)return!1;if("closed"===this.state)return!1;SL.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||pD.isOnline||!pD.onlineWaiter||(this.onlineReconnectListener=pD.onlineWaiter.then((()=>{this.onlineReconnectListener=void 0})));let n=!0;if(this.reconnectInterrupter=()=>n=!1,t){const t=qD(this.reconnectCount,this.retryConfig);SL.debug("[".concat(this.name,"] wait ").concat(t,"ms to reconnect websocket, mode: ").concat(e)),await cp.race([LD(t),this.onlineReconnectListener||new cp((()=>{}))])}if("closed"===this._state||!n)return!1;this.reconnectCount+=1;const i=async(e,t)=>{this.emit(cF.RECONNECT_CREATE_CONNECTION,t),await this.createWebSocketConnection(e)};try{if("retry"===e)await i(this.urls[this.currentURLIndex],e);else if("tryNext"===e){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);SL.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),await i(this.urls[this.currentURLIndex],e)}else"recover"===e&&(SL.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=await dD(this,cF.REQUEST_NEW_URLS),this.currentURLIndex=0,await i(this.urls[this.currentURLIndex],e))}catch(n){var r;SL.error("[".concat(this.name,"] reconnect failed ").concat(n&&n.toString()));const i=null==n||null===(r=n.data)||void 0===r?void 0:r.desc;if(Array.isArray(i)){if(Ui(i).call(i,"dynamic key expired"))return this.emit(cF.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1;if(Ui(i).call(i,"request downgrade fallback"))return this.emit(cF.ON_FALLBACK),!1}return this.reconnectWithAction(e,t)}return!0}}class fB extends mB{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){const n=LO(),i=function(e,t){return new _B(e,t)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{SL.debug("[choose-best-ws] close establishing websockets"),i.closeAllWebsockets(),n.reject(new ON(wN.WS_ABORT,"choose best websocket aborted"))};const r=xP("GATEWAY_DOMAINS");return SL.debug("[choose-best-ws] currentDomain: ",e,", domains: ",r,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),i.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,t).then(n.resolve).catch(n.reject),n.promise.finally((()=>{this.closeEstablishingWs=void 0}))}}class gB extends mB{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3&&void 0!==arguments[3]&&arguments[3],arguments.length>4&&void 0!==arguments[4]&&arguments[4],arguments.length>5?arguments[5]:void 0)}async chooseBestWebsocketConnection(e,t){return new cp(((n,i)=>{let r=!1;const o=[];this.closeEstablishingWs=()=>{SL.debug("[choose-best-ws] close establishing websockets"),o.forEach((e=>{e.onclose=null,e.onopen=null,e.onmessage=null,e.close()})),i(new ON(wN.WS_ABORT,"choose best websocket aborted"))};const s=xP("GATEWAY_DOMAINS");let a;const c=e.indexOf("?h="),d=s.find((t=>-1!==c?Ui(e).call(e,t,c):Ui(e).call(e,t)));SL.debug("[choose-best-ws] currentDomain: ",d,", domains: ",s);let l=!this.tryDoubleDomain||!d;if(!l&&d){var u;const h=Date.now();try{s.forEach((t=>{const n=-1===c?e.replace(d,t):e.substr(0,c)+e.substr(c).replace(d,t),i=new WebSocket(n);i.binaryType="arraybuffer",o.push(i),SL.debug("[choose-best-ws] ws is connecting:",i.url)}))}catch(e){for(SL.debug("[choose-best-ws] ws create failed, fallback to single url"),o.forEach((e=>e.close()));o.length;)o.pop();l=!0}null===(u=this.store)||void 0===u||u.recordJoinChannelService({urls:o.map((e=>e.url)),service:"gateway"},t),o.forEach((e=>{e.onopen=()=>{if(r)return;const t=Date.now()-h;SL.debug("[choose-best-ws] ws open cost ".concat(t,"ms")),o.filter((t=>t!==e)).forEach((e=>{SL.debug("[choose-best-ws]close backup websocket: ".concat(e.url)),e.close()})),r=!0,n(e)},e.onclose=e=>{if(a=e,r)return;o.find((e=>!(e.readyState===WebSocket.CLOSED||e.readyState===WebSocket.CLOSING)))||(SL.debug("[choose-best-ws] all websocket is closed"),r=!0,i(a))},e.onmessage=t=>{SL.debug("[choose-best-ws]".concat(e.url," onmessage: ").concat(t.data))}})),LD(this.forceCloseTimeout).then((()=>{o.forEach((e=>{e.readyState!==WebSocket.OPEN&&e.close()}))}))}if(l){var h;let r;SL.debug("[choose-best-ws] use single url: ",e),null===(h=this.store)||void 0===h||h.recordJoinChannelService({urls:[e],service:"gateway"},t);try{r=new WebSocket(e),o.push(r),r.binaryType="arraybuffer"}catch(e){const t=new ON(wN.WS_ERR,"init websocket failed! Error: ".concat(e.toString()));return SL.error("[".concat(this.name,"]").concat(t)),void i(t)}r.onopen=()=>{n(r)},r.onclose=e=>{i(e)},r.onmessage=e=>{SL.debug("[choose-best-ws]".concat(r.url," onmessage: ").concat(e.data))},LD(this.forceCloseTimeout).then((()=>{r&&r.readyState!==WebSocket.OPEN&&r.close()}))}})).then((e=>(this.closeEstablishingWs=void 0,e))).catch((e=>{throw this.closeEstablishingWs=void 0,e}))}}class SB extends YN{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===nF.CONNECTED?this.emit(iF.WS_CONNECTED):e===nF.RECONNECTING?this.emit(iF.WS_RECONNECTING,this._websocketReconnectReason):e===nF.CLOSED&&this.emit(iF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get reportUrl(){return this.websocket&&this.websocket.reportUrl||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),zA(this,"__name__","AgoraRTCSignal"),zA(this,"_disconnectedReason",void 0),zA(this,"_websocketReconnectReason",void 0),zA(this,"reconnectingFromConnecting",!1),zA(this,"_connectionState",nF.CLOSED),zA(this,"reconnectToken",void 0),zA(this,"websocket",void 0),zA(this,"openConnectionTime",void 0),zA(this,"clientId",void 0),zA(this,"lastMsgTime",Date.now()),zA(this,"uploadCache",[]),zA(this,"uploadCacheInterval",void 0),zA(this,"rttRolling",new eP(5)),zA(this,"pingpongTimer",void 0),zA(this,"wsInflateDataTimer",void 0),zA(this,"pingpongTimeoutCount",0),zA(this,"ortc",void 0),zA(this,"joinResponse",void 0),zA(this,"multiIpOption",void 0),zA(this,"initError",void 0),zA(this,"spec",void 0),zA(this,"store",void 0),zA(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(iF.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){if(this.emit(t._type,t._message),t._type===sF.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===sF.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close($N.UID_BANNED);break;case 15:this.close($N.IP_BANNED);break;case 16:this.close($N.CHANNEL_BANNED)}if(t._type===sF.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case tF.ERR_LICENSE_MISSING:this.close($N.LICENSE_MISSING);break;case tF.ERR_LICENSE_EXPIRED:this.close($N.LICENSE_EXPIRED);break;case tF.ERR_LICENSE_MINUTES_EXCEEDED:this.close($N.LICENSE_MINUTES_EXCEEDED);break;case tF.ERR_LICENSE_PERIOD_INVALID:this.close($N.LICENSE_PERIOD_INVALID);break;case tF.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close($N.LICENSE_MULTIPLE_SDK_SERVICE);break;case tF.ERR_LICENSE_ILLEGAL:this.close($N.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new fB("gateway-".concat(this.clientId),this.spec.retryConfig,!0,xP("JOIN_GATEWAY_USE_DUAL_DOMAIN"),xP("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===nF.CONNECTED&&this.reconnect("retry",sD.OFFLINE)}))}async request(e,t,n,i){const r=kD(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new cp(((t,n)=>{if(this.connectionState===nF.CONNECTED)return t();const i=()=>{this.off(iF.WS_CLOSED,r),t()},r=()=>{this.off(iF.WS_CONNECTED,i),n(new YL(wN.WS_ABORT))};this.once(iF.WS_CONNECTED,i),this.once(iF.WS_CLOSED,r),e!==rF.PUBLISH&&e!==rF.PUBLISH_DATASTREAM&&e!==rF.SUBSCRIBE&&e!==rF.SUBSCRIBE_DATASTREAM&&e!==rF.UNSUBSCRIBE&&e!==rF.UNSUBSCRIBE_DATASTREAM&&e!==rF.UNPUBLISH&&e!==rF.UNPUBLISH_DATASTREAM&&e!==rF.CONTROL&&e!==rF.RESTART_ICE||this.once(iF.DISCONNECT_P2P,(()=>{n(new YL(wN.DISCONNECT_P2P))})),e!==rF.PUBLISH&&e!==rF.RESTART_ICE||this.once(iF.ABORT_P2P_EXECUTION,(()=>{n(new YL(wN.DISCONNECT_P2P))}))}));if(this.connectionState!==nF.CONNECTING&&this.connectionState!==nF.RECONNECTING||e===rF.JOIN||e===rF.REJOIN||await a(),this.websocket.sendMessage(o,!0),i)return;const c=new cp(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(iF.WS_CLOSED,c),this.off(iF.WS_RECONNECTING,c),this.emit(iF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new YL(wN.WS_ABORT,"type: ".concat(e))),this.off(iF.WS_CLOSED,c),this.off(iF.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(iF.WS_CLOSED,c),this.once(iF.WS_RECONNECTING,c),LD(xP("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(SL.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(iF.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===nF.CLOSED||e===rF.LEAVE)throw new YL(wN.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===rF.JOIN||e===rF.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=oB(l),h=new YL(wN.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(SL.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===tF.ERR_TOO_MANY_BROADCASTERS?e===rF.JOIN||e===rF.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===tF.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,SL.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",sD.MULTI_IP)):this.reconnect(u.action,sD.SERVER_ERROR),e===rF.JOIN||e===rF.REJOIN?null:e===rF.RESTART_ICE&&n?h.throw():await this.request(e,t)))}waitMessage(e,t){return new cp((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void SL.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(oF.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=xP("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==nF.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),xP("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const n={_type:e,_message:t};this.websocket.sendMessage(n)}init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,this.reconnectingFromConnecting=!1,new cp(((n,i)=>{this.once(iF.WS_CONNECTED,(()=>n(this.joinResponse))),this.once(iF.WS_CLOSED,(e=>i(this.initError||new YL(wN.WS_ABORT,e)))),this.connectionState=nF.CONNECTING,this.websocket.init(e,5e3,t).catch(i),this.wsInflateDataTimer&&window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=window.setInterval((()=>{this.handleWsInflateData()}),2e4)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.wsInflateDataTimer&&(this.handleWsInflateData(),window.clearInterval(this.wsInflateDataTimer),this.wsInflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._disconnectedReason=e||$N.LEAVE,this.connectionState=nF.CLOSED,SL.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}async join(){if(!this.joinResponse){this.websocket.isFirstJoin&&!0===uD(this,iF.SHOULD_ENTER_RECONNECTING,void 0)||this.emit(iF.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await dD(this,iF.REQUEST_JOIN_INFO);this.store.joinReq();const t=await this.request(rF.JOIN,e);if(this.ortc=null==e?void 0:e.ortc,this.store.joinRep(),!t)return this.emit(iF.REPORT_JOIN_GATEWAY,IF.TIMEOUT,this.reportUrl||""),!1;this.joinResponse=t,this.emit(iF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.websocket.disableQueryReconnectingWhenConnecting(),this.connectionState=nF.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}async rejoin(){if(!this.reconnectToken)throw new YL(wN.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=hD(this,iF.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(rF.REJOIN,e);return!!t&&(this.connectionState=nF.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),t.peers&&t.peers.forEach((e=>{this.emit(sF.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(sF.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(sF.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(sF.MUTE_AUDIO,{uid:e.uid}):this.emit(sF.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(sF.MUTE_VIDEO,{uid:e.uid}):this.emit(sF.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(sF.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(sF.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(sF.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(sF.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(sF.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(rF.DOWNGRADE_CODEC,t)}handleNotification(e){SL.debug("[".concat(this.clientId,"] receive notification: "),e);const t=oB(e.code);if(28===e.code&&"detail"in e&&(SL.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(iF.RECOVER_NOTIFICATION,e.detail)),"success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===tF.ERR_REPEAT_JOIN_CHANNEL&&xP("IGNORE_UID_CHECK")?void this.close($N.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close($N.UID_BANNED),void this.close()):e.code===tF.K_VOS_FALLBACK&&"detail"in e?(SL.info("[".concat(this.clientId,"] receive vos fallback notification: "),e.detail),"FALLBACKCN"===e.detail&&xP("ENABLE_QUALITY_FALLBACK")?void dD(this,iF.VOS_FALLBACK_PROMISE,e.detail).then((()=>{this.reconnect("recover",t.desc)})).catch((e=>{SL.debug("[".concat(this.clientId,"] cancel vos fallback cn, error: "),e)})):"fallback_hls"===e.detail&&xP("ENABLE_FALLBACK_TO_HLS")?(this.emit(iF.VOS_FALLBACK,e.detail),void this.close($N.FALLBACK_TO_HLS)):this.reconnect(t.action,t.desc)):void this.reconnect(t.action,sD.SERVER_ERROR);SL.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=xP("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(SL.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>xP("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",sD.TIMEOUT):this.request(rF.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),xP("REPORT_STATS")&&this.send(rF.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWsInflateData(){const e=this.websocket.getWsInflateData(),t=e.wsInflateLength,n=e.wsDeflateLength;0!==t&&0!==n&&this.upload(oF.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(cF.SHOULD_ENTER_RECONNECTING,((e,t)=>{const n=!0===uD(this,iF.SHOULD_ENTER_RECONNECTING,e);this.reconnectingFromConnecting=n,t(n)})),this.websocket.on(cF.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(iF.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(cF.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(cF.CLOSED,(()=>{this.connectionState=nF.CLOSED})),this.websocket.on(cF.FAILED,(()=>{this._disconnectedReason=$N.NETWORK_ERROR,this.connectionState=nF.CLOSED})),this.websocket.on(cF.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===nF.CONNECTED||this.reconnectingFromConnecting?this.connectionState=nF.RECONNECTING:this.connectionState=nF.CONNECTING,this.reconnectingFromConnecting=!1})),this.websocket.on(cF.WILL_RECONNECT,((e,t,n)=>{const i=hD(this,iF.IS_P2P_DISCONNECTED),r=i||"retry"!==e;i&&"retry"===e&&(SL.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",t=IF.P2P_DISCONNECTED),r&&(SL.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(iF.REPORT_JOIN_GATEWAY,t||IF.UNKNOWN_REASON,this.reportUrl||""),this.reconnectToken=void 0,this.emit(iF.DISCONNECT_P2P)),"retry"!==e&&this.store.flexiblePC&&(this.store.flexiblePC=!1),n(e)})),this.websocket.on(cF.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{SL.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",sD.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(iF.REPORT_JOIN_GATEWAY,e,this.reportUrl||""),e instanceof YL){if(e.code===wN.UNEXPECTED_RESPONSE&&e.data.code===tF.ERR_NO_AUTHORIZED)return this.initError=new YL(wN.TOKEN_EXPIRE,"dynamic key expired"),void this.close($N.TOKEN_EXPIRE);SL.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",sD.SERVER_ERROR):(this.initError=e,this.close())}}))})),this.websocket.on(cF.REQUEST_NEW_URLS,((e,t)=>{dD(this,iF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(cF.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(sF.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(cF.ON_FALLBACK,(()=>{xP("ENABLE_FALLBACK_TO_HLS")&&this.emit(iF.VOS_FALLBACK,"fallback_hls")}))}}var TB=l,RB=tb,vB=RegExp.prototype,yB=function(e){return e===vB||TB(vB,e)?RB(e):e.flags},CB=n(yB);function bB(e){let t=e.length;for(;--t>=0;)e[t]=0}const IB=256,AB=286,wB=30,OB=15,NB=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),DB=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),PB=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),LB=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),kB=new Array(576);bB(kB);const MB=new Array(60);bB(MB);const UB=new Array(512);bB(UB);const VB=new Array(256);bB(VB);const xB=new Array(29);bB(xB);const FB=new Array(wB);function BB(e,t,n,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=n,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}let jB,GB,WB;function KB(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}bB(FB);const HB=e=>e<256?UB[e]:UB[256+(e>>>7)],YB=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},XB=(e,t,n)=>{e.bi_valid>16-n?(e.bi_buf|=t<<e.bi_valid&65535,YB(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=n-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=n)},JB=(e,t,n)=>{XB(e,n[2*t],n[2*t+1])},zB=(e,t)=>{let n=0;do{n|=1&e,e>>>=1,n<<=1}while(--t>0);return n>>>1},ZB=(e,t,n)=>{const i=new Array(16);let r,o,s=0;for(r=1;r<=OB;r++)s=s+n[r-1]<<1,i[r]=s;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=zB(i[t]++,t))}},qB=e=>{let t;for(t=0;t<AB;t++)e.dyn_ltree[2*t]=0;for(t=0;t<wB;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},QB=e=>{e.bi_valid>8?YB(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},$B=(e,t,n,i)=>{const r=2*t,o=2*n;return e[r]<e[o]||e[r]===e[o]&&i[t]<=i[n]},ej=(e,t,n)=>{const i=e.heap[n];let r=n<<1;for(;r<=e.heap_len&&(r<e.heap_len&&$B(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!$B(t,i,e.heap[r],e.depth));)e.heap[n]=e.heap[r],n=r,r<<=1;e.heap[n]=i},tj=(e,t,n)=>{let i,r,o,s,a=0;if(0!==e.sym_next)do{i=255&e.pending_buf[e.sym_buf+a++],i+=(255&e.pending_buf[e.sym_buf+a++])<<8,r=e.pending_buf[e.sym_buf+a++],0===i?JB(e,r,t):(o=VB[r],JB(e,o+IB+1,t),s=NB[o],0!==s&&(r-=xB[o],XB(e,r,s)),i--,o=HB(i),JB(e,o,n),s=DB[o],0!==s&&(i-=FB[o],XB(e,i,s)))}while(a<e.sym_next);JB(e,256,t)},nj=(e,t)=>{const n=t.dyn_tree,i=t.stat_desc.static_tree,r=t.stat_desc.has_stree,o=t.stat_desc.elems;let s,a,c,d=-1;for(e.heap_len=0,e.heap_max=573,s=0;s<o;s++)0!==n[2*s]?(e.heap[++e.heap_len]=d=s,e.depth[s]=0):n[2*s+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=d<2?++d:0,n[2*c]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=i[2*c+1]);for(t.max_code=d,s=e.heap_len>>1;s>=1;s--)ej(e,n,s);c=o;do{s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],ej(e,n,1),a=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=a,n[2*c]=n[2*s]+n[2*a],e.depth[c]=(e.depth[s]>=e.depth[a]?e.depth[s]:e.depth[a])+1,n[2*s+1]=n[2*a+1]=c,e.heap[1]=c++,ej(e,n,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const n=t.dyn_tree,i=t.max_code,r=t.stat_desc.static_tree,o=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let d,l,u,h,p,_,E=0;for(h=0;h<=OB;h++)e.bl_count[h]=0;for(n[2*e.heap[e.heap_max]+1]=0,d=e.heap_max+1;d<573;d++)l=e.heap[d],h=n[2*n[2*l+1]+1]+1,h>c&&(h=c,E++),n[2*l+1]=h,l>i||(e.bl_count[h]++,p=0,l>=a&&(p=s[l-a]),_=n[2*l],e.opt_len+=_*(h+p),o&&(e.static_len+=_*(r[2*l+1]+p)));if(0!==E){do{for(h=c-1;0===e.bl_count[h];)h--;e.bl_count[h]--,e.bl_count[h+1]+=2,e.bl_count[c]--,E-=2}while(E>0);for(h=c;0!==h;h--)for(l=e.bl_count[h];0!==l;)u=e.heap[--d],u>i||(n[2*u+1]!==h&&(e.opt_len+=(h-n[2*u+1])*n[2*u],n[2*u+1]=h),l--)}})(e,t),ZB(n,d,e.bl_count)},ij=(e,t,n)=>{let i,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),t[2*(n+1)+1]=65535,i=0;i<=n;i++)r=s,s=t[2*(i+1)+1],++a<c&&r===s||(a<d?e.bl_tree[2*r]+=a:0!==r?(r!==o&&e.bl_tree[2*r]++,e.bl_tree[32]++):a<=10?e.bl_tree[34]++:e.bl_tree[36]++,a=0,o=r,0===s?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4))},rj=(e,t,n)=>{let i,r,o=-1,s=t[1],a=0,c=7,d=4;for(0===s&&(c=138,d=3),i=0;i<=n;i++)if(r=s,s=t[2*(i+1)+1],!(++a<c&&r===s)){if(a<d)do{JB(e,r,e.bl_tree)}while(0!=--a);else 0!==r?(r!==o&&(JB(e,r,e.bl_tree),a--),JB(e,16,e.bl_tree),XB(e,a-3,2)):a<=10?(JB(e,17,e.bl_tree),XB(e,a-3,3)):(JB(e,18,e.bl_tree),XB(e,a-11,7));a=0,o=r,0===s?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4)}};let oj=!1;const sj=(e,t,n,i)=>{XB(e,0+(i?1:0),3),QB(e),YB(e,n),YB(e,~n),n&&e.pending_buf.set(e.window.subarray(t,t+n),e.pending),e.pending+=n};var aj=e=>{oj||((()=>{let e,t,n,i,r;const o=new Array(16);for(n=0,i=0;i<28;i++)for(xB[i]=n,e=0;e<1<<NB[i];e++)VB[n++]=i;for(VB[n-1]=i,r=0,i=0;i<16;i++)for(FB[i]=r,e=0;e<1<<DB[i];e++)UB[r++]=i;for(r>>=7;i<wB;i++)for(FB[i]=r<<7,e=0;e<1<<DB[i]-7;e++)UB[256+r++]=i;for(t=0;t<=OB;t++)o[t]=0;for(e=0;e<=143;)kB[2*e+1]=8,e++,o[8]++;for(;e<=255;)kB[2*e+1]=9,e++,o[9]++;for(;e<=279;)kB[2*e+1]=7,e++,o[7]++;for(;e<=287;)kB[2*e+1]=8,e++,o[8]++;for(ZB(kB,287,o),e=0;e<wB;e++)MB[2*e+1]=5,MB[2*e]=zB(e,5);jB=new BB(kB,NB,257,AB,OB),GB=new BB(MB,DB,0,wB,OB),WB=new BB(new Array(0),PB,0,19,7)})(),oj=!0),e.l_desc=new KB(e.dyn_ltree,jB),e.d_desc=new KB(e.dyn_dtree,GB),e.bl_desc=new KB(e.bl_tree,WB),e.bi_buf=0,e.bi_valid=0,qB(e)},cj=(e,t,n,i)=>{let r,o,s=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,n=4093624447;for(t=0;t<=31;t++,n>>>=1)if(1&n&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<IB;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0})(e)),nj(e,e.l_desc),nj(e,e.d_desc),s=(e=>{let t;for(ij(e,e.dyn_ltree,e.l_desc.max_code),ij(e,e.dyn_dtree,e.d_desc.max_code),nj(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*LB[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),r=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=r&&(r=o)):r=o=n+5,n+4<=r&&-1!==t?sj(e,t,n,i):4===e.strategy||o===r?(XB(e,2+(i?1:0),3),tj(e,kB,MB)):(XB(e,4+(i?1:0),3),((e,t,n,i)=>{let r;for(XB(e,t-257,5),XB(e,n-1,5),XB(e,i-4,4),r=0;r<i;r++)XB(e,e.bl_tree[2*LB[r]+1],3);rj(e,e.dyn_ltree,t-1),rj(e,e.dyn_dtree,n-1)})(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),tj(e,e.dyn_ltree,e.dyn_dtree)),qB(e),i&&QB(e)},dj=(e,t,n)=>(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=n,0===t?e.dyn_ltree[2*n]++:(e.matches++,t--,e.dyn_ltree[2*(VB[n]+IB+1)]++,e.dyn_dtree[2*HB(t)]++),e.sym_next===e.sym_end),lj=e=>{XB(e,2,3),JB(e,256,kB),(e=>{16===e.bi_valid?(YB(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)},uj={_tr_init:aj,_tr_stored_block:sj,_tr_flush_block:cj,_tr_tally:dj,_tr_align:lj};var hj=(e,t,n,i)=>{let r=65535&e|0,o=e>>>16&65535|0,s=0;for(;0!==n;){s=n>2e3?2e3:n,n-=s;do{r=r+t[i++]|0,o=o+r|0}while(--s);r%=65521,o%=65521}return r|o<<16|0};const pj=new Uint32Array((()=>{let e,t=[];for(var n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t})());var _j=(e,t,n,i)=>{const r=pj,o=i+n;e^=-1;for(let n=i;n<o;n++)e=e>>>8^r[255&(e^t[n])];return-1^e},Ej={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},mj={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const fj=uj._tr_init,gj=uj._tr_stored_block,Sj=uj._tr_flush_block,Tj=uj._tr_tally,Rj=uj._tr_align,vj=mj.Z_NO_FLUSH,yj=mj.Z_PARTIAL_FLUSH,Cj=mj.Z_FULL_FLUSH,bj=mj.Z_FINISH,Ij=mj.Z_BLOCK,Aj=mj.Z_OK,wj=mj.Z_STREAM_END,Oj=mj.Z_STREAM_ERROR,Nj=mj.Z_DATA_ERROR,Dj=mj.Z_BUF_ERROR,Pj=mj.Z_DEFAULT_COMPRESSION,Lj=mj.Z_FILTERED,kj=mj.Z_HUFFMAN_ONLY,Mj=mj.Z_RLE,Uj=mj.Z_FIXED,Vj=mj.Z_DEFAULT_STRATEGY,xj=mj.Z_UNKNOWN,Fj=mj.Z_DEFLATED,Bj=286,jj=30,Gj=19,Wj=2*Bj+1,Kj=15,Hj=258,Yj=262,Xj=42,Jj=113,zj=666,Zj=(e,t)=>(e.msg=Ej[t],t),qj=e=>2*e-(e>4?9:0),Qj=e=>{let t=e.length;for(;--t>=0;)e[t]=0},$j=e=>{let t,n,i,r=e.w_size;t=e.hash_size,i=t;do{n=e.head[--i],e.head[i]=n>=r?n-r:0}while(--t);t=r,i=t;do{n=e.prev[--i],e.prev[i]=n>=r?n-r:0}while(--t)};let eG=(e,t,n)=>(t<<e.hash_shift^n)&e.hash_mask;const tG=e=>{const t=e.state;let n=t.pending;n>e.avail_out&&(n=e.avail_out),0!==n&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+n),e.next_out),e.next_out+=n,t.pending_out+=n,e.total_out+=n,e.avail_out-=n,t.pending-=n,0===t.pending&&(t.pending_out=0))},nG=(e,t)=>{Sj(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,tG(e.strm)},iG=(e,t)=>{e.pending_buf[e.pending++]=t},rG=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},oG=(e,t,n,i)=>{let r=e.avail_in;return r>i&&(r=i),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),n),1===e.state.wrap?e.adler=hj(e.adler,t,r,n):2===e.state.wrap&&(e.adler=_j(e.adler,t,r,n)),e.next_in+=r,e.total_in+=r,r)},sG=(e,t)=>{let n,i,r=e.max_chain_length,o=e.strstart,s=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-Yj?e.strstart-(e.w_size-Yj):0,d=e.window,l=e.w_mask,u=e.prev,h=e.strstart+Hj;let p=d[o+s-1],_=d[o+s];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(n=t,d[n+s]===_&&d[n+s-1]===p&&d[n]===d[o]&&d[++n]===d[o+1]){o+=2,n++;do{}while(d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&d[++o]===d[++n]&&o<h);if(i=Hj-(h-o),o=h-Hj,i>s){if(e.match_start=t,s=i,i>=a)break;p=d[o+s-1],_=d[o+s]}}}while((t=u[t&l])>c&&0!=--r);return s<=e.lookahead?s:e.lookahead},aG=e=>{const t=e.w_size;let n,i,r;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Yj)&&(e.window.set(e.window.subarray(t,t+t-i),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),$j(e),i+=t),0===e.strm.avail_in)break;if(n=oG(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=n,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=eG(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=eG(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<Yj&&0!==e.strm.avail_in)},cG=(e,t)=>{let n,i,r,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,s=0,a=e.strm.avail_in;do{if(n=65535,r=e.bi_valid+42>>3,e.strm.avail_out<r)break;if(r=e.strm.avail_out-r,i=e.strstart-e.block_start,n>i+e.strm.avail_in&&(n=i+e.strm.avail_in),n>r&&(n=r),n<o&&(0===n&&t!==bj||t===vj||n!==i+e.strm.avail_in))break;s=t===bj&&n===i+e.strm.avail_in?1:0,gj(e,0,0,s),e.pending_buf[e.pending-4]=n,e.pending_buf[e.pending-3]=n>>8,e.pending_buf[e.pending-2]=~n,e.pending_buf[e.pending-1]=~n>>8,tG(e.strm),i&&(i>n&&(i=n),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+i),e.strm.next_out),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i,e.block_start+=i,n-=i),n&&(oG(e.strm,e.strm.output,e.strm.next_out,n),e.strm.next_out+=n,e.strm.avail_out-=n,e.strm.total_out+=n)}while(0===s);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_water<e.strstart&&(e.high_water=e.strstart),s?4:t!==vj&&t!==bj&&0===e.strm.avail_in&&e.strstart===e.block_start?2:(r=e.window_size-e.strstart,e.strm.avail_in>r&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(oG(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water<e.strstart&&(e.high_water=e.strstart),r=e.bi_valid+42>>3,r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r,o=r>e.w_size?e.w_size:r,i=e.strstart-e.block_start,(i>=o||(i||t===bj)&&t!==vj&&0===e.strm.avail_in&&i<=r)&&(n=i>r?r:i,s=t===bj&&0===e.strm.avail_in&&n===i?1:0,gj(e,e.block_start,n,s),e.block_start+=n,tG(e.strm)),s?3:1)},dG=(e,t)=>{let n,i;for(;;){if(e.lookahead<Yj){if(aG(e),e.lookahead<Yj&&t===vj)return 1;if(0===e.lookahead)break}if(n=0,e.lookahead>=3&&(e.ins_h=eG(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==n&&e.strstart-n<=e.w_size-Yj&&(e.match_length=sG(e,n)),e.match_length>=3)if(i=Tj(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=eG(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=eG(e,e.ins_h,e.window[e.strstart+1]);else i=Tj(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(nG(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===bj?(nG(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nG(e,!1),0===e.strm.avail_out)?1:2},lG=(e,t)=>{let n,i,r;for(;;){if(e.lookahead<Yj){if(aG(e),e.lookahead<Yj&&t===vj)return 1;if(0===e.lookahead)break}if(n=0,e.lookahead>=3&&(e.ins_h=eG(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==n&&e.prev_length<e.max_lazy_match&&e.strstart-n<=e.w_size-Yj&&(e.match_length=sG(e,n),e.match_length<=5&&(e.strategy===Lj||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,i=Tj(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=eG(e,e.ins_h,e.window[e.strstart+3-1]),n=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,i&&(nG(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(i=Tj(e,0,e.window[e.strstart-1]),i&&nG(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=Tj(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===bj?(nG(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nG(e,!1),0===e.strm.avail_out)?1:2};function uG(e,t,n,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=n,this.max_chain=i,this.func=r}const hG=[new uG(0,0,0,0,cG),new uG(4,4,8,4,dG),new uG(4,5,16,8,dG),new uG(4,6,32,32,dG),new uG(4,4,16,16,lG),new uG(8,16,32,32,lG),new uG(8,16,128,128,lG),new uG(8,32,128,256,lG),new uG(32,128,258,1024,lG),new uG(32,258,258,4096,lG)];function pG(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Fj,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(2*Wj),this.dyn_dtree=new Uint16Array(2*(2*jj+1)),this.bl_tree=new Uint16Array(2*(2*Gj+1)),Qj(this.dyn_ltree),Qj(this.dyn_dtree),Qj(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(Kj+1),this.heap=new Uint16Array(2*Bj+1),Qj(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*Bj+1),Qj(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const _G=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==Xj&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==Jj&&t.status!==zj?1:0},EG=e=>{if(_G(e))return Zj(e,Oj);e.total_in=e.total_out=0,e.data_type=xj;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?Xj:Jj,e.adler=2===t.wrap?0:1,t.last_flush=-2,fj(t),Aj},mG=e=>{const t=EG(e);return t===Aj&&(e=>{e.window_size=2*e.w_size,Qj(e.head),e.max_lazy_match=hG[e.level].max_lazy,e.good_match=hG[e.level].good_length,e.nice_match=hG[e.level].nice_length,e.max_chain_length=hG[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0})(e.state),t},fG=(e,t,n,i,r,o)=>{if(!e)return Oj;let s=1;if(t===Pj&&(t=6),i<0?(s=0,i=-i):i>15&&(s=2,i-=16),r<1||r>9||n!==Fj||i<8||i>15||t<0||t>9||o<0||o>Uj||8===i&&1!==s)return Zj(e,Oj);8===i&&(i=9);const a=new pG;return e.state=a,a.strm=e,a.status=Xj,a.wrap=s,a.gzhead=null,a.w_bits=i,a.w_size=1<<a.w_bits,a.w_mask=a.w_size-1,a.hash_bits=r+7,a.hash_size=1<<a.hash_bits,a.hash_mask=a.hash_size-1,a.hash_shift=~~((a.hash_bits+3-1)/3),a.window=new Uint8Array(2*a.w_size),a.head=new Uint16Array(a.hash_size),a.prev=new Uint16Array(a.w_size),a.lit_bufsize=1<<r+6,a.pending_buf_size=4*a.lit_bufsize,a.pending_buf=new Uint8Array(a.pending_buf_size),a.sym_buf=a.lit_bufsize,a.sym_end=3*(a.lit_bufsize-1),a.level=t,a.strategy=o,a.method=n,mG(e)};var gG=(e,t)=>{if(_G(e)||t>Ij||t<0)return e?Zj(e,Oj):Oj;const n=e.state;if(!e.output||0!==e.avail_in&&!e.input||n.status===zj&&t!==bj)return Zj(e,0===e.avail_out?Dj:Oj);const i=n.last_flush;if(n.last_flush=t,0!==n.pending){if(tG(e),0===e.avail_out)return n.last_flush=-1,Aj}else if(0===e.avail_in&&qj(t)<=qj(i)&&t!==bj)return Zj(e,Dj);if(n.status===zj&&0!==e.avail_in)return Zj(e,Dj);if(n.status===Xj&&0===n.wrap&&(n.status=Jj),n.status===Xj){let t=Fj+(n.w_bits-8<<4)<<8,i=-1;if(i=n.strategy>=kj||n.level<2?0:n.level<6?1:6===n.level?2:3,t|=i<<6,0!==n.strstart&&(t|=32),t+=31-t%31,rG(n,t),0!==n.strstart&&(rG(n,e.adler>>>16),rG(n,65535&e.adler)),e.adler=1,n.status=Jj,tG(e),0!==n.pending)return n.last_flush=-1,Aj}if(57===n.status)if(e.adler=0,iG(n,31),iG(n,139),iG(n,8),n.gzhead)iG(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),iG(n,255&n.gzhead.time),iG(n,n.gzhead.time>>8&255),iG(n,n.gzhead.time>>16&255),iG(n,n.gzhead.time>>24&255),iG(n,9===n.level?2:n.strategy>=kj||n.level<2?4:0),iG(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(iG(n,255&n.gzhead.extra.length),iG(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=_j(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69;else if(iG(n,0),iG(n,0),iG(n,0),iG(n,0),iG(n,0),iG(n,9===n.level?2:n.strategy>=kj||n.level<2?4:0),iG(n,3),n.status=Jj,tG(e),0!==n.pending)return n.last_flush=-1,Aj;if(69===n.status){if(n.gzhead.extra){let t=n.pending,i=(65535&n.gzhead.extra.length)-n.gzindex;for(;n.pending+i>n.pending_buf_size;){let r=n.pending_buf_size-n.pending;if(n.pending_buf.set(n.gzhead.extra.subarray(n.gzindex,n.gzindex+r),n.pending),n.pending=n.pending_buf_size,n.gzhead.hcrc&&n.pending>t&&(e.adler=_j(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex+=r,tG(e),0!==n.pending)return n.last_flush=-1,Aj;t=0,i-=r}let r=new Uint8Array(n.gzhead.extra);n.pending_buf.set(r.subarray(n.gzindex,n.gzindex+i),n.pending),n.pending+=i,n.gzhead.hcrc&&n.pending>t&&(e.adler=_j(e.adler,n.pending_buf,n.pending-t,t)),n.gzindex=0}n.status=73}if(73===n.status){if(n.gzhead.name){let t,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(e.adler=_j(e.adler,n.pending_buf,n.pending-i,i)),tG(e),0!==n.pending)return n.last_flush=-1,Aj;i=0}t=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,iG(n,t)}while(0!==t);n.gzhead.hcrc&&n.pending>i&&(e.adler=_j(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex=0}n.status=91}if(91===n.status){if(n.gzhead.comment){let t,i=n.pending;do{if(n.pending===n.pending_buf_size){if(n.gzhead.hcrc&&n.pending>i&&(e.adler=_j(e.adler,n.pending_buf,n.pending-i,i)),tG(e),0!==n.pending)return n.last_flush=-1,Aj;i=0}t=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,iG(n,t)}while(0!==t);n.gzhead.hcrc&&n.pending>i&&(e.adler=_j(e.adler,n.pending_buf,n.pending-i,i))}n.status=103}if(103===n.status){if(n.gzhead.hcrc){if(n.pending+2>n.pending_buf_size&&(tG(e),0!==n.pending))return n.last_flush=-1,Aj;iG(n,255&e.adler),iG(n,e.adler>>8&255),e.adler=0}if(n.status=Jj,tG(e),0!==n.pending)return n.last_flush=-1,Aj}if(0!==e.avail_in||0!==n.lookahead||t!==vj&&n.status!==zj){let i=0===n.level?cG(n,t):n.strategy===kj?((e,t)=>{let n;for(;;){if(0===e.lookahead&&(aG(e),0===e.lookahead)){if(t===vj)return 1;break}if(e.match_length=0,n=Tj(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,n&&(nG(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===bj?(nG(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nG(e,!1),0===e.strm.avail_out)?1:2})(n,t):n.strategy===Mj?((e,t)=>{let n,i,r,o;const s=e.window;for(;;){if(e.lookahead<=Hj){if(aG(e),e.lookahead<=Hj&&t===vj)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=e.strstart-1,i=s[r],i===s[++r]&&i===s[++r]&&i===s[++r])){o=e.strstart+Hj;do{}while(i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&i===s[++r]&&r<o);e.match_length=Hj-(o-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(n=Tj(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(n=Tj(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),n&&(nG(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===bj?(nG(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(nG(e,!1),0===e.strm.avail_out)?1:2})(n,t):hG[n.level].func(n,t);if(3!==i&&4!==i||(n.status=zj),1===i||3===i)return 0===e.avail_out&&(n.last_flush=-1),Aj;if(2===i&&(t===yj?Rj(n):t!==Ij&&(gj(n,0,0,!1),t===Cj&&(Qj(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),tG(e),0===e.avail_out))return n.last_flush=-1,Aj}return t!==bj?Aj:n.wrap<=0?wj:(2===n.wrap?(iG(n,255&e.adler),iG(n,e.adler>>8&255),iG(n,e.adler>>16&255),iG(n,e.adler>>24&255),iG(n,255&e.total_in),iG(n,e.total_in>>8&255),iG(n,e.total_in>>16&255),iG(n,e.total_in>>24&255)):(rG(n,e.adler>>>16),rG(n,65535&e.adler)),tG(e),n.wrap>0&&(n.wrap=-n.wrap),0!==n.pending?Aj:wj)},SG=(e,t)=>{let n=t.length;if(_G(e))return Oj;const i=e.state,r=i.wrap;if(2===r||1===r&&i.status!==Xj||i.lookahead)return Oj;if(1===r&&(e.adler=hj(e.adler,t,n,0)),i.wrap=0,n>=i.w_size){0===r&&(Qj(i.head),i.strstart=0,i.block_start=0,i.insert=0);let e=new Uint8Array(i.w_size);e.set(t.subarray(n-i.w_size,n),0),t=e,n=i.w_size}const o=e.avail_in,s=e.next_in,a=e.input;for(e.avail_in=n,e.next_in=0,e.input=t,aG(i);i.lookahead>=3;){let e=i.strstart,t=i.lookahead-2;do{i.ins_h=eG(i,i.ins_h,i.window[e+3-1]),i.prev[e&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=e,e++}while(--t);i.strstart=e,i.lookahead=2,aG(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=s,e.input=a,e.avail_in=o,i.wrap=r,Aj},TG={deflateInit:(e,t)=>fG(e,t,Fj,15,8,Vj),deflateInit2:fG,deflateReset:mG,deflateResetKeep:EG,deflateSetHeader:(e,t)=>_G(e)||2!==e.state.wrap?Oj:(e.state.gzhead=t,Aj),deflate:gG,deflateEnd:e=>{if(_G(e))return Oj;const t=e.state.status;return e.state=null,t===Jj?Zj(e,Nj):Aj},deflateSetDictionary:SG,deflateInfo:"pako deflate (from Nodeca project)"};const RG=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var vG={assign:function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if("object"!=typeof n)throw new TypeError(n+"must be non-object");for(const t in n)RG(n,t)&&(e[t]=n[t])}}return e},flattenChunks:e=>{let t=0;for(let n=0,i=e.length;n<i;n++)t+=e[n].length;const n=new Uint8Array(t);for(let t=0,i=0,r=e.length;t<r;t++){let r=e[t];n.set(r,i),i+=r.length}return n}};let yG=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){yG=!1}const CG=new Uint8Array(256);for(let e=0;e<256;e++)CG[e]=e>=252?6:e>=248?5:e>=240?4:e>=224?3:e>=192?2:1;CG[254]=CG[254]=1;var bG={string2buf:e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,n,i,r,o,s=e.length,a=0;for(r=0;r<s;r++)n=e.charCodeAt(r),55296==(64512&n)&&r+1<s&&(i=e.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),a+=n<128?1:n<2048?2:n<65536?3:4;for(t=new Uint8Array(a),o=0,r=0;o<a;r++)n=e.charCodeAt(r),55296==(64512&n)&&r+1<s&&(i=e.charCodeAt(r+1),56320==(64512&i)&&(n=65536+(n-55296<<10)+(i-56320),r++)),n<128?t[o++]=n:n<2048?(t[o++]=192|n>>>6,t[o++]=128|63&n):n<65536?(t[o++]=224|n>>>12,t[o++]=128|n>>>6&63,t[o++]=128|63&n):(t[o++]=240|n>>>18,t[o++]=128|n>>>12&63,t[o++]=128|n>>>6&63,t[o++]=128|63&n);return t},buf2string:(e,t)=>{const n=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let i,r;const o=new Array(2*n);for(r=0,i=0;i<n;){let t=e[i++];if(t<128){o[r++]=t;continue}let s=CG[t];if(s>4)o[r++]=65533,i+=s-1;else{for(t&=2===s?31:3===s?15:7;s>1&&i<n;)t=t<<6|63&e[i++],s--;s>1?o[r++]=65533:t<65536?o[r++]=t:(t-=65536,o[r++]=55296|t>>10&1023,o[r++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&yG)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let n="";for(let i=0;i<t;i++)n+=String.fromCharCode(e[i]);return n})(o,r)},utf8border:(e,t)=>{(t=t||e.length)>e.length&&(t=e.length);let n=t-1;for(;n>=0&&128==(192&e[n]);)n--;return n<0||0===n?t:n+CG[e[n]]>t?n:t}};var IG=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const AG=Object.prototype.toString,wG=mj.Z_NO_FLUSH,OG=mj.Z_SYNC_FLUSH,NG=mj.Z_FULL_FLUSH,DG=mj.Z_FINISH,PG=mj.Z_OK,LG=mj.Z_STREAM_END,kG=mj.Z_DEFAULT_COMPRESSION,MG=mj.Z_DEFAULT_STRATEGY,UG=mj.Z_DEFLATED;function VG(e){this.options=vG.assign({level:kG,method:UG,chunkSize:16384,windowBits:15,memLevel:8,strategy:MG},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new IG,this.strm.avail_out=0;let n=TG.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==PG)throw new Error(Ej[n]);if(t.header&&TG.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?bG.string2buf(t.dictionary):"[object ArrayBuffer]"===AG.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,n=TG.deflateSetDictionary(this.strm,e),n!==PG)throw new Error(Ej[n]);this._dict_set=!0}}function xG(e,t){const n=new VG(t);if(n.push(e,!0),n.err)throw n.msg||Ej[n.err];return n.result}VG.prototype.push=function(e,t){const n=this.strm,i=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?DG:wG,"string"==typeof e?n.input=bG.string2buf(e):"[object ArrayBuffer]"===AG.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;)if(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),(o===OG||o===NG)&&n.avail_out<=6)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else{if(r=TG.deflate(n,o),r===LG)return n.next_out>0&&this.onData(n.output.subarray(0,n.next_out)),r=TG.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===PG;if(0!==n.avail_out){if(o>0&&n.next_out>0)this.onData(n.output.subarray(0,n.next_out)),n.avail_out=0;else if(0===n.avail_in)break}else this.onData(n.output)}return!0},VG.prototype.onData=function(e){this.chunks.push(e)},VG.prototype.onEnd=function(e){e===PG&&(this.result=vG.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var FG={Deflate:VG,deflate:xG,deflateRaw:function(e,t){return(t=t||{}).raw=!0,xG(e,t)},gzip:function(e,t){return(t=t||{}).gzip=!0,xG(e,t)},constants:mj};const BG=16209;var jG=function(e,t){let n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,C,b;const I=e.state;n=e.next_in,C=e.input,i=n+(e.avail_in-5),r=e.next_out,b=e.output,o=r-(t-e.avail_out),s=r+(e.avail_out-257),a=I.dmax,c=I.wsize,d=I.whave,l=I.wnext,u=I.window,h=I.hold,p=I.bits,_=I.lencode,E=I.distcode,m=(1<<I.lenbits)-1,f=(1<<I.distbits)-1;e:do{p<15&&(h+=C[n++]<<p,p+=8,h+=C[n++]<<p,p+=8),g=_[h&m];t:for(;;){if(S=g>>>24,h>>>=S,p-=S,S=g>>>16&255,0===S)b[r++]=65535&g;else{if(!(16&S)){if(0==(64&S)){g=_[(65535&g)+(h&(1<<S)-1)];continue t}if(32&S){I.mode=16191;break e}e.msg="invalid literal/length code",I.mode=BG;break e}T=65535&g,S&=15,S&&(p<S&&(h+=C[n++]<<p,p+=8),T+=h&(1<<S)-1,h>>>=S,p-=S),p<15&&(h+=C[n++]<<p,p+=8,h+=C[n++]<<p,p+=8),g=E[h&f];n:for(;;){if(S=g>>>24,h>>>=S,p-=S,S=g>>>16&255,!(16&S)){if(0==(64&S)){g=E[(65535&g)+(h&(1<<S)-1)];continue n}e.msg="invalid distance code",I.mode=BG;break e}if(R=65535&g,S&=15,p<S&&(h+=C[n++]<<p,p+=8,p<S&&(h+=C[n++]<<p,p+=8)),R+=h&(1<<S)-1,R>a){e.msg="invalid distance too far back",I.mode=BG;break e}if(h>>>=S,p-=S,S=r-o,R>S){if(S=R-S,S>d&&I.sane){e.msg="invalid distance too far back",I.mode=BG;break e}if(v=0,y=u,0===l){if(v+=c-S,S<T){T-=S;do{b[r++]=u[v++]}while(--S);v=r-R,y=b}}else if(l<S){if(v+=c+l-S,S-=l,S<T){T-=S;do{b[r++]=u[v++]}while(--S);if(v=0,l<T){S=l,T-=S;do{b[r++]=u[v++]}while(--S);v=r-R,y=b}}}else if(v+=l-S,S<T){T-=S;do{b[r++]=u[v++]}while(--S);v=r-R,y=b}for(;T>2;)b[r++]=y[v++],b[r++]=y[v++],b[r++]=y[v++],T-=3;T&&(b[r++]=y[v++],T>1&&(b[r++]=y[v++]))}else{v=r-R;do{b[r++]=b[v++],b[r++]=b[v++],b[r++]=b[v++],T-=3}while(T>2);T&&(b[r++]=b[v++],T>1&&(b[r++]=b[v++]))}break}}break}}while(n<i&&r<s);T=p>>3,n-=T,p-=T<<3,h&=(1<<p)-1,e.next_in=n,e.next_out=r,e.avail_in=n<i?i-n+5:5-(n-i),e.avail_out=r<s?s-r+257:257-(r-s),I.hold=h,I.bits=p};const GG=15,WG=new Uint16Array([3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0]),KG=new Uint8Array([16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78]),HG=new Uint16Array([1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0]),YG=new Uint8Array([16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64]);var XG=(e,t,n,i,r,o,s,a)=>{const c=a.bits;let d,l,u,h,p,_,E=0,m=0,f=0,g=0,S=0,T=0,R=0,v=0,y=0,C=0,b=null;const I=new Uint16Array(16),A=new Uint16Array(16);let w,O,N,D=null;for(E=0;E<=GG;E++)I[E]=0;for(m=0;m<i;m++)I[t[n+m]]++;for(S=c,g=GG;g>=1&&0===I[g];g--);if(S>g&&(S=g),0===g)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(f=1;f<g&&0===I[f];f++);for(S<f&&(S=f),v=1,E=1;E<=GG;E++)if(v<<=1,v-=I[E],v<0)return-1;if(v>0&&(0===e||1!==g))return-1;for(A[1]=0,E=1;E<GG;E++)A[E+1]=A[E]+I[E];for(m=0;m<i;m++)0!==t[n+m]&&(s[A[t[n+m]]++]=m);if(0===e?(b=D=s,_=20):1===e?(b=WG,D=KG,_=257):(b=HG,D=YG,_=0),C=0,m=0,E=f,p=o,T=S,R=0,u=-1,y=1<<S,h=y-1,1===e&&y>852||2===e&&y>592)return 1;for(;;){w=E-R,s[m]+1<_?(O=0,N=s[m]):s[m]>=_?(O=D[s[m]-_],N=b[s[m]-_]):(O=96,N=0),d=1<<E-R,l=1<<T,f=l;do{l-=d,r[p+(C>>R)+l]=w<<24|O<<16|N|0}while(0!==l);for(d=1<<E-1;C&d;)d>>=1;if(0!==d?(C&=d-1,C+=d):C=0,m++,0==--I[E]){if(E===g)break;E=t[n+s[m]]}if(E>S&&(C&h)!==u){for(0===R&&(R=S),p+=f,T=E-R,v=1<<T;T+R<g&&(v-=I[T+R],!(v<=0));)T++,v<<=1;if(y+=1<<T,1===e&&y>852||2===e&&y>592)return 1;u=C&h,r[u]=S<<24|T<<16|p-o|0}}return 0!==C&&(r[p+C]=E-R<<24|64<<16|0),a.bits=S,0};const JG=mj.Z_FINISH,zG=mj.Z_BLOCK,ZG=mj.Z_TREES,qG=mj.Z_OK,QG=mj.Z_STREAM_END,$G=mj.Z_NEED_DICT,eW=mj.Z_STREAM_ERROR,tW=mj.Z_DATA_ERROR,nW=mj.Z_MEM_ERROR,iW=mj.Z_BUF_ERROR,rW=mj.Z_DEFLATED,oW=16180,sW=16190,aW=16191,cW=16192,dW=16194,lW=16199,uW=16200,hW=16206,pW=16209,_W=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function EW(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const mW=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode<oW||t.mode>16211?1:0},fW=e=>{if(mW(e))return eW;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=oW,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,qG},gW=e=>{if(mW(e))return eW;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,fW(e)},SW=(e,t)=>{let n;if(mW(e))return eW;const i=e.state;return t<0?(n=0,t=-t):(n=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?eW:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=n,i.wbits=t,gW(e))},TW=(e,t)=>{if(!e)return eW;const n=new EW;e.state=n,n.strm=e,n.window=null,n.mode=oW;const i=SW(e,t);return i!==qG&&(e.state=null),i};let RW,vW,yW=!0;const CW=e=>{if(yW){RW=new Int32Array(512),vW=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(XG(1,e.lens,0,288,RW,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;XG(2,e.lens,0,32,vW,0,e.work,{bits:5}),yW=!1}e.lencode=RW,e.lenbits=9,e.distcode=vW,e.distbits=5},bW=(e,t,n,i)=>{let r;const o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Uint8Array(o.wsize)),i>=o.wsize?(o.window.set(t.subarray(n-o.wsize,n),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>i&&(r=i),o.window.set(t.subarray(n-i,n-i+r),o.wnext),(i-=r)?(o.window.set(t.subarray(n-i,n),0),o.wnext=i,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0};var IW=(e,t)=>{let n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,C=0;const b=new Uint8Array(4);let I,A;const w=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(mW(e)||!e.output||!e.input&&0!==e.avail_in)return eW;n=e.state,n.mode===aW&&(n.mode=cW),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,i=e.input,a=e.avail_in,d=n.hold,l=n.bits,u=a,h=c,y=qG;e:for(;;)switch(n.mode){case oW:if(0===n.wrap){n.mode=cW;break}for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(2&n.wrap&&35615===d){0===n.wbits&&(n.wbits=15),n.check=0,b[0]=255&d,b[1]=d>>>8&255,n.check=_j(n.check,b,2,0),d=0,l=0,n.mode=16181;break}if(n.head&&(n.head.done=!1),!(1&n.wrap)||(((255&d)<<8)+(d>>8))%31){e.msg="incorrect header check",n.mode=pW;break}if((15&d)!==rW){e.msg="unknown compression method",n.mode=pW;break}if(d>>>=4,l-=4,v=8+(15&d),0===n.wbits&&(n.wbits=v),v>15||v>n.wbits){e.msg="invalid window size",n.mode=pW;break}n.dmax=1<<n.wbits,n.flags=0,e.adler=n.check=1,n.mode=512&d?16189:aW,d=0,l=0;break;case 16181:for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(n.flags=d,(255&CB(n))!==rW){e.msg="unknown compression method",n.mode=pW;break}if(57344&CB(n)){e.msg="unknown header flags set",n.mode=pW;break}n.head&&(n.head.text=d>>8&1),512&CB(n)&&4&n.wrap&&(b[0]=255&d,b[1]=d>>>8&255,n.check=_j(n.check,b,2,0)),d=0,l=0,n.mode=16182;case 16182:for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.head&&(n.head.time=d),512&CB(n)&&4&n.wrap&&(b[0]=255&d,b[1]=d>>>8&255,b[2]=d>>>16&255,b[3]=d>>>24&255,n.check=_j(n.check,b,4,0)),d=0,l=0,n.mode=16183;case 16183:for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.head&&(n.head.xflags=255&d,n.head.os=d>>8),512&CB(n)&&4&n.wrap&&(b[0]=255&d,b[1]=d>>>8&255,n.check=_j(n.check,b,2,0)),d=0,l=0,n.mode=16184;case 16184:if(1024&CB(n)){for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.length=d,n.head&&(n.head.extra_len=d),512&CB(n)&&4&n.wrap&&(b[0]=255&d,b[1]=d>>>8&255,n.check=_j(n.check,b,2,0)),d=0,l=0}else n.head&&(n.head.extra=null);n.mode=16185;case 16185:if(1024&CB(n)&&(p=n.length,p>a&&(p=a),p&&(n.head&&(v=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(i.subarray(o,o+p),v)),512&CB(n)&&4&n.wrap&&(n.check=_j(n.check,i,p,o)),a-=p,o+=p,n.length-=p),n.length))break e;n.length=0,n.mode=16186;case 16186:if(2048&CB(n)){if(0===a)break e;p=0;do{v=i[o+p++],n.head&&v&&n.length<65536&&(n.head.name+=String.fromCharCode(v))}while(v&&p<a);if(512&CB(n)&&4&n.wrap&&(n.check=_j(n.check,i,p,o)),a-=p,o+=p,v)break e}else n.head&&(n.head.name=null);n.length=0,n.mode=16187;case 16187:if(4096&CB(n)){if(0===a)break e;p=0;do{v=i[o+p++],n.head&&v&&n.length<65536&&(n.head.comment+=String.fromCharCode(v))}while(v&&p<a);if(512&CB(n)&&4&n.wrap&&(n.check=_j(n.check,i,p,o)),a-=p,o+=p,v)break e}else n.head&&(n.head.comment=null);n.mode=16188;case 16188:if(512&CB(n)){for(;l<16;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(4&n.wrap&&d!==(65535&n.check)){e.msg="header crc mismatch",n.mode=pW;break}d=0,l=0}n.head&&(n.head.hcrc=CB(n)>>9&1,n.head.done=!0),e.adler=n.check=0,n.mode=aW;break;case 16189:for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}e.adler=n.check=_W(d),d=0,l=0,n.mode=sW;case sW:if(0===n.havedict)return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,$G;e.adler=n.check=1,n.mode=aW;case aW:if(t===zG||t===ZG)break e;case cW:if(n.last){d>>>=7&l,l-=7&l,n.mode=hW;break}for(;l<3;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}switch(n.last=1&d,d>>>=1,l-=1,3&d){case 0:n.mode=16193;break;case 1:if(CW(n),n.mode=lW,t===ZG){d>>>=2,l-=2;break e}break;case 2:n.mode=16196;break;case 3:e.msg="invalid block type",n.mode=pW}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if((65535&d)!=(d>>>16^65535)){e.msg="invalid stored block lengths",n.mode=pW;break}if(n.length=65535&d,d=0,l=0,n.mode=dW,t===ZG)break e;case dW:n.mode=16195;case 16195:if(p=n.length,p){if(p>a&&(p=a),p>c&&(p=c),0===p)break e;r.set(i.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,n.length-=p;break}n.mode=aW;break;case 16196:for(;l<14;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(n.nlen=257+(31&d),d>>>=5,l-=5,n.ndist=1+(31&d),d>>>=5,l-=5,n.ncode=4+(15&d),d>>>=4,l-=4,n.nlen>286||n.ndist>30){e.msg="too many length or distance symbols",n.mode=pW;break}n.have=0,n.mode=16197;case 16197:for(;n.have<n.ncode;){for(;l<3;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.lens[w[n.have++]]=7&d,d>>>=3,l-=3}for(;n.have<19;)n.lens[w[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,I={bits:n.lenbits},y=XG(0,n.lens,0,19,n.lencode,0,n.work,I),n.lenbits=I.bits,y){e.msg="invalid code lengths set",n.mode=pW;break}n.have=0,n.mode=16198;case 16198:for(;n.have<n.nlen+n.ndist;){for(;C=n.lencode[d&(1<<n.lenbits)-1],m=C>>>24,f=C>>>16&255,g=65535&C,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(g<16)d>>>=m,l-=m,n.lens[n.have++]=g;else{if(16===g){for(A=m+2;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(d>>>=m,l-=m,0===n.have){e.msg="invalid bit length repeat",n.mode=pW;break}v=n.lens[n.have-1],p=3+(3&d),d>>>=2,l-=2}else if(17===g){for(A=m+3;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=m,l-=m,v=0,p=3+(7&d),d>>>=3,l-=3}else{for(A=m+7;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=m,l-=m,v=0,p=11+(127&d),d>>>=7,l-=7}if(n.have+p>n.nlen+n.ndist){e.msg="invalid bit length repeat",n.mode=pW;break}for(;p--;)n.lens[n.have++]=v}}if(n.mode===pW)break;if(0===n.lens[256]){e.msg="invalid code -- missing end-of-block",n.mode=pW;break}if(n.lenbits=9,I={bits:n.lenbits},y=XG(1,n.lens,0,n.nlen,n.lencode,0,n.work,I),n.lenbits=I.bits,y){e.msg="invalid literal/lengths set",n.mode=pW;break}if(n.distbits=6,n.distcode=n.distdyn,I={bits:n.distbits},y=XG(2,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,I),n.distbits=I.bits,y){e.msg="invalid distances set",n.mode=pW;break}if(n.mode=lW,t===ZG)break e;case lW:n.mode=uW;case uW:if(a>=6&&c>=258){e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,jG(e,h),s=e.next_out,r=e.output,c=e.avail_out,o=e.next_in,i=e.input,a=e.avail_in,d=n.hold,l=n.bits,n.mode===aW&&(n.back=-1);break}for(n.back=0;C=n.lencode[d&(1<<n.lenbits)-1],m=C>>>24,f=C>>>16&255,g=65535&C,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(f&&0==(240&f)){for(S=m,T=f,R=g;C=n.lencode[R+((d&(1<<S+T)-1)>>S)],m=C>>>24,f=C>>>16&255,g=65535&C,!(S+m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=S,l-=S,n.back+=S}if(d>>>=m,l-=m,n.back+=m,n.length=g,0===f){n.mode=16205;break}if(32&f){n.back=-1,n.mode=aW;break}if(64&f){e.msg="invalid literal/length code",n.mode=pW;break}n.extra=15&f,n.mode=16201;case 16201:if(n.extra){for(A=n.extra;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.length+=d&(1<<n.extra)-1,d>>>=n.extra,l-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=16202;case 16202:for(;C=n.distcode[d&(1<<n.distbits)-1],m=C>>>24,f=C>>>16&255,g=65535&C,!(m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(0==(240&f)){for(S=m,T=f,R=g;C=n.distcode[R+((d&(1<<S+T)-1)>>S)],m=C>>>24,f=C>>>16&255,g=65535&C,!(S+m<=l);){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}d>>>=S,l-=S,n.back+=S}if(d>>>=m,l-=m,n.back+=m,64&f){e.msg="invalid distance code",n.mode=pW;break}n.offset=g,n.extra=15&f,n.mode=16203;case 16203:if(n.extra){for(A=n.extra;l<A;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}n.offset+=d&(1<<n.extra)-1,d>>>=n.extra,l-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){e.msg="invalid distance too far back",n.mode=pW;break}n.mode=16204;case 16204:if(0===c)break e;if(p=h-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){e.msg="invalid distance too far back",n.mode=pW;break}p>n.wnext?(p-=n.wnext,_=n.wsize-p):_=n.wnext-p,p>n.length&&(p=n.length),E=n.window}else E=r,_=s-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do{r[s++]=E[_++]}while(--p);0===n.length&&(n.mode=uW);break;case 16205:if(0===c)break e;r[s++]=n.length,c--,n.mode=uW;break;case hW:if(n.wrap){for(;l<32;){if(0===a)break e;a--,d|=i[o++]<<l,l+=8}if(h-=c,e.total_out+=h,n.total+=h,4&n.wrap&&h&&(e.adler=n.check=CB(n)?_j(n.check,r,h,s-h):hj(n.check,r,h,s-h)),h=c,4&n.wrap&&(CB(n)?d:_W(d))!==n.check){e.msg="incorrect data check",n.mode=pW;break}d=0,l=0}n.mode=16207;case 16207:if(n.wrap&&CB(n)){for(;l<32;){if(0===a)break e;a--,d+=i[o++]<<l,l+=8}if(4&n.wrap&&d!==(4294967295&n.total)){e.msg="incorrect length check",n.mode=pW;break}d=0,l=0}n.mode=16208;case 16208:y=QG;break e;case pW:y=tW;break e;case 16210:return nW;default:return eW}return e.next_out=s,e.avail_out=c,e.next_in=o,e.avail_in=a,n.hold=d,n.bits=l,(n.wsize||h!==e.avail_out&&n.mode<pW&&(n.mode<hW||t!==JG))&&bW(e,e.output,e.next_out,h-e.avail_out),u-=e.avail_in,h-=e.avail_out,e.total_in+=u,e.total_out+=h,n.total+=h,4&n.wrap&&h&&(e.adler=n.check=CB(n)?_j(n.check,r,h,e.next_out-h):hj(n.check,r,h,e.next_out-h)),e.data_type=n.bits+(n.last?64:0)+(n.mode===aW?128:0)+(n.mode===lW||n.mode===dW?256:0),(0===u&&0===h||t===JG)&&y===qG&&(y=iW),y},AW={inflateReset:gW,inflateReset2:SW,inflateResetKeep:fW,inflateInit:e=>TW(e,15),inflateInit2:TW,inflate:IW,inflateEnd:e=>{if(mW(e))return eW;let t=e.state;return t.window&&(t.window=null),e.state=null,qG},inflateGetHeader:(e,t)=>{if(mW(e))return eW;const n=e.state;return 0==(2&n.wrap)?eW:(n.head=t,t.done=!1,qG)},inflateSetDictionary:(e,t)=>{const n=t.length;let i,r,o;return mW(e)?eW:(i=e.state,0!==i.wrap&&i.mode!==sW?eW:i.mode===sW&&(r=1,r=hj(r,t,n,0),r!==i.check)?tW:(o=bW(e,t,n,n),o?(i.mode=16210,nW):(i.havedict=1,qG)))},inflateInfo:"pako inflate (from Nodeca project)"};var wW=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const OW=Object.prototype.toString,NW=mj.Z_NO_FLUSH,DW=mj.Z_FINISH,PW=mj.Z_OK,LW=mj.Z_STREAM_END,kW=mj.Z_NEED_DICT,MW=mj.Z_STREAM_ERROR,UW=mj.Z_DATA_ERROR,VW=mj.Z_MEM_ERROR;function xW(e){this.options=vG.assign({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new IG,this.strm.avail_out=0;let n=AW.inflateInit2(this.strm,t.windowBits);if(n!==PW)throw new Error(Ej[n]);if(this.header=new wW,AW.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=bG.string2buf(t.dictionary):"[object ArrayBuffer]"===OW.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=AW.inflateSetDictionary(this.strm,t.dictionary),n!==PW)))throw new Error(Ej[n])}function FW(e,t){const n=new xW(t);if(n.push(e),n.err)throw n.msg||Ej[n.err];return n.result}xW.prototype.push=function(e,t){const n=this.strm,i=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=t===~~t?t:!0===t?DW:NW,"[object ArrayBuffer]"===OW.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(i),n.next_out=0,n.avail_out=i),o=AW.inflate(n,s),o===kW&&r&&(o=AW.inflateSetDictionary(n,r),o===PW?o=AW.inflate(n,s):o===UW&&(o=kW));n.avail_in>0&&o===LW&&n.state.wrap>0&&0!==e[n.next_in];)AW.inflateReset(n),o=AW.inflate(n,s);switch(o){case MW:case UW:case kW:case VW:return this.onEnd(o),this.ended=!0,!1}if(a=n.avail_out,n.next_out&&(0===n.avail_out||o===LW))if("string"===this.options.to){let e=bG.utf8border(n.output,n.next_out),t=n.next_out-e,r=bG.buf2string(n.output,e);n.next_out=t,n.avail_out=i-t,t&&n.output.set(n.output.subarray(e,e+t),0),this.onData(r)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(o!==PW||0!==a){if(o===LW)return o=AW.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},xW.prototype.onData=function(e){this.chunks.push(e)},xW.prototype.onEnd=function(e){e===PW&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=vG.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var BW={Inflate:xW,inflate:FW,inflateRaw:function(e,t){return(t=t||{}).raw=!0,FW(e,t)},ungzip:FW,constants:mj};var jW,GW=FG.deflate,WW=FG.deflateRaw,KW=BW.inflate,HW=BW.inflateRaw,YW=function(e){return e[e.CHOOSE_SERVER=11]="CHOOSE_SERVER",e[e.CLOUD_PROXY=18]="CLOUD_PROXY",e[e.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",e[e.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK",e}(YW||{});function XW(e){let t=!1;const n=[];for(let i=0;i<e.length;i++){let r=e.charAt(i);switch(r){case"_":t=!0;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":n.push(r),t=!1;break;default:t&&(t=!1,r=r.toUpperCase()),n.push(r)}}return n.join("")}const JW=new Set(["constructor","toString","toJSON","valueOf"]);function zW(e){return JW.has(e)?e+"$":e}var ZW=void 0!==Ub?Ub:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function qW(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var QW,$W,eK=function(e){try{return!!e()}catch(e){return!0}},tK=!eK((function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})),nK=tK,iK=Function.prototype,rK=iK.call,oK=nK&&iK.bind.bind(rK,rK),sK=nK?oK:function(e){return function(){return rK.apply(e,arguments)}},aK=sK,cK=aK({}.toString),dK=aK("".slice),lK=function(e){return dK(cK(e),8,-1)},uK=eK,hK=lK,pK=Object,_K=sK("".split),EK=uK((function(){return!pK("z").propertyIsEnumerable(0)}))?function(e){return"String"===hK(e)?_K(e,""):pK(e)}:pK,mK=function(e){return null==e},fK=mK,gK=TypeError,SK=function(e){if(fK(e))throw new gK("Can't call method on "+e);return e},TK=EK,RK=SK,vK=function(e){return TK(RK(e))},yK={},CK=function(e){return e&&e.Math===Math&&e},bK=CK("object"==typeof Ub&&Ub)||CK("object"==typeof window&&window)||CK("object"==typeof self&&self)||CK("object"==typeof ZW&&ZW)||CK("object"==typeof ZW&&ZW)||function(){return this}()||Function("return this")(),IK="object"==typeof document&&document.all,AK=void 0===IK&&void 0!==IK?function(e){return"function"==typeof e||e===IK}:function(e){return"function"==typeof e},wK=AK,OK=bK.WeakMap,NK=wK(OK)&&/native code/.test(String(OK)),DK=AK,PK=function(e){return"object"==typeof e?null!==e:DK(e)},LK=!eK((function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})),kK={},MK=PK,UK=bK.document,VK=MK(UK)&&MK(UK.createElement),xK=function(e){return VK?UK.createElement(e):{}},FK=xK,BK=!LK&&!eK((function(){return 7!==Object.defineProperty(FK("div"),"a",{get:function(){return 7}}).a})),jK=LK&&eK((function(){return 42!==Object.defineProperty((function(){}),"prototype",{value:42,writable:!1}).prototype})),GK=PK,WK=String,KK=TypeError,HK=function(e){if(GK(e))return e;throw new KK(WK(e)+" is not an object")},YK=tK,XK=Function.prototype.call,JK=YK?XK.bind(XK):function(){return XK.apply(XK,arguments)},zK={},ZK=zK,qK=bK,QK=AK,$K=function(e){return QK(e)?e:void 0},eH=function(e,t){return arguments.length<2?$K(ZK[e])||$K(qK[e]):ZK[e]&&ZK[e][t]||qK[e]&&qK[e][t]},tH=sK({}.isPrototypeOf),nH=bK.navigator,iH=nH&&nH.userAgent,rH=iH?String(iH):"",oH=bK,sH=rH,aH=oH.process,cH=oH.Deno,dH=aH&&aH.versions||cH&&cH.version,lH=dH&&dH.v8;lH&&($W=(QW=lH.split("."))[0]>0&&QW[0]<4?1:+(QW[0]+QW[1])),!$W&&sH&&(!(QW=sH.match(/Edge\/(\d+)/))||QW[1]>=74)&&(QW=sH.match(/Chrome\/(\d+)/))&&($W=+QW[1]);var uH=$W,hH=uH,pH=eK,_H=bK.String,EH=!!Object.getOwnPropertySymbols&&!pH((function(){var e=Symbol("symbol detection");return!_H(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&hH&&hH<41})),mH=EH&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,fH=eH,gH=AK,SH=tH,TH=Object,RH=mH?function(e){return"symbol"==typeof e}:function(e){var t=fH("Symbol");return gH(t)&&SH(t.prototype,TH(e))},vH=String,yH=function(e){try{return vH(e)}catch(e){return"Object"}},CH=AK,bH=yH,IH=TypeError,AH=function(e){if(CH(e))return e;throw new IH(bH(e)+" is not a function")},wH=AH,OH=mK,NH=function(e,t){var n=e[t];return OH(n)?void 0:wH(n)},DH=JK,PH=AK,LH=PK,kH=TypeError,MH={exports:{}},UH=bK,VH=Object.defineProperty,xH=bK,FH="__core-js_shared__",BH=MH.exports=xH[FH]||function(e,t){try{VH(UH,e,{value:t,configurable:!0,writable:!0})}catch(n){UH[e]=t}return t}(FH,{});(BH.versions||(BH.versions=[])).push({version:"3.49.0",mode:"pure",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.49.0/LICENSE",source:"https://github.com/zloirock/core-js"});var jH=MH.exports,GH=jH,WH=function(e,t){return GH[e]||(GH[e]=t||{})},KH=SK,HH=Object,YH=function(e){return HH(KH(e))},XH=YH,JH=sK({}.hasOwnProperty),zH=Object.hasOwn||function(e,t){return JH(XH(e),t)},ZH=sK,qH=0,QH=Math.random(),$H=ZH(1.1.toString),eY=function(e){return"Symbol("+(void 0===e?"":e)+")_"+$H(++qH+QH,36)},tY=WH,nY=zH,iY=eY,rY=EH,oY=mH,sY=bK.Symbol,aY=tY("wks"),cY=oY?sY.for||sY:sY&&sY.withoutSetter||iY,dY=function(e){return nY(aY,e)||(aY[e]=rY&&nY(sY,e)?sY[e]:cY("Symbol."+e)),aY[e]},lY=JK,uY=PK,hY=RH,pY=NH,_Y=TypeError,EY=dY("toPrimitive"),mY=function(e,t){if(!uY(e)||hY(e))return e;var n,i=pY(e,EY);if(i){if(void 0===t&&(t="default"),n=lY(i,e,t),!uY(n)||hY(n))return n;throw new _Y("Can't convert object to primitive value")}return void 0===t&&(t="number"),function(e,t){var n,i;if("string"===t&&PH(n=e.toString)&&!LH(i=DH(n,e)))return i;if(PH(n=e.valueOf)&&!LH(i=DH(n,e)))return i;if("string"!==t&&PH(n=e.toString)&&!LH(i=DH(n,e)))return i;throw new kH("Can't convert object to primitive value")}(e,t)},fY=RH,gY=function(e){var t=mY(e,"string");return fY(t)?t:t+""},SY=LK,TY=BK,RY=jK,vY=HK,yY=gY,CY=TypeError,bY=Object.defineProperty,IY=Object.getOwnPropertyDescriptor,AY="enumerable",wY="configurable",OY="writable";kK.f=SY?RY?function(e,t,n){if(vY(e),t=yY(t),vY(n),"function"==typeof e&&"prototype"===t&&"value"in n&&OY in n&&!n[OY]){var i=IY(e,t);i&&i[OY]&&(e[t]=n.value,n={configurable:wY in n?n[wY]:i[wY],enumerable:AY in n?n[AY]:i[AY],writable:!1})}return bY(e,t,n)}:bY:function(e,t,n){if(vY(e),t=yY(t),vY(n),TY)try{return bY(e,t,n)}catch(e){}if("get"in n||"set"in n)throw new CY("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var NY,DY,PY,LY=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},kY=kK,MY=LY,UY=LK?function(e,t,n){return kY.f(e,t,MY(1,n))}:function(e,t,n){return e[t]=n,e},VY=eY,xY=WH("keys"),FY=function(e){return xY[e]||(xY[e]=VY(e))},BY={},jY=NK,GY=bK,WY=PK,KY=UY,HY=zH,YY=jH,XY=FY,JY=BY,zY="Object already initialized",ZY=GY.TypeError,qY=GY.WeakMap;if(jY||YY.state){var QY=YY.state||(YY.state=new qY);QY.get=QY.get,QY.has=QY.has,QY.set=QY.set,NY=function(e,t){if(QY.has(e))throw new ZY(zY);return t.facade=e,QY.set(e,t),t},DY=function(e){return QY.get(e)||{}},PY=function(e){return QY.has(e)}}else{var $Y=XY("state");JY[$Y]=!0,NY=function(e,t){if(HY(e,$Y))throw new ZY(zY);return t.facade=e,KY(e,$Y,t),t},DY=function(e){return HY(e,$Y)?e[$Y]:{}},PY=function(e){return HY(e,$Y)}}var eX={set:NY,get:DY,has:PY,enforce:function(e){return PY(e)?DY(e):NY(e,{})},getterFor:function(e){return function(t){var n;if(!WY(t)||(n=DY(t)).type!==e)throw new ZY("Incompatible receiver, "+e+" required");return n}}},tX=tK,nX=Function.prototype,iX=nX.apply,rX=nX.call,oX="object"==typeof Reflect&&Reflect.apply||(tX?rX.bind(iX):function(){return rX.apply(iX,arguments)}),sX=lK,aX=sK,cX=function(e){if("Function"===sX(e))return aX(e)},dX={},lX={},uX={}.propertyIsEnumerable,hX=Object.getOwnPropertyDescriptor,pX=hX&&!uX.call({1:2},1);lX.f=pX?function(e){var t=hX(this,e);return!!t&&t.enumerable}:uX;var _X=LK,EX=JK,mX=lX,fX=LY,gX=vK,SX=gY,TX=zH,RX=BK,vX=Object.getOwnPropertyDescriptor;dX.f=_X?vX:function(e,t){if(e=gX(e),t=SX(t),RX)try{return vX(e,t)}catch(e){}if(TX(e,t))return fX(!EX(mX.f,e,t),e[t])};var yX=eK,CX=AK,bX=/#|\.prototype\./,IX=function(e,t){var n=wX[AX(e)];return n===NX||n!==OX&&(CX(t)?yX(t):!!t)},AX=IX.normalize=function(e){return String(e).replace(bX,".").toLowerCase()},wX=IX.data={},OX=IX.NATIVE="N",NX=IX.POLYFILL="P",DX=IX,PX=AH,LX=tK,kX=cX(cX.bind),MX=function(e,t){return PX(e),void 0===t?e:LX?kX(e,t):function(){return e.apply(t,arguments)}},UX=bK,VX=oX,xX=cX,FX=AK,BX=dX.f,jX=DX,GX=zK,WX=MX,KX=UY,HX=zH,YX=function(e){var t=function(n,i,r){if(this instanceof t){switch(arguments.length){case 0:return new e;case 1:return new e(n);case 2:return new e(n,i)}return new e(n,i,r)}return VX(e,this,arguments)};return t.prototype=e.prototype,t},XX=function(e,t){var n,i,r,o,s,a,c,d,l,u=e.target,h=e.global,p=e.stat,_=e.proto,E=h?UX:p?UX[u]:UX[u]&&UX[u].prototype,m=h?GX:GX[u]||KX(GX,u,{})[u],f=m.prototype;for(o in t)i=!(n=jX(h?o:u+(p?".":"#")+o,e.forced))&&E&&HX(E,o),a=m[o],i&&(c=e.dontCallGetSet?(l=BX(E,o))&&l.value:E[o]),s=i&&c?c:t[o],(n||_||typeof a!=typeof s)&&(d=e.bind&&i?WX(s,UX):e.wrap&&i?YX(s):_&&FX(s)?xX(s):s,(e.sham||s&&s.sham||a&&a.sham)&&KX(d,"sham",!0),KX(m,o,d),_&&(HX(GX,r=u+"Prototype")||KX(GX,r,{}),KX(GX[r],o,s),e.real&&f&&(n||!f[o])&&KX(f,o,s)))},JX=LK,zX=zH,ZX=Function.prototype,qX=JX&&Object.getOwnPropertyDescriptor,QX=zX(ZX,"name"),$X={EXISTS:QX,PROPER:QX&&"something"===function(){}.name,CONFIGURABLE:QX&&(!JX||JX&&qX(ZX,"name").configurable)},eJ={},tJ=Math.ceil,nJ=Math.floor,iJ=Math.trunc||function(e){var t=+e;return(t>0?nJ:tJ)(t)},rJ=function(e){var t=+e;return t!=t||0===t?0:iJ(t)},oJ=rJ,sJ=Math.max,aJ=Math.min,cJ=function(e,t){var n=oJ(e);return n<0?sJ(n+t,0):aJ(n,t)},dJ=rJ,lJ=Math.min,uJ=function(e){return function(e){var t=dJ(e);return t>0?lJ(t,9007199254740991):0}(e.length)},hJ=vK,pJ=cJ,_J=uJ,EJ=function(e){return function(t,n,i){var r=hJ(t),o=_J(r);if(0===o)return!e&&-1;var s,a=pJ(i,o);if(e&&n!=n){for(;o>a;)if((s=r[a++])!=s)return!0}else for(;o>a;a++)if((e||a in r)&&r[a]===n)return e||a||0;return!e&&-1}},mJ={includes:EJ(!0),indexOf:EJ(!1)},fJ=zH,gJ=vK,SJ=mJ.indexOf,TJ=BY,RJ=sK([].push),vJ=function(e,t){var n,i=gJ(e),r=0,o=[];for(n in i)!fJ(TJ,n)&&fJ(i,n)&&RJ(o,n);for(;t.length>r;)fJ(i,n=t[r++])&&(~SJ(o,n)||RJ(o,n));return o},yJ=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],CJ=vJ,bJ=yJ,IJ=Object.keys||function(e){return CJ(e,bJ)},AJ=LK,wJ=jK,OJ=kK,NJ=HK,DJ=vK,PJ=IJ;eJ.f=AJ&&!wJ?Object.defineProperties:function(e,t){NJ(e);for(var n,i=DJ(t),r=PJ(t),o=r.length,s=0;o>s;)OJ.f(e,n=r[s++],i[n]);return e};var LJ,kJ=eH("document","documentElement"),MJ=HK,UJ=eJ,VJ=yJ,xJ=BY,FJ=kJ,BJ=xK,jJ="prototype",GJ="script",WJ=FY("IE_PROTO"),KJ=function(){},HJ=function(e){return"<"+GJ+">"+e+"</"+GJ+">"},YJ=function(e){e.write(HJ("")),e.close();var t=e.parentWindow.Object;return e=null,t},XJ=function(){try{LJ=new ActiveXObject("htmlfile")}catch(e){}var e,t,n;XJ="undefined"!=typeof document?document.domain&&LJ?YJ(LJ):(t=BJ("iframe"),n="java"+GJ+":",t.style.display="none",FJ.appendChild(t),t.src=String(n),(e=t.contentWindow.document).open(),e.write(HJ("document.F=Object")),e.close(),e.F):YJ(LJ);for(var i=VJ.length;i--;)delete XJ[jJ][VJ[i]];return XJ()};xJ[WJ]=!0;var JJ,zJ,ZJ,qJ=Object.create||function(e,t){var n;return null!==e?(KJ[jJ]=MJ(e),n=new KJ,KJ[jJ]=null,n[WJ]=e):n=XJ(),void 0===t?n:UJ.f(n,t)},QJ=!eK((function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})),$J=zH,ez=AK,tz=YH,nz=QJ,iz=FY("IE_PROTO"),rz=Object,oz=rz.prototype,sz=nz?rz.getPrototypeOf:function(e){var t=tz(e);if($J(t,iz))return t[iz];var n=t.constructor;return ez(n)&&t instanceof n?n.prototype:t instanceof rz?oz:null},az=UY,cz=function(e,t,n,i){return i&&i.enumerable?e[t]=n:az(e,t,n),e},dz=eK,lz=AK,uz=PK,hz=qJ,pz=sz,_z=cz,Ez=dY("iterator"),mz=!1;oL([])&&("next"in(ZJ=oL(jW=[]).call(jW))?(zJ=pz(pz(ZJ)))!==Object.prototype&&(JJ=zJ):mz=!0);var fz=!uz(JJ)||dz((function(){var e={};return JJ[Ez].call(e)!==e}));lz((JJ=fz?{}:hz(JJ))[Ez])||_z(JJ,Ez,(function(){return this}));var gz={IteratorPrototype:JJ,BUGGY_SAFARI_ITERATORS:mz},Sz={};Sz[dY("toStringTag")]="z";var Tz="[object z]"===String(Sz),Rz=Tz,vz=AK,yz=lK,Cz=dY("toStringTag"),bz=Object,Iz="Arguments"===yz(function(){return arguments}()),Az=Rz?yz:function(e){var t,n,i;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=bz(e),Cz))?n:Iz?yz(t):"Object"===(i=yz(t))&&vz(t.callee)?"Arguments":i},wz=Az,Oz=Tz?{}.toString:function(){return"[object "+wz(this)+"]"},Nz=Tz,Dz=kK.f,Pz=UY,Lz=zH,kz=Oz,Mz=dY("toStringTag"),Uz=function(e,t,n,i){var r=n?e:e&&e.prototype;r&&(Lz(r,Mz)||Dz(r,Mz,{configurable:!0,value:t}),i&&!Nz&&Pz(r,"toString",kz))},Vz=gz.IteratorPrototype,xz=qJ,Fz=LY,Bz=Uz,jz=yK,Gz=function(){return this},Wz=XX,Kz=JK,Hz=sz,Yz=Uz,Xz=cz,Jz=yK,zz=$X.PROPER,Zz=gz.BUGGY_SAFARI_ITERATORS,qz=dY("iterator"),Qz="keys",$z="values",eZ="entries",tZ=function(){return this},nZ=function(e,t,n,i,r,o,s){!function(e,t,n,i){var r=t+" Iterator";e.prototype=xz(Vz,{next:Fz(+!i,n)}),Bz(e,r,!1,!0),jz[r]=Gz}(n,t,i);var a,c,d,l=function(e){if(e===r&&E)return E;if(!Zz&&e&&e in p)return p[e];switch(e){case Qz:case $z:case eZ:return function(){return new n(this,e)}}return function(){return new n(this)}},u=t+" Iterator",h=!1,p=e.prototype,_=p[qz]||p["@@iterator"]||r&&p[r],E=!Zz&&_||l(r),m="Array"===t&&p.entries||_;if(m&&(a=Hz(m.call(new e)))!==Object.prototype&&a.next&&(Yz(a,u,!0,!0),Jz[u]=tZ),zz&&r===$z&&_&&_.name!==$z&&(h=!0,E=function(){return Kz(_,this)}),r)if(c={values:l($z),keys:o?E:l(Qz),entries:l(eZ)},s)for(d in c)(Zz||h||!(d in p))&&Xz(p,d,c[d]);else Wz({target:t,proto:!0,forced:Zz||h},c);return s&&p[qz]!==E&&Xz(p,qz,E,{name:r}),Jz[t]=E,c},iZ=function(e,t){return{value:e,done:t}},rZ=vK,oZ=yK,sZ=eX;kK.f;var aZ=nZ,cZ=iZ,dZ="Array Iterator",lZ=sZ.set,uZ=sZ.getterFor(dZ);aZ(Array,"Array",(function(e,t){lZ(this,{type:dZ,target:rZ(e),index:0,kind:t})}),(function(){var e=uZ(this),t=e.target,n=e.index++;if(!t||n>=t.length)return e.target=null,cZ(void 0,!0);switch(e.kind){case"keys":return cZ(n,!1);case"values":return cZ(t[n],!1)}return cZ([n,t[n]],!1)}),"values"),oZ.Arguments=oZ.Array;var hZ=bK,pZ=Uz,_Z=yK;for(var EZ in{CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0})pZ(hZ[EZ],EZ),_Z[EZ]=_Z.Array;var mZ=bK,fZ=zK,gZ=function(e,t){var n=fZ[e+"Prototype"],i=n&&n[t];if(i)return i;var r=mZ[e],o=r&&r.prototype;return o&&o[t]},SZ=gZ("Array","values"),TZ=Az,RZ=zH,vZ=tH,yZ=SZ,CZ=Array.prototype,bZ={DOMTokenList:!0,NodeList:!0},IZ=qW((function(e){var t=fp(e);return e===CZ||vZ(CZ,e)&&t===fp(CZ)||RZ(bZ,TZ(e))?yZ:t})),AZ=bK;XX({global:!0,forced:AZ.globalThis!==AZ},{globalThis:AZ});var wZ=qW(bK);function OZ(){let e=0,t=0;for(let n=0;n<28;n+=7){let i=this.buf[this.pos++];if(e|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(15&n)<<28,t=(112&n)>>4,0==(128&n))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let i=this.buf[this.pos++];if(t|=(127&i)<<n,0==(128&i))return this.assertBounds(),[e,t]}throw new Error("invalid varint")}function NZ(e,t,n){for(let i=0;i<28;i+=7){const r=e>>>i,o=!(r>>>7==0&&0==t),s=255&(o?128|r:r);if(n.push(s),!o)return}const i=e>>>28&15|(7&t)<<4,r=!(t>>3==0);if(n.push(255&(r?128|i:i)),r){for(let e=3;e<31;e+=7){const i=t>>>e,r=!(i>>>7==0),o=255&(r?128|i:i);if(n.push(o),!r)return}n.push(t>>>31&1)}}const DZ=4294967296;function PZ(e){const t="-"===e[0];t&&(e=e.slice(1));const n=1e6;let i=0,r=0;function o(t,o){const s=Number(e.slice(t,o));r*=n,i=i*n+s,i>=DZ&&(r+=i/DZ|0,i%=DZ)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?MZ(i,r):kZ(i,r)}function LZ(e,t){var n=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t);if(e=n.lo,(t=n.hi)<=2097151)return String(DZ*t+e);const i=16777215&(e>>>24|t<<8),r=t>>16&65535;let o=(16777215&e)+6777216*i+6710656*r,s=i+8147497*r,a=2*r;const c=1e7;return o>=c&&(s+=Math.floor(o/c),o%=c),s>=c&&(a+=Math.floor(s/c),s%=c),a.toString()+UZ(s)+UZ(o)}function kZ(e,t){return{lo:0|e,hi:0|t}}function MZ(e,t){return t=~t,e?e=1+~e:t+=1,kZ(e,t)}const UZ=e=>{const t=String(e);return"0000000".slice(t.length)+t};function VZ(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(127&e|128),e>>=7;t.push(1)}}function xZ(){let e=this.buf[this.pos++],t=127&e;if(0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,0==(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,0==(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;0!=(128&e)&&t<10;t++)e=this.buf[this.pos++];if(0!=(128&e))throw new Error("invalid varint");return this.assertBounds(),t>>>0}const FZ=function(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&(wZ.Deno||"object"!=typeof process||"object"!=typeof process.env||"1"!==process.env.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),n=BigInt("9223372036854775807"),i=BigInt("0"),r=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const i="bigint"==typeof e?e:BigInt(e);if(i>n||i<t)throw new Error("invalid int64: ".concat(e));return i},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>r||t<i)throw new Error("invalid uint64: ".concat(e));return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)),uDec:(t,n)=>(e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0))}}return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),BZ(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),jZ(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),BZ(e),PZ(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),jZ(e),PZ(e)),dec:(e,t)=>function(e,t){let n=kZ(e,t);const i=2147483648&n.hi;i&&(n=MZ(n.lo,n.hi));const r=LZ(n.lo,n.hi);return i?"-"+r:r}(e,t),uDec:(e,t)=>LZ(e,t)}}();function BZ(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function jZ(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}var GZ;function WZ(e,t){switch(e){case GZ.STRING:return"";case GZ.BOOL:return!1;case GZ.DOUBLE:case GZ.FLOAT:return 0;case GZ.INT64:case GZ.UINT64:case GZ.SFIXED64:case GZ.FIXED64:case GZ.SINT64:return t?"0":FZ.zero;case GZ.BYTES:return new Uint8Array(0);default:return 0}}!function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(GZ||(GZ={}));const KZ=2,HZ=Symbol.for("reflect unsafe local");function YZ(e,t){const n=e[t.localName].case;return void 0===n?n:t.fields.find((e=>e.localName===n))}function XZ(e,t){return Object.prototype.hasOwnProperty.call(e,t)&&void 0!==e[t]}function JZ(e,t){if(t.oneof){const n=e[t.oneof.localName];return n.case===t.localName?n.value:void 0}return e[t.localName]}function zZ(e,t,n){t.oneof?e[t.oneof.localName]={case:t.localName,value:n}:e[t.localName]=n}function ZZ(e){for(const t of e.field)XZ(t,"jsonName")||(t.jsonName=XW(t.name));e.nestedType.forEach(ZZ)}var qZ=lK,QZ=Array.isArray||function(e){return"Array"===qZ(e)},$Z=XX,eq=QZ,tq=sK(Sr([])),nq=[1,2];$Z({target:"Array",proto:!0,forced:String(nq)===String(Sr(nq).call(nq))},{reverse:function(){return eq(this)&&(this.length=this.length),tq(this)}});var iq=gZ("Array","reverse"),rq=tH,oq=iq,sq=Array.prototype,aq=qW((function(e){var t=Sr(e);return e===sq||rq(sq,e)&&t===Sr(sq)?oq:t}));function*cq(e){switch(e.kind){case"file":for(const t of e.messages)yield t,yield*cq(t);yield*e.enums,yield*e.services,yield*e.extensions;break;case"message":for(const t of e.nestedMessages)yield t,yield*cq(t);yield*e.nestedEnums,yield*e.nestedExtensions}}function dq(){const e=function(){const e=new Map,t=new Map,n=new Map;return{kind:"registry",types:e,extendees:t,[Symbol.iterator]:()=>IZ(e).call(e),get files(){return IZ(n).call(n)},addFile(e,t,i){if(n.set(e.proto.name,e),!t)for(const t of cq(e))this.add(t);if(i)for(const n of e.dependencies)this.addFile(n,t,i)},add(n){if("extension"==n.kind){let e=t.get(n.extendee.typeName);e||t.set(n.extendee.typeName,e=new Map),e.set(n.number,n)}e.set(n.typeName,n)},get:t=>e.get(t),getFile:e=>n.get(e),getMessage(t){const n=e.get(t);return"message"==(null==n?void 0:n.kind)?n:void 0},getEnum(t){const n=e.get(t);return"enum"==(null==n?void 0:n.kind)?n:void 0},getExtension(t){const n=e.get(t);return"extension"==(null==n?void 0:n.kind)?n:void 0},getExtensionFor(e,n){var i;return null===(i=t.get(e.typeName))||void 0===i?void 0:i.get(n)},getService(t){const n=e.get(t);return"service"==(null==n?void 0:n.kind)?n:void 0}}}();for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];if(!n.length)return e;if("$typeName"in n[0]&&"google.protobuf.FileDescriptorSet"==n[0].$typeName){for(const t of n[0].file)wq(t,e);return e}if("$typeName"in n[0]){const t=n[0],i=n[1],o=new Set;for(const n of aq(r=[t,...function t(n){const r=[];for(const t of n.dependency){if(null!=e.getFile(t))continue;if(o.has(t))continue;const s=i(t);if(!s)throw new Error("Unable to resolve ".concat(t,", imported by ").concat(n.name));"kind"in s?e.addFile(s,!1,!0):(o.add(s.name),r.push(s))}return r.concat(...r.map(t))}(t)]).call(r)){var r;wq(n,e)}}else for(const t of n)for(const n of t.files)e.addFile(n);return e}const lq=998,uq=999,hq=9,pq=10,_q=11,Eq=12,mq=14,fq=3,gq=2,Sq=1,Tq=0,Rq=1,vq=2,yq=3,Cq=1,bq=2,Iq=1,Aq={998:{fieldPresence:1,enumType:2,repeatedFieldEncoding:2,utf8Validation:3,messageEncoding:1,jsonFormat:2,enforceNamingStyle:2,defaultSymbolVisibility:1},999:{fieldPresence:2,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1e3:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:2,defaultSymbolVisibility:1},1001:{fieldPresence:1,enumType:1,repeatedFieldEncoding:1,utf8Validation:2,messageEncoding:1,jsonFormat:1,enforceNamingStyle:1,defaultSymbolVisibility:2}};function wq(e,t){var n,i;const r={kind:"file",proto:e,deprecated:null!==(i=null===(n=e.options)||void 0===n?void 0:n.deprecated)&&void 0!==i&&i,edition:Uq(e),name:e.name.replace(/\.proto$/,""),dependencies:Vq(e,t),enums:[],messages:[],extensions:[],services:[],toString:()=>"file ".concat(e.name)},o=new Map,s={get:e=>o.get(e),add(e){var t;Kq(!0===(null===(t=e.proto.options)||void 0===t?void 0:t.mapEntry)),o.set(e.typeName,e)}};for(const n of e.enumType)Dq(n,r,void 0,t);for(const n of e.messageType)Pq(n,r,void 0,t,s);for(const n of e.service)Lq(n,r,t);Oq(r,t);for(const e of IZ(o).call(o))Nq(e,t,s);for(const e of r.messages)Nq(e,t,s),Oq(e,t);t.addFile(r,!0)}function Oq(e,t){switch(e.kind){case"file":for(const n of e.proto.extension){const i=Mq(n,e,t);e.extensions.push(i),t.add(i)}break;case"message":for(const n of e.proto.extension){const i=Mq(n,e,t);e.nestedExtensions.push(i),t.add(i)}for(const n of e.nestedMessages)Oq(n,t)}}function Nq(e,t,n){const i=e.proto.oneofDecl.map((t=>function(e,t){return{kind:"oneof",proto:e,deprecated:!1,parent:t,fields:[],name:e.name,localName:zW(XW(e.name)),toString(){return"oneof ".concat(t.typeName,".").concat(this.name)}}}(t,e))),r=new Set;for(const o of e.proto.field){const s=Bq(o,i),a=Mq(o,e,t,s,n);e.fields.push(a),e.field[a.localName]=a,void 0===s?e.members.push(a):(s.fields.push(a),r.has(s)||(r.add(s),e.members.push(s)))}for(const t of i.filter((e=>r.has(e))))e.oneofs.push(t);for(const i of e.nestedMessages)Nq(i,t,n)}function Dq(e,t,n,i){var r,o,s,a,c;const d=function(e,t){const n=((i=e).substring(0,1)+i.substring(1).replace(/[A-Z]/g,(e=>"_"+e))).toLowerCase()+"_";var i;for(const e of t){if(!e.name.toLowerCase().startsWith(n))return;const t=e.name.substring(n.length);if(0==t.length)return;if(/^\d/.test(t))return}return n}(e.name,e.value),l={kind:"enum",proto:e,deprecated:null!==(o=null===(r=e.options)||void 0===r?void 0:r.deprecated)&&void 0!==o&&o,file:t,parent:n,open:!0,name:e.name,typeName:xq(e,n,t),value:{},values:[],sharedPrefix:d,toString(){return"enum ".concat(this.typeName)}};l.open=function(e){var t;return Iq==Wq("enumType",{proto:e.proto,parent:null!==(t=e.parent)&&void 0!==t?t:e.file})}(l),i.add(l);for(const t of e.value){const e=t.name;IZ(l).push(l.value[t.number]={kind:"enum_value",proto:t,deprecated:null!==(a=null===(s=t.options)||void 0===s?void 0:s.deprecated)&&void 0!==a&&a,parent:l,name:e,localName:zW(null==d?e:e.substring(d.length)),number:t.number,toString:()=>"enum value ".concat(l.typeName,".").concat(e)})}(null!==(c=null==n?void 0:n.nestedEnums)&&void 0!==c?c:t.enums).push(l)}function Pq(e,t,n,i,r){var o,s,a,c;const d={kind:"message",proto:e,deprecated:null!==(s=null===(o=e.options)||void 0===o?void 0:o.deprecated)&&void 0!==s&&s,file:t,parent:n,name:e.name,typeName:xq(e,n,t),fields:[],field:{},oneofs:[],members:[],nestedEnums:[],nestedMessages:[],nestedExtensions:[],toString(){return"message ".concat(this.typeName)}};!0===(null===(a=e.options)||void 0===a?void 0:a.mapEntry)?r.add(d):((null!==(c=null==n?void 0:n.nestedMessages)&&void 0!==c?c:t.messages).push(d),i.add(d));for(const n of e.enumType)Dq(n,t,d,i);for(const n of e.nestedType)Pq(n,t,d,i,r)}function Lq(e,t,n){var i,r;const o={kind:"service",proto:e,deprecated:null!==(r=null===(i=e.options)||void 0===i?void 0:i.deprecated)&&void 0!==r&&r,file:t,name:e.name,typeName:xq(e,void 0,t),methods:[],method:{},toString(){return"service ".concat(this.typeName)}};t.services.push(o),n.add(o);for(const t of e.method){const e=kq(t,o,n);o.methods.push(e),o.method[e.localName]=e}}function kq(e,t,n){var i,r,o,s;let a;a=e.clientStreaming&&e.serverStreaming?"bidi_streaming":e.clientStreaming?"client_streaming":e.serverStreaming?"server_streaming":"unary";const c=n.getMessage(Fq(e.inputType)),d=n.getMessage(Fq(e.outputType));Kq(c,"invalid MethodDescriptorProto: input_type ".concat(e.inputType," not found")),Kq(d,"invalid MethodDescriptorProto: output_type ".concat(e.inputType," not found"));const l=e.name;return{kind:"rpc",proto:e,deprecated:null!==(r=null===(i=e.options)||void 0===i?void 0:i.deprecated)&&void 0!==r&&r,parent:t,name:l,localName:zW(l.length?zW(l[0].toLowerCase()+l.substring(1)):l),methodKind:a,input:c,output:d,idempotency:null!==(s=null===(o=e.options)||void 0===o?void 0:o.idempotencyLevel)&&void 0!==s?s:Tq,toString:()=>"rpc ".concat(t.typeName,".").concat(l)}}function Mq(e,t,n,i,r){var o,s,a;const c=void 0===r,d={kind:"field",proto:e,deprecated:null!==(s=null===(o=e.options)||void 0===o?void 0:o.deprecated)&&void 0!==s&&s,name:e.name,number:e.number,scalar:void 0,message:void 0,enum:void 0,presence:jq(e,i,c,t),listKind:void 0,mapKind:void 0,mapKey:void 0,delimitedEncoding:void 0,packed:void 0,longAsString:!1,getDefaultValue:void 0};if(c){const i="file"==t.kind?t:t.file,r="file"==t.kind?void 0:t,o=xq(e,r,i);d.kind="extension",d.file=i,d.parent=r,d.oneof=void 0,d.typeName=o,d.jsonName="[".concat(o,"]"),d.toString=()=>"extension ".concat(o);const s=n.getMessage(Fq(e.extendee));Kq(s,"invalid FieldDescriptorProto: extendee ".concat(e.extendee," not found")),d.extendee=s}else{const n=t;Kq("message"==n.kind),d.parent=n,d.oneof=i,d.localName=i?XW(e.name):zW(XW(e.name)),d.jsonName=e.jsonName,d.toString=()=>"field ".concat(n.typeName,".").concat(e.name)}const l=e.label,u=e.type,h=null===(a=e.options)||void 0===a?void 0:a.jstype;if(l===fq){const i=u==_q?null==r?void 0:r.get(Fq(e.typeName)):void 0;if(i){d.fieldKind="map";const e=function(e){const t=e.fields.find((e=>1===e.number)),n=e.fields.find((e=>2===e.number));return Kq(t&&"scalar"==t.fieldKind&&t.scalar!=GZ.BYTES&&t.scalar!=GZ.FLOAT&&t.scalar!=GZ.DOUBLE&&n&&"list"!=n.fieldKind&&"map"!=n.fieldKind),{key:t,value:n}}(i),t=e.key,n=e.value;return d.mapKey=t.scalar,d.mapKind=n.fieldKind,d.message=n.message,d.delimitedEncoding=!1,d.enum=n.enum,d.scalar=n.scalar,d}switch(d.fieldKind="list",u){case _q:case pq:d.listKind="message",d.message=n.getMessage(Fq(e.typeName)),Kq(d.message),d.delimitedEncoding=Gq(e,t);break;case mq:d.listKind="enum",d.enum=n.getEnum(Fq(e.typeName)),Kq(d.enum);break;default:d.listKind="scalar",d.scalar=u,d.longAsString=h==Sq}return d.packed=function(e,t){if(e.label!=fq)return!1;switch(e.type){case hq:case Eq:case pq:case _q:return!1}const n=e.options;return n&&XZ(n,"packed")?n.packed:Cq==Wq("repeatedFieldEncoding",{proto:e,parent:t})}(e,t),d}switch(u){case _q:case pq:d.fieldKind="message",d.message=n.getMessage(Fq(e.typeName)),Kq(d.message,"invalid FieldDescriptorProto: type_name ".concat(e.typeName," not found")),d.delimitedEncoding=Gq(e,t),d.getDefaultValue=()=>{};break;case mq:{const t=n.getEnum(Fq(e.typeName));Kq(void 0!==t,"invalid FieldDescriptorProto: type_name ".concat(e.typeName," not found")),d.fieldKind="enum",d.enum=n.getEnum(Fq(e.typeName)),d.getDefaultValue=()=>XZ(e,"defaultValue")?function(e,t){const n=IZ(e).find((e=>e.name===t));if(!n)throw new Error("cannot parse ".concat(e," default value: ").concat(t));return n.number}(t,e.defaultValue):void 0;break}default:d.fieldKind="scalar",d.scalar=u,d.longAsString=h==Sq,d.getDefaultValue=()=>XZ(e,"defaultValue")?function(e,t){switch(e){case GZ.STRING:return t;case GZ.BYTES:{const n=function(e){const t=[],n={tail:e,c:"",next(){return 0!=this.tail.length&&(this.c=this.tail[0],this.tail=this.tail.substring(1),!0)},take(e){if(this.tail.length>=e){const t=this.tail.substring(0,e);return this.tail=this.tail.substring(e),t}return!1}};for(;n.next();)if("\\"===n.c){if(n.next())switch(n.c){case"\\":t.push(n.c.charCodeAt(0));break;case"b":t.push(8);break;case"f":t.push(12);break;case"n":t.push(10);break;case"r":t.push(13);break;case"t":t.push(9);break;case"v":t.push(11);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{const e=n.c,i=n.take(2);if(!1===i)return!1;const r=parseInt(e+i,8);if(Number.isNaN(r))return!1;t.push(r);break}case"x":{const e=n.c,i=n.take(2);if(!1===i)return!1;const r=parseInt(e+i,16);if(Number.isNaN(r))return!1;t.push(r);break}case"u":{const e=n.c,i=n.take(4);if(!1===i)return!1;const r=parseInt(e+i,16);if(Number.isNaN(r))return!1;const o=new Uint8Array(4);new DataView(o.buffer).setInt32(0,r,!0),t.push(o[0],o[1],o[2],o[3]);break}case"U":{const e=n.c,i=n.take(8);if(!1===i)return!1;const r=FZ.uEnc(e+i),o=new Uint8Array(8),s=new DataView(o.buffer);s.setInt32(0,r.lo,!0),s.setInt32(4,r.hi,!0),t.push(o[0],o[1],o[2],o[3],o[4],o[5],o[6],o[7]);break}}}else t.push(n.c.charCodeAt(0));return new Uint8Array(t)}(t);if(!1===n)throw new Error("cannot parse ".concat(GZ[e]," default value: ").concat(t));return n}case GZ.INT64:case GZ.SFIXED64:case GZ.SINT64:return FZ.parse(t);case GZ.UINT64:case GZ.FIXED64:return FZ.uParse(t);case GZ.DOUBLE:case GZ.FLOAT:switch(t){case"inf":return Number.POSITIVE_INFINITY;case"-inf":return Number.NEGATIVE_INFINITY;case"nan":return Number.NaN;default:return parseFloat(t)}case GZ.BOOL:return"true"===t;case GZ.INT32:case GZ.UINT32:case GZ.SINT32:case GZ.FIXED32:case GZ.SFIXED32:return parseInt(t,10)}}(u,e.defaultValue):void 0}return d}function Uq(e){switch(e.syntax){case"":case"proto2":return lq;case"proto3":return uq;case"editions":if(e.edition in Aq)return e.edition;throw new Error("".concat(e.name,": unsupported edition"));default:throw new Error("".concat(e.name,': unsupported syntax "').concat(e.syntax,'"'))}}function Vq(e,t){return e.dependency.map((n=>{const i=t.getFile(n);if(!i)throw new Error("Cannot find ".concat(n,", imported by ").concat(e.name));return i}))}function xq(e,t,n){let i;return i=t?"".concat(t.typeName,".").concat(e.name):n.proto.package.length>0?"".concat(n.proto.package,".").concat(e.name):"".concat(e.name),i}function Fq(e){return e.startsWith(".")?e.substring(1):e}function Bq(e,t){if(!XZ(e,"oneofIndex"))return;if(e.proto3Optional)return;const n=t[e.oneofIndex];return Kq(n,"invalid FieldDescriptorProto: oneof #".concat(e.oneofIndex," for field #").concat(e.number," not found")),n}function jq(e,t,n,i){if(e.label==gq)return yq;if(e.label==fq)return vq;if(t||e.proto3Optional)return Rq;if(n)return Rq;const r=Wq("fieldPresence",{proto:e,parent:i});return r!=vq||e.type!=_q&&e.type!=pq?r:Rq}function Gq(e,t){return e.type==pq||bq==Wq("messageEncoding",{proto:e,parent:t})}function Wq(e,t){var n,i;const r=null===(n=t.proto.options)||void 0===n?void 0:n.features;if(r){const t=r[e];if(0!=t)return t}if("kind"in t){if("message"==t.kind)return Wq(e,null!==(i=t.parent)&&void 0!==i?i:t.file);const n=Aq[t.edition];if(!n)throw new Error("feature default for edition ".concat(t.edition," not found"));return n[e]}return Wq(e,t.parent)}function Kq(e,t){if(!e)throw new Error(t)}function Hq(e){var t,n,i,r,o,s,a,c;const d=Object.create({visibility:0});return Object.assign(d,{$typeName:"google.protobuf.DescriptorProto",name:e.name,field:null!==(n=null===(t=e.field)||void 0===t?void 0:t.map(Yq))&&void 0!==n?n:[],extension:[],nestedType:null!==(r=null===(i=e.nestedType)||void 0===i?void 0:i.map(Hq))&&void 0!==r?r:[],enumType:null!==(s=null===(o=e.enumType)||void 0===o?void 0:o.map(Jq))&&void 0!==s?s:[],extensionRange:null!==(c=null===(a=e.extensionRange)||void 0===a?void 0:a.map((e=>Object.assign({$typeName:"google.protobuf.DescriptorProto.ExtensionRange"},e))))&&void 0!==c?c:[],oneofDecl:[],reservedRange:[],reservedName:[]})}function Yq(e){const t=Object.create({label:1,typeName:"",extendee:"",defaultValue:"",oneofIndex:0,jsonName:"",proto3Optional:!1});return Object.assign(t,Object.assign(Object.assign({$typeName:"google.protobuf.FieldDescriptorProto"},e),{options:e.options?Xq(e.options):void 0}))}function Xq(e){var t,n,i;const r=Object.create({ctype:0,packed:!1,jstype:0,lazy:!1,unverifiedLazy:!1,deprecated:!1,weak:!1,debugRedact:!1,retention:0});return Object.assign(r,Object.assign(Object.assign({$typeName:"google.protobuf.FieldOptions"},e),{targets:null!==(t=e.targets)&&void 0!==t?t:[],editionDefaults:null!==(i=null===(n=e.editionDefaults)||void 0===n?void 0:n.map((e=>Object.assign({$typeName:"google.protobuf.FieldOptions.EditionDefault"},e))))&&void 0!==i?i:[],uninterpretedOption:[]}))}function Jq(e){const t=Object.create({visibility:0});return Object.assign(t,{$typeName:"google.protobuf.EnumDescriptorProto",name:e.name,reservedName:[],reservedRange:[],value:e.value.map((e=>Object.assign({$typeName:"google.protobuf.EnumValueDescriptorProto"},e)))})}function zq(e){const t=function(){if(!Qq){Qq=[];const e=$q("std");for(let t=0;t<e.length;t++)Qq[e[t].charCodeAt(0)]=t;Qq["-".charCodeAt(0)]=e.indexOf("+"),Qq["_".charCodeAt(0)]=e.indexOf("/")}return Qq}();let n=3*e.length/4;"="==e[e.length-2]?n-=2:"="==e[e.length-1]&&(n-=1);let i,r=new Uint8Array(n),o=0,s=0,a=0;for(let n=0;n<e.length;n++){if(i=t[e.charCodeAt(n)],void 0===i)switch(e[n]){case"=":s=0;case"\n":case"\r":case"\t":case" ":continue;default:throw Error("invalid base64 string")}switch(s){case 0:a=i,s=1;break;case 1:r[o++]=a<<2|(48&i)>>4,a=i,s=2;break;case 2:r[o++]=(15&a)<<4|(60&i)>>2,a=i,s=3;break;case 3:r[o++]=(3&a)<<6|i,s=0}}if(1==s)throw Error("invalid base64 string");return r.subarray(0,o)}let Zq,qq,Qq;function $q(e){return Zq||(Zq="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),qq=Zq.slice(0,-2).concat("-","_")),"url"==e?qq:Zq}XX({target:"Array",stat:!0},{isArray:QZ});var eQ=qW(zK.Array.isArray),tQ=TypeError,nQ=function(e){if(e>9007199254740991)throw new tQ("Maximum allowed index exceeded");return e},iQ=LK,rQ=kK,oQ=LY,sQ=function(e,t,n){iQ?rQ.f(e,t,oQ(0,n)):e[t]=n},aQ=LK,cQ=QZ,dQ=TypeError,lQ=Object.getOwnPropertyDescriptor,uQ=aQ&&!function(){if(void 0!==this)return!0;try{Object.defineProperty([],"length",{writable:!1}).length=1}catch(e){return e instanceof TypeError}}()?function(e,t){if(cQ(e)&&!lQ(e,"length").writable)throw new dQ("Cannot set read only .length");return e.length=t}:function(e,t){return e.length=t},hQ=AK,pQ=jH,_Q=sK(Function.toString);hQ(pQ.inspectSource)||(pQ.inspectSource=function(e){return _Q(e)});var EQ=pQ.inspectSource,mQ=sK,fQ=eK,gQ=AK,SQ=Az,TQ=EQ,RQ=function(){},vQ=eH("Reflect","construct"),yQ=/^\s*(?:class|function)\b/,CQ=mQ(yQ.exec),bQ=!yQ.test(RQ),IQ=function(e){if(!gQ(e))return!1;try{return vQ(RQ,[],e),!0}catch(e){return!1}},AQ=function(e){if(!gQ(e))return!1;switch(SQ(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return bQ||!!CQ(yQ,TQ(e))}catch(e){return!0}};AQ.sham=!0;var wQ=!vQ||fQ((function(){var e;return IQ(IQ.call)||!IQ(Object)||!IQ((function(){e=!0}))||e}))?AQ:IQ,OQ=QZ,NQ=wQ,DQ=PK,PQ=dY("species"),LQ=Array,kQ=function(e,t){return new(function(e){var t;return OQ(e)&&(t=e.constructor,(NQ(t)&&(t===LQ||OQ(t.prototype))||DQ(t)&&null===(t=t[PQ]))&&(t=void 0)),void 0===t?LQ:t}(e))(0===t?0:t)},MQ=eK,UQ=uH,VQ=dY("species"),xQ=function(e){return UQ>=51||!MQ((function(){var t=[];return(t.constructor={})[VQ]=function(){return{foo:1}},1!==t[e](Boolean).foo}))},FQ=XX,BQ=eK,jQ=QZ,GQ=PK,WQ=YH,KQ=uJ,HQ=nQ,YQ=sQ,XQ=uQ,JQ=kQ,zQ=xQ,ZQ=uH,qQ=dY("isConcatSpreadable"),QQ=ZQ>=51||!BQ((function(){var e=[];return e[qQ]=!1,e.concat()[0]!==e})),$Q=function(e){if(!GQ(e))return!1;var t=e[qQ];return void 0!==t?!!t:jQ(e)};FQ({target:"Array",proto:!0,arity:1,forced:!QQ||!zQ("concat")},{concat:function(e){var t,n,i,r,o,s=WQ(this),a=JQ(s,0),c=0;for(t=-1,i=arguments.length;t<i;t++)if($Q(o=-1===t?s:arguments[t]))for(r=KQ(o),HQ(c+r),n=0;n<r;n++,c++)n in o&&YQ(a,c,o[n]);else HQ(c+1),YQ(a,c++,o);return XQ(a,c),a}});var e$=Az,t$=String,n$=function(e){if("Symbol"===e$(e))throw new TypeError("Cannot convert a Symbol value to a string");return t$(e)},i$={},r$=vJ,o$=yJ.concat("length","prototype");i$.f=Object.getOwnPropertyNames||function(e){return r$(e,o$)};var s$={},a$=sK([].slice),c$=lK,d$=vK,l$=i$.f,u$=a$,h$="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];s$.f=function(e){return h$&&"Window"===c$(e)?function(e){try{return l$(e)}catch(e){return u$(h$)}}(e):l$(d$(e))};var p$={};p$.f=Object.getOwnPropertySymbols;var _$=kK,E$={},m$=dY;E$.f=m$;var f$=zK,g$=zH,S$=E$,T$=kK.f,R$=function(e){var t=f$.Symbol||(f$.Symbol={});g$(t,e)||T$(t,e,{value:S$.f(e)})},v$=JK,y$=eH,C$=dY,b$=cz,I$=function(){var e=y$("Symbol"),t=e&&e.prototype,n=t&&t.valueOf,i=C$("toPrimitive");t&&!t[i]&&b$(t,i,(function(e){return v$(n,this)}),{arity:1})},A$=MX,w$=EK,O$=YH,N$=uJ,D$=kQ,P$=sQ,L$=function(e){var t=1===e,n=2===e,i=3===e,r=4===e,o=6===e,s=7===e,a=5===e||o;return function(c,d,l){for(var u,h,p=O$(c),_=w$(p),E=N$(_),m=A$(d,l),f=0,g=0,S=t?D$(c,E):n||s?D$(c,0):void 0;E>f;f++)if((a||f in _)&&(h=m(u=_[f],f,p),e))if(t)P$(S,f,h);else if(h)switch(e){case 3:return!0;case 5:return u;case 6:return f;case 2:P$(S,g++,u)}else switch(e){case 4:return!1;case 7:P$(S,g++,u)}return o?-1:i||r?r:S}},k$={forEach:L$(0),map:L$(1),filter:L$(2),some:L$(3),every:L$(4),find:L$(5),findIndex:L$(6),filterReject:L$(7)},M$=XX,U$=bK,V$=JK,x$=sK,F$=LK,B$=EH,j$=eK,G$=zH,W$=tH,K$=HK,H$=vK,Y$=gY,X$=n$,J$=LY,z$=qJ,Z$=IJ,q$=i$,Q$=s$,$$=p$,e0=dX,t0=kK,n0=eJ,i0=lX,r0=cz,o0=WH,s0=BY,a0=eY,c0=dY,d0=E$,l0=R$,u0=I$,h0=Uz,p0=eX,_0=k$.forEach,E0=FY("hidden"),m0="Symbol",f0="prototype",g0=p0.set,S0=p0.getterFor(m0),T0=Object[f0],R0=U$.Symbol,v0=R0&&R0[f0],y0=U$.RangeError,C0=U$.TypeError,b0=U$.QObject,I0=e0.f,A0=t0.f,w0=Q$.f,O0=i0.f,N0=x$([].push),D0=o0("symbols"),P0=o0("op-symbols"),L0=o0("wks"),k0=!b0||!b0[f0]||!b0[f0].findChild,M0=function(e,t,n){var i=I0(T0,t);return i&&delete T0[t],A0(e,t,n),i&&e!==T0&&A0(T0,t,i),e},U0=F$&&j$((function(){return 7!==z$(A0({},"a",{get:function(){return A0(this,"a",{value:7}).a}})).a}))?M0:A0,V0=function(e,t){var n=D0[e]=z$(v0);return g0(n,{type:m0,tag:e,description:t}),F$||(n.description=t),n},x0=function(e,t,n){e===T0&&x0(P0,t,n),K$(e);var i=Y$(t);return K$(n),G$(D0,i)?(("enumerable"in n?!n.enumerable:!G$(e,i)||G$(e,E0)&&e[E0][i])?(G$(e,E0)||A0(e,E0,J$(1,z$(null))),e[E0][i]=!0):(G$(e,E0)&&e[E0][i]&&(e[E0][i]=!1),n=z$(n,{enumerable:J$(0,!1)})),U0(e,i,n)):A0(e,i,n)},F0=function(e,t){K$(e);var n=H$(t),i=Z$(n).concat(W0(n));return _0(i,(function(t){F$&&!V$(B0,n,t)||x0(e,t,n[t])})),e},B0=function(e){var t=Y$(e),n=V$(O0,this,t);return!(this===T0&&G$(D0,t)&&!G$(P0,t))&&(!(n||!G$(this,t)||!G$(D0,t)||G$(this,E0)&&this[E0][t])||n)},j0=function(e,t){var n=H$(e),i=Y$(t);if(n!==T0||!G$(D0,i)||G$(P0,i)){var r=I0(n,i);return!r||!G$(D0,i)||G$(n,E0)&&n[E0][i]||(r.enumerable=!0),r}},G0=function(e){var t=w0(H$(e)),n=[];return _0(t,(function(e){G$(D0,e)||G$(s0,e)||N0(n,e)})),n},W0=function(e){var t=e===T0,n=w0(t?P0:H$(e)),i=[];return _0(n,(function(e){!G$(D0,e)||t&&!G$(T0,e)||N0(i,D0[e])})),i};B$||(r0(v0=(R0=function(){if(W$(v0,this))throw new C0("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?X$(arguments[0]):void 0,t=a0(e),n=function(e){var i=void 0===this?U$:this;i===T0&&V$(n,P0,e),G$(i,E0)&&G$(i[E0],t)&&(i[E0][t]=!1);var r=J$(1,e);try{U0(i,t,r)}catch(e){if(!(e instanceof y0))throw e;M0(i,t,r)}};return F$&&k0&&U0(T0,t,{configurable:!0,set:n}),V0(t,e)})[f0],"toString",(function(){return S0(this).tag})),r0(R0,"withoutSetter",(function(e){return V0(a0(e),e)})),i0.f=B0,t0.f=x0,n0.f=F0,e0.f=j0,q$.f=Q$.f=G0,$$.f=W0,d0.f=function(e){return V0(c0(e),e)},F$&&function(e,t,n){_$.f(e,t,n)}(v0,"description",{configurable:!0,get:function(){return S0(this).description}})),M$({global:!0,constructor:!0,wrap:!0,forced:!B$,sham:!B$},{Symbol:R0}),_0(Z$(L0),(function(e){l0(e)})),M$({target:m0,stat:!0,forced:!B$},{useSetter:function(){k0=!0},useSimple:function(){k0=!1}}),M$({target:"Object",stat:!0,forced:!B$,sham:!F$},{create:function(e,t){return void 0===t?z$(e):F0(z$(e),t)},defineProperty:x0,defineProperties:F0,getOwnPropertyDescriptor:j0}),M$({target:"Object",stat:!0,forced:!B$},{getOwnPropertyNames:G0}),u0(),h0(R0,m0),s0[E0]=!0;var K0=EH&&!!Symbol.for&&!!Symbol.keyFor,H0=XX,Y0=eH,X0=zH,J0=n$,z0=WH,Z0=K0,q0=z0("string-to-symbol-registry"),Q0=z0("symbol-to-string-registry");H0({target:"Symbol",stat:!0,forced:!Z0},{for:function(e){var t=J0(e);if(X0(q0,t))return q0[t];var n=Y0("Symbol")(t);return q0[t]=n,Q0[n]=t,n}});var $0=XX,e1=zH,t1=RH,n1=yH,i1=K0,r1=WH("symbol-to-string-registry");$0({target:"Symbol",stat:!0,forced:!i1},{keyFor:function(e){if(!t1(e))throw new TypeError(n1(e)+" is not a symbol");if(e1(r1,e))return r1[e]}});var o1=PK,s1=eX.get,a1=sK,c1=zH,d1=SyntaxError,l1=parseInt,u1=String.fromCharCode,h1=a1("".charAt),p1=a1("".slice),_1=a1(/./.exec),E1={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":"\n","\\r":"\r","\\t":"\t"},m1=/^[\da-f]{4}$/i,f1=/^[\u0000-\u001F]$/,g1=!eK((function(){var e="9007199254740993",t=JSON.rawJSON(e);return!JSON.isRawJSON(t)||JSON.stringify(t)!==e})),S1=XX,T1=eH,R1=oX,v1=JK,y1=sK,C1=eK,b1=QZ,I1=AK,A1=RH,w1=lK,O1=n$,N1=a$,D1=function(e,t){for(var n=!0,i="";t<e.length;){var r=h1(e,t);if("\\"===r){var o=p1(e,t,t+2);if(c1(E1,o))i+=E1[o],t+=2;else{if("\\u"!==o)throw new d1('Unknown escape sequence: "'+o+'"');var s=p1(e,t+=2,t+4);if(!_1(m1,s))throw new d1("Bad Unicode escape at: "+t);i+=u1(l1(s,16)),t+=4}}else{if('"'===r){n=!1,t++;break}if(_1(f1,r))throw new d1("Bad control character in string literal at: "+t);i+=r,t++}}if(n)throw new d1("Unterminated string at: "+t);return{value:i,end:t}},P1=eY,L1=EH,k1=g1,M1=String,U1=T1("JSON","stringify"),V1=y1(/./.exec),x1=y1("".charAt),F1=y1("".charCodeAt),B1=y1("".replace),j1=y1("".slice),G1=y1([].push),W1=y1(1.1.toString),K1=/[\uD800-\uDFFF]/g,H1=/^[\uD800-\uDBFF]$/,Y1=/^[\uDC00-\uDFFF]$/,X1=P1(),J1=X1.length,z1=!L1||C1((function(){var e=T1("Symbol")("stringify detection");return"[null]"!==U1([e])||"{}"!==U1({a:e})||"{}"!==U1(Object(e))})),Z1=C1((function(){return'"\\udf06\\ud834"'!==U1("\udf06\ud834")||'"\\udead"'!==U1("\udead")})),q1=z1?function(e,t){var n=N1(arguments),i=$1(t);if(I1(i)||void 0!==e&&!A1(e))return n[1]=function(e,t){if(I1(i)&&(t=v1(i,this,M1(e),t)),!A1(t))return t},R1(U1,null,n)}:U1,Q1=function(e,t,n){var i=x1(n,t-1),r=x1(n,t+1);return V1(H1,e)&&!V1(Y1,r)||V1(Y1,e)&&!V1(H1,i)?"\\u"+W1(F1(e,0),16):e},$1=function(e){if(I1(e))return e;if(b1(e)){for(var t=e.length,n=[],i=0;i<t;i++){var r=e[i];"string"==typeof r?G1(n,r):"number"!=typeof r&&"Number"!==w1(r)&&"String"!==w1(r)||G1(n,O1(r))}var o=n.length,s=!0;return function(e,t){if(s)return s=!1,t;if(b1(this))return t;for(var i=0;i<o;i++)if(n[i]===e)return t}}};U1&&S1({target:"JSON",stat:!0,arity:3,forced:z1||Z1||!k1},{stringify:function(e,t,n){var i=$1(t),r=[],o=q1(e,(function(e,t){var n=I1(i)?v1(i,this,M1(e),t):t;return!k1&&function(e){if(!o1(e))return!1;var t=s1(e);return!!t&&"RawJSON"===t.type}(n)?X1+(G1(r,n.rawJSON)-1):n}),n);if("string"!=typeof o)return o;if(Z1&&(o=B1(o,K1,Q1)),k1)return o;for(var s="",a=o.length,c=0;c<a;c++){var d=x1(o,c);if('"'===d){var l=D1(o,++c).end-1,u=j1(o,c,l);s+=j1(u,0,J1)===X1?r[j1(u,J1)]:'"'+u+'"',c=l}else s+=d}return s}});var e2=p$,t2=YH;XX({target:"Object",stat:!0,forced:!EH||eK((function(){e2.f(1)}))},{getOwnPropertySymbols:function(e){var t=e2.f;return t?t(t2(e)):[]}}),R$("asyncDispose"),R$("asyncIterator"),R$("dispose"),R$("hasInstance"),R$("isConcatSpreadable"),R$("iterator"),R$("match"),R$("matchAll"),R$("replace"),R$("search"),R$("species"),R$("split");var n2=I$;R$("toPrimitive"),n2();var i2=eH,r2=Uz;R$("toStringTag"),r2(i2("Symbol"),"Symbol"),R$("unscopables"),Uz(bK.JSON,"JSON",!0);var o2=zK.Symbol,s2=dY,a2=kK.f,c2=s2("metadata"),d2=Function.prototype;void 0===d2[c2]&&a2(d2,c2,{value:null}),R$("metadata");var l2=o2,u2=sK,h2=eH("Symbol"),p2=h2.keyFor,_2=u2(h2.prototype.valueOf),E2=h2.isRegisteredSymbol||function(e){try{return void 0!==p2(_2(e))}catch(e){return!1}};XX({target:"Symbol",stat:!0},{isRegisteredSymbol:E2});for(var m2=WH,f2=eH,g2=sK,S2=RH,T2=dY,R2=f2("Symbol"),v2=R2.isWellKnownSymbol,y2=f2("Object","getOwnPropertyNames"),C2=g2(R2.prototype.valueOf),b2=m2("wks"),I2=0,A2=y2(R2),w2=A2.length;I2<w2;I2++)try{var O2=A2[I2];S2(R2[O2])&&T2(O2)}catch(xb){}var N2=function(e){if(v2&&v2(e))return!0;try{for(var t=C2(e),n=0,i=y2(b2),r=i.length;n<r;n++)if(b2[i[n]]==t)return!0}catch(e){}return!1};XX({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:N2}),R$("customMatcher"),R$("observable"),XX({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:E2}),XX({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:N2}),R$("matcher"),R$("metadataKey"),R$("patternMatch"),R$("replaceAll");var D2=qW(l2),P2=sK,L2=rJ,k2=n$,M2=SK,U2=P2("".charAt),V2=P2("".charCodeAt),x2=P2("".slice),F2=function(e){return function(t,n){var i,r,o=k2(M2(t)),s=L2(n),a=o.length;return s<0||s>=a?e?"":void 0:(i=V2(o,s))<55296||i>56319||s+1===a||(r=V2(o,s+1))<56320||r>57343?e?U2(o,s):i:e?x2(o,s,s+2):r-56320+(i-55296<<10)+65536}},B2=(F2(!1),F2(!0)),j2=n$,G2=eX,W2=nZ,K2=iZ,H2="String Iterator",Y2=G2.set,X2=G2.getterFor(H2);W2(String,"String",(function(e){Y2(this,{type:H2,string:j2(e),index:0})}),(function(){var e,t=X2(this),n=t.string,i=t.index;return i>=n.length?K2(void 0,!0):(e=B2(n,i),t.index+=e.length,K2(e,!1))}));var J2=Az,z2=NH,Z2=mK,q2=yK,Q2=dY("iterator"),$2=function(e){if(!Z2(e))return z2(e,Q2)||z2(e,"@@iterator")||q2[J2(e)]},e3=qW($2),t3=YH,n3=uJ,i3=uQ,r3=nQ;XX({target:"Array",proto:!0,arity:1,forced:eK((function(){return 4294967297!==[].push.call({length:4294967296},1)}))||!function(){try{Object.defineProperty([],"length",{writable:!1}).push()}catch(e){return e instanceof TypeError}}()},{push:function(e){var t=t3(this),n=n3(t),i=arguments.length;r3(n+i);for(var r=0;r<i;r++)t[n]=arguments[r],n++;return i3(t,n),n}});var o3=gZ("Array","push"),s3=tH,a3=o3,c3=Array.prototype,d3=qW((function(e){var t=e.push;return e===c3||s3(c3,e)&&t===c3.push?a3:t})),l3=XX,u3=QZ,h3=wQ,p3=PK,_3=cJ,E3=uJ,m3=vK,f3=sQ,g3=uQ,S3=dY,T3=a$,R3=xQ("slice"),v3=S3("species"),y3=Array,C3=Math.max;l3({target:"Array",proto:!0,forced:!R3},{slice:function(e,t){var n,i,r,o=m3(this),s=E3(o),a=_3(e,s),c=_3(void 0===t?s:t,s);if(u3(o)&&(n=o.constructor,(h3(n)&&(n===y3||u3(n.prototype))||p3(n)&&null===(n=n[v3]))&&(n=void 0),n===y3||void 0===n))return T3(o,a,c);for(i=new(void 0===n?y3:n)(C3(c-a,0)),r=0;a<c;a++,r++)a in o&&f3(i,r,o[a]);return g3(i,r),i}});var b3=gZ("Array","slice"),I3=tH,A3=b3,w3=Array.prototype,O3=qW((function(e){var t=e.slice;return e===w3||I3(w3,e)&&t===w3.slice?A3:t})),N3=JK,D3=HK,P3=NH,L3=function(e,t,n){var i,r;D3(e);try{if(!(i=P3(e,"return"))){if("throw"===t)throw n;return n}i=N3(i,e)}catch(e){r=!0,i=e}if("throw"===t)throw n;if(r)throw i;return D3(i),n},k3=HK,M3=L3,U3=yK,V3=dY("iterator"),x3=Array.prototype,F3=JK,B3=AH,j3=HK,G3=yH,W3=$2,K3=TypeError,H3=MX,Y3=JK,X3=YH,J3=function(e,t,n,i){try{return i?t(k3(n)[0],n[1]):t(n)}catch(t){M3(e,"throw",t)}},z3=function(e){return void 0!==e&&(U3.Array===e||x3[V3]===e)},Z3=wQ,q3=uJ,Q3=sQ,$3=uQ,e5=function(e,t){var n=arguments.length<2?W3(e):t;if(B3(n))return j3(F3(n,e));throw new K3(G3(e)+" is not iterable")},t5=$2,n5=L3,i5=Array,r5=dY("iterator"),o5=!1;try{var s5=0,a5={next:function(){return{done:!!s5++}},return:function(){o5=!0}};a5[r5]=function(){return this},Array.from(a5,(function(){throw 2}))}catch(xb){}XX({target:"Array",stat:!0,forced:!function(e,t){try{if(!t&&!o5)return!1}catch(e){return!1}var n=!1;try{var i={};i[r5]=function(){return{next:function(){return{done:n=!0}}}},e(i)}catch(e){}return n}((function(e){Array.from(e)}))},{from:function(e){var t=Z3(this),n=arguments.length,i=n>1?arguments[1]:void 0,r=void 0!==i;r&&(i=H3(i,n>2?arguments[2]:void 0));var o,s,a,c,d,l,u=X3(e),h=t5(u),p=0;if(!h||this===i5&&z3(h))for(o=q3(u),s=t?new this(o):i5(o);o>p;p++)l=r?i(u[p],p):u[p],Q3(s,p,l);else for(s=t?new this:[],d=(c=e5(u,h)).next;!(a=Y3(d,c)).done;p++){l=r?J3(c,i,[a.value,p],!0):a.value;try{Q3(s,p,l)}catch(e){n5(c,"throw",e)}}return $3(s,p),s}});var c5=qW(zK.Array.from);function d5(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,i=new Array(t);n<t;n++)i[n]=e[n];return i}function l5(e,t){return function(e){if(eQ(e))return e}(e)||function(e,t){var n=null==e?null:void 0!==D2&&e3(e)||e["@@iterator"];if(null!=n){var i,r,o,s,a=[],c=!0,d=!1;try{if(o=(n=n.call(e)).next,0===t){if(Object(n)!==n)return;c=!1}else for(;!(c=(i=o.call(n)).done)&&(d3(a).call(a,i.value),a.length!==t);c=!0);}catch(e){d=!0,r=e}finally{try{if(!c&&null!=n.return&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return a}}(e,t)||function(e,t){var n;if(e){if("string"==typeof e)return d5(e,t);var i=O3(n=Object.prototype.toString.call(e)).call(n,8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?c5(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?d5(e,t):void 0}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var u5=yH,h5=TypeError,p5=a$,_5=Math.floor,E5=function(e,t){var n=e.length;if(n<8)for(var i,r,o=1;o<n;){for(r=o,i=e[o];r&&t(e[r-1],i)>0;)e[r]=e[--r];r!==o++&&(e[r]=i)}else for(var s=_5(n/2),a=E5(p5(e,0,s),t),c=E5(p5(e,s),t),d=a.length,l=c.length,u=0,h=0;u<d||h<l;)e[u+h]=u<d&&h<l?t(a[u],c[h])<=0?a[u++]:c[h++]:u<d?a[u++]:c[h++];return e},m5=E5,f5=eK,g5=function(e,t){var n=[][e];return!!n&&f5((function(){n.call(null,t||function(){return 1},1)}))},S5=rH.match(/firefox\/(\d+)/i),T5=!!S5&&+S5[1],R5=/MSIE|Trident/.test(rH),v5=rH.match(/AppleWebKit\/(\d+)\./),y5=!!v5&&+v5[1],C5=XX,b5=sK,I5=AH,A5=YH,w5=uJ,O5=function(e,t){if(!delete e[t])throw new h5("Cannot delete property "+u5(t)+" of "+u5(e))},N5=n$,D5=eK,P5=m5,L5=g5,k5=T5,M5=R5,U5=uH,V5=y5,x5=[],F5=b5(t_(x5)),B5=b5(x5.push),j5=D5((function(){t_(x5).call(x5,void 0)})),G5=D5((function(){t_(x5).call(x5,null)})),W5=L5("sort"),K5=!D5((function(){if(U5)return U5<70;if(!(k5&&k5>3)){if(M5)return!0;if(V5)return V5<603;var e,t,n,i,r="";for(e=65;e<76;e++){switch(t=String.fromCharCode(e),e){case 66:case 69:case 70:case 72:n=3;break;case 68:case 71:n=4;break;default:n=2}for(i=0;i<47;i++)x5.push({k:t+i,v:n})}for(t_(x5).call(x5,(function(e,t){return t.v-e.v})),i=0;i<x5.length;i++)t=x5[i].k.charAt(0),r.charAt(r.length-1)!==t&&(r+=t);return"DGBEFHACIJK"!==r}}));C5({target:"Array",proto:!0,forced:j5||!G5||!W5||!K5},{sort:function(e){void 0!==e&&I5(e);var t=A5(this);if(K5)return void 0===e?F5(t):F5(t,e);var n,i,r=[],o=w5(t);for(i=0;i<o;i++)i in t&&B5(r,t[i]);for(P5(r,function(e){return function(t,n){if(void 0===n)return-1;if(void 0===t)return 1;if(void 0!==e)return+e(t,n)||0;var i=N5(t),r=N5(n);return i===r?0:i>r?1:-1}}(e)),n=w5(r),i=0;i<n;)t[i]=r[i++];for(;i<o;)O5(t,i++);return t}});var H5=gZ("Array","sort"),Y5=tH,X5=H5,J5=Array.prototype,z5=qW((function(e){var t=t_(e);return e===J5||Y5(J5,e)&&t===t_(J5)?X5:t})),Z5=gZ("Array","keys"),q5=Az,Q5=zH,$5=tH,e4=Z5,t4=Array.prototype,n4={DOMTokenList:!0,NodeList:!0},i4=qW((function(e){var t=oL(e);return e===t4||$5(t4,e)&&t===oL(t4)||Q5(n4,q5(e))?e4:t}));function r4(e,t){return!(null===e||"object"!=typeof e||!("$typeName"in e)||"string"!=typeof e.$typeName||void 0!==t&&t.typeName!==e.$typeName)}var o4=XX,s4=Ui(mJ),a4=eK,c4=a4((function(){var e;return!Ui(e=Array(1)).call(e)})),d4=a4((function(){var e;return Ui(e=[,1]).call(e,void 0,1)}));o4({target:"Array",proto:!0,forced:c4||d4},{includes:function(e){return s4(this,e,arguments.length>1?arguments[1]:void 0)}});var l4=gZ("Array","includes"),u4=PK,h4=lK,p4=dY("match"),_4=TypeError,E4=dY("match"),m4=XX,f4=function(e){if(function(e){var t;return u4(e)&&(void 0!==(t=e[p4])?!!t:"RegExp"===h4(e))}(e))throw new _4("The method doesn't accept regular expressions");return e},g4=SK,S4=n$,T4=sK("".indexOf);m4({target:"String",proto:!0,forced:!function(e){var t=/./;try{"/./"[e](t)}catch(n){try{return t[E4]=!1,"/./"[e](t)}catch(e){}}return!1}("includes")},{includes:function(e){return!!~T4(S4(g4(this)),S4(f4(e)),arguments.length>1?arguments[1]:void 0)}});var R4=gZ("String","includes"),v4=tH,y4=l4,C4=R4,b4=Array.prototype,I4=String.prototype,A4=qW((function(e){var t=Ui(e);return e===b4||v4(b4,e)&&t===Ui(b4)?y4:"string"==typeof e||e===I4||v4(I4,e)&&t===Ui(I4)?C4:t}));const w4=["FieldValueInvalidError","FieldListRangeError","ForeignFieldError"];class O4 extends Error{constructor(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"FieldValueInvalidError";super(t),this.name=n,this.field=()=>e}}function N4(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function D4(e,t){var n,i,r,o;if(N4(e)&&HZ in e&&"add"in e&&"field"in e&&"function"==typeof e.field){if(void 0!==t){const s=t,a=e.field();return s.listKind==a.listKind&&s.scalar===a.scalar&&(null===(n=s.message)||void 0===n?void 0:n.typeName)===(null===(i=a.message)||void 0===i?void 0:i.typeName)&&(null===(r=s.enum)||void 0===r?void 0:r.typeName)===(null===(o=a.enum)||void 0===o?void 0:o.typeName)}return!0}return!1}function P4(e,t){var n,i,r,o;if(N4(e)&&HZ in e&&"has"in e&&"field"in e&&"function"==typeof e.field){if(void 0!==t){const s=t,a=e.field();return s.mapKey===a.mapKey&&s.mapKind==a.mapKind&&s.scalar===a.scalar&&(null===(n=s.message)||void 0===n?void 0:n.typeName)===(null===(i=a.message)||void 0===i?void 0:i.typeName)&&(null===(r=s.enum)||void 0===r?void 0:r.typeName)===(null===(o=a.enum)||void 0===o?void 0:o.typeName)}return!0}return!1}function L4(e,t){return N4(e)&&HZ in e&&"desc"in e&&N4(e.desc)&&"message"===e.desc.kind&&(void 0===t||e.desc.typeName==t.typeName)}const k4=Symbol.for("@bufbuild/protobuf/text-encoding");function M4(){if(null==wZ[k4]){const e=new wZ.TextEncoder,t=new wZ.TextDecoder;wZ[k4]={encodeUtf8:t=>e.encode(t),decodeUtf8:e=>t.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(e){return!1}}}}return wZ[k4]}var U4;!function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(U4||(U4={}));const V4=34028234663852886e22,x4=-34028234663852886e22,F4=4294967295,B4=2147483647,j4=-2147483648;class G4{constructor(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M4().encodeUtf8;this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw new Error("invalid state, fork stack empty");return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(H4(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return K4(e),VZ(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.encodeUtf8(e);return this.uint32(t.byteLength),this.raw(t)}float(e){!function(e){if("string"==typeof e){const t=e;if(e=Number(e),Number.isNaN(e)&&"NaN"!==t)throw new Error("invalid float32: "+t)}else if("number"!=typeof e)throw new Error("invalid float32: "+typeof e);if(Number.isFinite(e)&&(e>V4||e<x4))throw new Error("invalid float32: "+e)}(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){H4(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){K4(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return K4(e),VZ(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=FZ.enc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),i=FZ.uEnc(e);return n.setInt32(0,i.lo,!0),n.setInt32(4,i.hi,!0),this.raw(t)}int64(e){let t=FZ.enc(e);return NZ(t.lo,t.hi,this.buf),this}sint64(e){const t=FZ.enc(e),n=t.hi>>31;return NZ(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){const t=FZ.uEnc(e);return NZ(t.lo,t.hi,this.buf),this}}class W4{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:M4().decodeUtf8;this.decodeUtf8=t,this.varint64=OZ,this.uint32=xZ,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.uint32(),t=e>>>3,n=7&e;if(t<=0||n<0||n>5)throw new Error("illegal tag: field no "+t+" wire type "+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case U4.Varint:for(;128&this.buf[this.pos++];);break;case U4.Bit64:this.pos+=4;case U4.Bit32:this.pos+=4;break;case U4.LengthDelimited:let n=this.uint32();this.pos+=n;break;case U4.StartGroup:for(;;){const e=l5(this.tag(),2),n=e[0],i=e[1];if(i===U4.EndGroup){if(void 0!==t&&n!==t)throw new Error("invalid end group tag");break}this.skip(i,n)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return FZ.dec(...this.varint64())}uint64(){return FZ.uDec(...this.varint64())}sint64(){let e=l5(this.varint64(),2),t=e[0],n=e[1],i=-(1&t);return t=(t>>>1|(1&n)<<31)^i,n=n>>>1^i,FZ.dec(t,n)}bool(){let e=l5(this.varint64(),2),t=e[0],n=e[1];return 0!==t||0!==n}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return FZ.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return FZ.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.decodeUtf8(this.bytes())}}function K4(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>B4||e<j4)throw new Error("invalid int32: "+e)}function H4(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid uint32: "+typeof e);if(!Number.isInteger(e)||e>F4||e<0)throw new Error("invalid uint32: "+e)}function Y4(e,t){const n="list"==e.fieldKind?D4(t,e):"map"==e.fieldKind?P4(t,e):J4(e,t);if(!0===n)return;let i;switch(e.fieldKind){case"list":i="expected ".concat($4(e),", got ").concat(q4(t));break;case"map":i="expected ".concat(e6(e),", got ").concat(q4(t));break;default:i=Z4(e,t,n)}return new O4(e,i)}function X4(e,t,n){const i=J4(e,n);if(!0!==i)return new O4(e,"list item #".concat(t+1,": ").concat(Z4(e,n,i)))}function J4(e,t){return void 0!==e.scalar?z4(t,e.scalar):void 0!==e.enum?e.enum.open?Number.isInteger(t):IZ(e.enum).some((e=>e.number===t)):L4(t,e.message)}function z4(e,t){switch(t){case GZ.DOUBLE:return"number"==typeof e;case GZ.FLOAT:return"number"==typeof e&&(!(!Number.isNaN(e)&&Number.isFinite(e))||!(e>V4||e<x4)||"".concat(e.toFixed()," out of range"));case GZ.INT32:case GZ.SFIXED32:case GZ.SINT32:return!("number"!=typeof e||!Number.isInteger(e))&&(!(e>B4||e<j4)||"".concat(e.toFixed()," out of range"));case GZ.FIXED32:case GZ.UINT32:return!("number"!=typeof e||!Number.isInteger(e))&&(!(e>F4||e<0)||"".concat(e.toFixed()," out of range"));case GZ.BOOL:return"boolean"==typeof e;case GZ.STRING:return"string"==typeof e&&(M4().checkUtf8(e)||"invalid UTF8");case GZ.BYTES:return e instanceof Uint8Array;case GZ.INT64:case GZ.SFIXED64:case GZ.SINT64:if("bigint"==typeof e||"number"==typeof e||"string"==typeof e&&e.length>0)try{return FZ.parse(e),!0}catch(t){return"".concat(e," out of range")}return!1;case GZ.FIXED64:case GZ.UINT64:if("bigint"==typeof e||"number"==typeof e||"string"==typeof e&&e.length>0)try{return FZ.uParse(e),!0}catch(t){return"".concat(e," out of range")}return!1}}function Z4(e,t,n){return n="string"==typeof n?": ".concat(n):", got ".concat(q4(t)),void 0!==e.scalar?"expected ".concat(function(e){switch(e){case GZ.STRING:return"string";case GZ.BOOL:return"boolean";case GZ.INT64:case GZ.SINT64:case GZ.SFIXED64:return"bigint (int64)";case GZ.UINT64:case GZ.FIXED64:return"bigint (uint64)";case GZ.BYTES:return"Uint8Array";case GZ.DOUBLE:return"number (float64)";case GZ.FLOAT:return"number (float32)";case GZ.FIXED32:case GZ.UINT32:return"number (uint32)";case GZ.INT32:case GZ.SFIXED32:case GZ.SINT32:return"number (int32)"}}(e.scalar))+n:void 0!==e.enum?"expected ".concat(e.enum.toString())+n:"expected ".concat(Q4(e.message))+n}function q4(e){switch(typeof e){case"object":return null===e?"null":e instanceof Uint8Array?"Uint8Array(".concat(e.length,")"):Array.isArray(e)?"Array(".concat(e.length,")"):D4(e)?$4(e.field()):P4(e)?e6(e.field()):L4(e)?Q4(e.desc):r4(e)?"message ".concat(e.$typeName):"object";case"string":return e.length>30?"string":'"'.concat(e.split('"').join('\\"'),'"');case"boolean":case"number":return String(e);case"bigint":return String(e)+"n";default:return typeof e}}function Q4(e){return"ReflectMessage (".concat(e.typeName,")")}function $4(e){switch(e.listKind){case"message":return"ReflectList (".concat(e.message.toString(),")");case"enum":return"ReflectList (".concat(e.enum.toString(),")");case"scalar":return"ReflectList (".concat(GZ[e.scalar],")")}}function e6(e){switch(e.mapKind){case"message":return"ReflectMap (".concat(GZ[e.mapKey],", ").concat(e.message.toString(),")");case"enum":return"ReflectMap (".concat(GZ[e.mapKey],", ").concat(e.enum.toString(),")");case"scalar":return"ReflectMap (".concat(GZ[e.mapKey],", ").concat(GZ[e.scalar],")")}}function t6(e){const t=e.fields[0];return n6(e.typeName)&&void 0!==t&&"scalar"==t.fieldKind&&"value"==t.name&&1==t.number}function n6(e){var t;return e.startsWith("google.protobuf.")&&A4(t=["DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue"]).call(t,e.substring(16))}const i6=999,r6=998,o6=2;function s6(e,t){if(r4(t,e))return t;const n=function(e){let t;if(function(e){switch(e.file.edition){case i6:return!1;case r6:return!0;default:return e.fields.some((e=>e.presence!=o6&&"message"!=e.fieldKind&&!e.oneof))}}(e)){const n=_6.get(e);let i,r;if(n)i=n.prototype,r=n.members;else{i={},r=new Set;for(const t of e.members)"oneof"!=t.kind&&("scalar"!=t.fieldKind&&"enum"!=t.fieldKind||t.presence!=o6&&(r.add(t),i[t.localName]=E6(t)));_6.set(e,{prototype:i,members:r})}t=Object.create(i),t.$typeName=e.typeName;for(const n of e.members)if(!r.has(n)){if("field"==n.kind){if("message"==n.fieldKind)continue;if(("scalar"==n.fieldKind||"enum"==n.fieldKind)&&n.presence!=o6)continue}t[n.localName]=E6(n)}}else{t={$typeName:e.typeName};for(const n of e.members)"oneof"!=n.kind&&n.presence!=o6||(t[n.localName]=E6(n))}return t}(e);return void 0!==t&&function(e,t,n){for(const i of e.members){let e,r=n[i.localName];if(null!=r){if("oneof"==i.kind){const t=YZ(n,i);if(!t)continue;e=t,r=JZ(n,t)}else e=i;switch(e.fieldKind){case"message":r=l6(e,r);break;case"scalar":r=a6(e,r);break;case"list":r=d6(e,r);break;case"map":r=c6(e,r)}zZ(t,e,r)}}}(e,n,t),n}function a6(e,t){return e.scalar==GZ.BYTES?u6(t):t}function c6(e,t){if(N4(t)){if(e.scalar==GZ.BYTES)return h6(t,u6);if("message"==e.mapKind)return h6(t,(t=>l6(e,t)))}return t}function d6(e,t){if(Array.isArray(t)){if(e.scalar==GZ.BYTES)return t.map(u6);if("message"==e.listKind)return t.map((t=>l6(e,t)))}return t}function l6(e,t){if("message"==e.fieldKind&&!e.oneof&&t6(e.message))return a6(e.message.fields[0],t);if(N4(t)){if("google.protobuf.Struct"==e.message.typeName&&"google.protobuf.Value"!==e.parent.typeName)return t;if(!r4(t,e.message))return s6(e.message,t)}return t}function u6(e){return Array.isArray(e)?new Uint8Array(e):e}function h6(e,t){const n={};for(const i of Object.entries(e))n[i[0]]=t(i[1]);return n}const p6=Symbol(),_6=new WeakMap;function E6(e){if("oneof"==e.kind)return{case:void 0};if("list"==e.fieldKind)return[];if("map"==e.fieldKind)return{};if("message"==e.fieldKind)return p6;const t=e.getDefaultValue();return void 0!==t?"scalar"==e.fieldKind&&e.longAsString?t.toString():t:"scalar"==e.fieldKind?WZ(e.scalar,e.longAsString):IZ(e.enum)[0].number}function m6(e,t){return new g6(e,t,!(arguments.length>2&&void 0!==arguments[2])||arguments[2])}const f6=new WeakMap;class g6{get sortedFields(){var e;const t=f6.get(this.desc);if(t)return t;const n=z5(e=this.desc.fields.concat()).call(e,((e,t)=>e.number-t.number));return f6.set(this.desc,n),n}constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.lists=new Map,this.maps=new Map,this.check=n,this.desc=e,this.message=this[HZ]=null!=t?t:s6(e),this.fields=e.fields,this.oneofs=e.oneofs,this.members=e.members}findNumber(e){return this._fieldsByNumber||(this._fieldsByNumber=new Map(this.desc.fields.map((e=>[e.number,e])))),this._fieldsByNumber.get(e)}oneofCase(e){return S6(this.message,e),YZ(this.message,e)}isSet(e){return S6(this.message,e),function(e,t){const n=t.localName;if(t.oneof)return e[t.oneof.localName].case===n;if(t.presence!=KZ)return void 0!==e[n]&&Object.prototype.hasOwnProperty.call(e,n);switch(t.fieldKind){case"list":return e[n].length>0;case"map":return Object.keys(e[n]).length>0;case"scalar":return!function(e,t){switch(e){case GZ.BOOL:return!1===t;case GZ.STRING:return""===t;case GZ.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return 0==t}}(t.scalar,e[n]);case"enum":return e[n]!==IZ(t.enum)[0].number}throw new Error("message field with implicit presence")}(this.message,e)}clear(e){S6(this.message,e),function(e,t){const n=t.localName;if(t.oneof){const i=t.oneof.localName;e[i].case===n&&(e[i]={case:void 0})}else if(t.presence!=KZ)delete e[n];else switch(t.fieldKind){case"map":e[n]={};break;case"list":e[n]=[];break;case"enum":e[n]=IZ(t.enum)[0].number;break;case"scalar":e[n]=WZ(t.scalar,t.longAsString)}}(this.message,e)}get(e){S6(this.message,e);const t=JZ(this.message,e);switch(e.fieldKind){case"list":let n=this.lists.get(e);return n&&n[HZ]===t||this.lists.set(e,n=new T6(e,t,this.check)),n;case"map":let i=this.maps.get(e);return i&&i[HZ]===t||this.maps.set(e,i=new R6(e,t,this.check)),i;case"message":return y6(e,t,this.check);case"scalar":return void 0===t?WZ(e.scalar,!1):O6(e,t);case"enum":return null!=t?t:IZ(e.enum)[0].number}}set(e,t){if(S6(this.message,e),this.check){const n=Y4(e,t);if(n)throw n}let n;n="message"==e.fieldKind?v6(e,t):P4(t)||D4(t)?t[HZ]:N6(e,t),zZ(this.message,e,n)}getUnknown(){return this.message.$unknown}setUnknown(e){this.message.$unknown=e}}function S6(e,t){if(t.parent.typeName!==e.$typeName)throw new O4(t,"cannot use ".concat(t.toString()," with message ").concat(e.$typeName),"ForeignFieldError")}class T6{field(){return this._field}get size(){return this._arr.length}constructor(e,t,n){this._field=e,this._arr=this[HZ]=t,this.check=n}get(e){const t=this._arr[e];return void 0===t?void 0:b6(this._field,t,this.check)}set(e,t){if(e<0||e>=this._arr.length)throw new O4(this._field,"list item #".concat(e+1,": out of range"));if(this.check){const n=X4(this._field,e,t);if(n)throw n}this._arr[e]=C6(this._field,t)}add(e){if(this.check){const t=X4(this._field,this._arr.length,e);if(t)throw t}this._arr.push(C6(this._field,e))}clear(){this._arr.splice(0,this._arr.length)}[Symbol.iterator](){return IZ(this).call(this)}keys(){var e;return i4(e=this._arr).call(e)}*values(){for(const e of this._arr)yield b6(this._field,e,this.check)}*entries(){for(let e=0;e<this._arr.length;e++)yield[e,b6(this._field,this._arr[e],this.check)]}}class R6{constructor(e,t){let n=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];this.obj=this[HZ]=null!=t?t:{},this.check=n,this._field=e}field(){return this._field}set(e,t){if(this.check){const n=function(e,t,n){const i=z4(t,e.mapKey);if(!0!==i)return new O4(e,"invalid map key: ".concat(Z4({scalar:e.mapKey},t,i)));const r=J4(e,n);return!0!==r?new O4(e,"map entry ".concat(q4(t),": ").concat(Z4(e,n,r))):void 0}(this._field,e,t);if(n)throw n}return this.obj[A6(e)]=function(e,t){return"message"==e.mapKind?v6(e,t):N6(e,t)}(this._field,t),this}delete(e){const t=A6(e),n=Object.prototype.hasOwnProperty.call(this.obj,t);return n&&delete this.obj[t],n}clear(){for(const e of Object.keys(this.obj))delete this.obj[e]}get(e){let t=this.obj[A6(e)];return void 0!==t&&(t=I6(this._field,t,this.check)),t}has(e){return Object.prototype.hasOwnProperty.call(this.obj,A6(e))}*keys(){for(const e of Object.keys(this.obj))yield w6(e,this._field.mapKey)}*entries(){for(const e of Object.entries(this.obj))yield[w6(e[0],this._field.mapKey),I6(this._field,e[1],this.check)]}[Symbol.iterator](){return this.entries()}get size(){return Object.keys(this.obj).length}*values(){for(const e of Object.values(this.obj))yield I6(this._field,e,this.check)}forEach(e,t){for(const n of this.entries())e.call(t,n[1],n[0],this)}}function v6(e,t){return L4(t)?n6(t.message.$typeName)&&!e.oneof&&"message"==e.fieldKind?t.message.value:"google.protobuf.Struct"==t.desc.typeName&&"google.protobuf.Value"!=e.parent.typeName?P6(t.message):t.message:t}function y6(e,t,n){return void 0!==t&&(t6(e.message)&&!e.oneof&&"message"==e.fieldKind?t={$typeName:e.message.typeName,value:O6(e.message.fields[0],t)}:"google.protobuf.Struct"==e.message.typeName&&"google.protobuf.Value"!=e.parent.typeName&&N4(t)&&(t=D6(t))),new g6(e.message,t,n)}function C6(e,t){return"message"==e.listKind?v6(e,t):N6(e,t)}function b6(e,t,n){return"message"==e.listKind?y6(e,t,n):O6(e,t)}function I6(e,t,n){return"message"==e.mapKind?y6(e,t,n):t}function A6(e){return"string"==typeof e||"number"==typeof e?e:String(e)}function w6(e,t){switch(t){case GZ.STRING:return e;case GZ.INT32:case GZ.FIXED32:case GZ.UINT32:case GZ.SFIXED32:case GZ.SINT32:{const t=Number.parseInt(e);if(Number.isFinite(t))return t;break}case GZ.BOOL:switch(e){case"true":return!0;case"false":return!1}break;case GZ.UINT64:case GZ.FIXED64:try{return FZ.uParse(e)}catch(e){}break;default:try{return FZ.parse(e)}catch(e){}}return e}function O6(e,t){switch(e.scalar){case GZ.INT64:case GZ.SFIXED64:case GZ.SINT64:"longAsString"in e&&e.longAsString&&"string"==typeof t&&(t=FZ.parse(t));break;case GZ.FIXED64:case GZ.UINT64:"longAsString"in e&&e.longAsString&&"string"==typeof t&&(t=FZ.uParse(t))}return t}function N6(e,t){switch(e.scalar){case GZ.INT64:case GZ.SFIXED64:case GZ.SINT64:"longAsString"in e&&e.longAsString?t=String(t):"string"!=typeof t&&"number"!=typeof t||(t=FZ.parse(t));break;case GZ.FIXED64:case GZ.UINT64:"longAsString"in e&&e.longAsString?t=String(t):"string"!=typeof t&&"number"!=typeof t||(t=FZ.uParse(t))}return t}function D6(e){const t={$typeName:"google.protobuf.Struct",fields:{}};if(N4(e))for(const i of Object.entries(e)){var n=l5(i,2);const e=n[0],r=n[1];t.fields[e]=k6(r)}return t}function P6(e){const t={};for(const i of Object.entries(e.fields)){var n=l5(i,2);const e=n[0],r=n[1];t[e]=L6(r)}return t}function L6(e){switch(e.kind.case){case"structValue":return P6(e.kind.value);case"listValue":return IZ(e.kind.value).map(L6);case"nullValue":case void 0:return null;default:return e.kind.value}}function k6(e){const t={$typeName:"google.protobuf.Value",kind:{case:void 0}};switch(typeof e){case"number":t.kind={case:"numberValue",value:e};break;case"string":t.kind={case:"stringValue",value:e};break;case"boolean":t.kind={case:"boolValue",value:e};break;case"object":if(null===e){const e=0;t.kind={case:"nullValue",value:e}}else if(Array.isArray(e)){const n={$typeName:"google.protobuf.ListValue",values:[]};if(Array.isArray(e))for(const t of e)IZ(n).push(k6(t));t.kind={case:"listValue",value:n}}else t.kind={case:"structValue",value:D6(e)}}return t}const M6=3,U6={writeUnknownFields:!0};function V6(e,t,n){return x6(new G4,function(e){return e?Object.assign(Object.assign({},U6),e):U6}(n),m6(e,t)).finish()}function x6(e,t,n){var i;for(const i of n.sortedFields)if(n.isSet(i))F6(e,t,n,i);else if(i.presence==M6)throw new Error("cannot encode ".concat(i," to binary: required field not set"));if(t.writeUnknownFields)for(const t of null!==(i=n.getUnknown())&&void 0!==i?i:[]){const n=t.no,i=t.wireType,r=t.data;e.tag(n,i).raw(r)}return e}function F6(e,t,n,i){var r;switch(i.fieldKind){case"scalar":case"enum":B6(e,n.desc.typeName,i.name,null!==(r=i.scalar)&&void 0!==r?r:GZ.INT32,i.number,n.get(i));break;case"list":!function(e,t,n,i){var r;if("message"==n.listKind){for(const r of i)j6(e,t,n,r);return}const o=null!==(r=n.scalar)&&void 0!==r?r:GZ.INT32;if(n.packed){if(!i.size)return;e.tag(n.number,U4.LengthDelimited).fork();for(const t of i)W6(e,n.parent.typeName,n.name,o,t);e.join()}else for(const t of i)B6(e,n.parent.typeName,n.name,o,n.number,t)}(e,t,i,n.get(i));break;case"message":j6(e,t,i,n.get(i));break;case"map":for(const r of n.get(i)){var o=l5(r,2);G6(e,t,i,o[0],o[1])}}}function B6(e,t,n,i,r,o){W6(e.tag(r,function(e){switch(e){case GZ.BYTES:case GZ.STRING:return U4.LengthDelimited;case GZ.DOUBLE:case GZ.FIXED64:case GZ.SFIXED64:return U4.Bit64;case GZ.FIXED32:case GZ.SFIXED32:case GZ.FLOAT:return U4.Bit32;default:return U4.Varint}}(i)),t,n,i,o)}function j6(e,t,n,i){n.delimitedEncoding?x6(e.tag(n.number,U4.StartGroup),t,i).tag(n.number,U4.EndGroup):x6(e.tag(n.number,U4.LengthDelimited).fork(),t,i).join()}function G6(e,t,n,i,r){var o;switch(e.tag(n.number,U4.LengthDelimited).fork(),B6(e,n.parent.typeName,n.name,n.mapKey,1,i),n.mapKind){case"scalar":case"enum":B6(e,n.parent.typeName,n.name,null!==(o=n.scalar)&&void 0!==o?o:GZ.INT32,2,r);break;case"message":x6(e.tag(2,U4.LengthDelimited).fork(),t,r).join()}e.join()}function W6(e,t,n,i,r){try{switch(i){case GZ.STRING:e.string(r);break;case GZ.BOOL:e.bool(r);break;case GZ.DOUBLE:e.double(r);break;case GZ.FLOAT:e.float(r);break;case GZ.INT32:e.int32(r);break;case GZ.INT64:e.int64(r);break;case GZ.UINT64:e.uint64(r);break;case GZ.FIXED64:e.fixed64(r);break;case GZ.BYTES:e.bytes(r);break;case GZ.FIXED32:e.fixed32(r);break;case GZ.SFIXED32:e.sfixed32(r);break;case GZ.SFIXED64:e.sfixed64(r);break;case GZ.SINT64:e.sint64(r);break;case GZ.UINT32:e.uint32(r);break;case GZ.SINT32:e.sint32(r)}}catch(e){if(e instanceof Error)throw new Error("cannot encode field ".concat(t,".").concat(n," to binary: ").concat(e.message));throw e}}var K6=AH,H6=YH,Y6=EK,X6=uJ,J6=TypeError,z6="Reduce of empty array with no initial value",Z6=function(e){return function(t,n,i,r){var o=H6(t),s=Y6(o),a=X6(o);if(K6(n),0===a&&i<2)throw new J6(z6);var c=e?a-1:0,d=e?-1:1;if(i<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,e?c<0:a<=c)throw new J6(z6)}for(;e?c>=0:a>c;c+=d)c in s&&(r=n(r,s[c],c,o));return r}},q6={left:Z6(!1),right:Z6(!0)},Q6=bK,$6=rH,e9=lK,t9=function(e){return $6.slice(0,e.length)===e},n9=t9("Bun/")?"BUN":t9("Cloudflare-Workers")?"CLOUDFLARE":t9("Deno/")?"DENO":t9("Node.js/")?"NODE":Q6.Bun&&"string"==typeof Bun.version?"BUN":Q6.Deno&&"object"==typeof Deno.version?"DENO":"process"===e9(Q6.process)?"NODE":Q6.window&&Q6.document?"BROWSER":"REST",i9=q6.left;XX({target:"Array",proto:!0,forced:!("NODE"===n9)&&uH>79&&uH<83||!g5("reduce")},{reduce:function(e){var t=arguments.length;return i9(this,e,t,t>1?arguments[1]:void 0)}});var r9=gZ("Array","reduce"),o9=tH,s9=r9,a9=Array.prototype,c9=qW((function(e){var t=sr(e);return e===a9||o9(a9,e)&&t===sr(a9)?s9:t}));function d9(e,t){for(var n=arguments.length,i=new Array(n>2?n-2:0),r=2;r<n;r++)i[r-2]=arguments[r];return c9(i).call(i,((e,t)=>e.nestedMessages[t]),e.messages[t])}const l9=d9(function(e){const t=function(e){const t=Object.create({syntax:"",edition:0});return Object.assign(t,Object.assign(Object.assign({$typeName:"google.protobuf.FileDescriptorProto",dependency:[],publicDependency:[],weakDependency:[],optionDependency:[],service:[],extension:[]},e),{messageType:e.messageType.map(Hq),enumType:e.enumType.map(Jq)}))}(e);return t.messageType.forEach(ZZ),dq(t,(()=>{})).getFile(t.name)}({name:"google/protobuf/descriptor.proto",package:"google.protobuf",messageType:[{name:"FileDescriptorSet",field:[{name:"file",number:1,type:11,label:3,typeName:".google.protobuf.FileDescriptorProto"}],extensionRange:[{start:536e6,end:536000001}]},{name:"FileDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"package",number:2,type:9,label:1},{name:"dependency",number:3,type:9,label:3},{name:"public_dependency",number:10,type:5,label:3},{name:"weak_dependency",number:11,type:5,label:3},{name:"option_dependency",number:15,type:9,label:3},{name:"message_type",number:4,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:5,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"service",number:6,type:11,label:3,typeName:".google.protobuf.ServiceDescriptorProto"},{name:"extension",number:7,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FileOptions"},{name:"source_code_info",number:9,type:11,label:1,typeName:".google.protobuf.SourceCodeInfo"},{name:"syntax",number:12,type:9,label:1},{name:"edition",number:14,type:14,label:1,typeName:".google.protobuf.Edition"}]},{name:"DescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"field",number:2,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"extension",number:6,type:11,label:3,typeName:".google.protobuf.FieldDescriptorProto"},{name:"nested_type",number:3,type:11,label:3,typeName:".google.protobuf.DescriptorProto"},{name:"enum_type",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto"},{name:"extension_range",number:5,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ExtensionRange"},{name:"oneof_decl",number:8,type:11,label:3,typeName:".google.protobuf.OneofDescriptorProto"},{name:"options",number:7,type:11,label:1,typeName:".google.protobuf.MessageOptions"},{name:"reserved_range",number:9,type:11,label:3,typeName:".google.protobuf.DescriptorProto.ReservedRange"},{name:"reserved_name",number:10,type:9,label:3},{name:"visibility",number:11,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"ExtensionRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ExtensionRangeOptions"}]},{name:"ReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"ExtensionRangeOptions",field:[{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"},{name:"declaration",number:2,type:11,label:3,typeName:".google.protobuf.ExtensionRangeOptions.Declaration",options:{retention:2}},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"verification",number:3,type:14,label:1,typeName:".google.protobuf.ExtensionRangeOptions.VerificationState",defaultValue:"UNVERIFIED",options:{retention:2}}],nestedType:[{name:"Declaration",field:[{name:"number",number:1,type:5,label:1},{name:"full_name",number:2,type:9,label:1},{name:"type",number:3,type:9,label:1},{name:"reserved",number:5,type:8,label:1},{name:"repeated",number:6,type:8,label:1}]}],enumType:[{name:"VerificationState",value:[{name:"DECLARATION",number:0},{name:"UNVERIFIED",number:1}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:3,type:5,label:1},{name:"label",number:4,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Label"},{name:"type",number:5,type:14,label:1,typeName:".google.protobuf.FieldDescriptorProto.Type"},{name:"type_name",number:6,type:9,label:1},{name:"extendee",number:2,type:9,label:1},{name:"default_value",number:7,type:9,label:1},{name:"oneof_index",number:9,type:5,label:1},{name:"json_name",number:10,type:9,label:1},{name:"options",number:8,type:11,label:1,typeName:".google.protobuf.FieldOptions"},{name:"proto3_optional",number:17,type:8,label:1}],enumType:[{name:"Type",value:[{name:"TYPE_DOUBLE",number:1},{name:"TYPE_FLOAT",number:2},{name:"TYPE_INT64",number:3},{name:"TYPE_UINT64",number:4},{name:"TYPE_INT32",number:5},{name:"TYPE_FIXED64",number:6},{name:"TYPE_FIXED32",number:7},{name:"TYPE_BOOL",number:8},{name:"TYPE_STRING",number:9},{name:"TYPE_GROUP",number:10},{name:"TYPE_MESSAGE",number:11},{name:"TYPE_BYTES",number:12},{name:"TYPE_UINT32",number:13},{name:"TYPE_ENUM",number:14},{name:"TYPE_SFIXED32",number:15},{name:"TYPE_SFIXED64",number:16},{name:"TYPE_SINT32",number:17},{name:"TYPE_SINT64",number:18}]},{name:"Label",value:[{name:"LABEL_OPTIONAL",number:1},{name:"LABEL_REPEATED",number:3},{name:"LABEL_REQUIRED",number:2}]}]},{name:"OneofDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"options",number:2,type:11,label:1,typeName:".google.protobuf.OneofOptions"}]},{name:"EnumDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"value",number:2,type:11,label:3,typeName:".google.protobuf.EnumValueDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumOptions"},{name:"reserved_range",number:4,type:11,label:3,typeName:".google.protobuf.EnumDescriptorProto.EnumReservedRange"},{name:"reserved_name",number:5,type:9,label:3},{name:"visibility",number:6,type:14,label:1,typeName:".google.protobuf.SymbolVisibility"}],nestedType:[{name:"EnumReservedRange",field:[{name:"start",number:1,type:5,label:1},{name:"end",number:2,type:5,label:1}]}]},{name:"EnumValueDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"number",number:2,type:5,label:1},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.EnumValueOptions"}]},{name:"ServiceDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"method",number:2,type:11,label:3,typeName:".google.protobuf.MethodDescriptorProto"},{name:"options",number:3,type:11,label:1,typeName:".google.protobuf.ServiceOptions"}]},{name:"MethodDescriptorProto",field:[{name:"name",number:1,type:9,label:1},{name:"input_type",number:2,type:9,label:1},{name:"output_type",number:3,type:9,label:1},{name:"options",number:4,type:11,label:1,typeName:".google.protobuf.MethodOptions"},{name:"client_streaming",number:5,type:8,label:1,defaultValue:"false"},{name:"server_streaming",number:6,type:8,label:1,defaultValue:"false"}]},{name:"FileOptions",field:[{name:"java_package",number:1,type:9,label:1},{name:"java_outer_classname",number:8,type:9,label:1},{name:"java_multiple_files",number:10,type:8,label:1,defaultValue:"false"},{name:"java_generate_equals_and_hash",number:20,type:8,label:1,options:{deprecated:!0}},{name:"java_string_check_utf8",number:27,type:8,label:1,defaultValue:"false"},{name:"optimize_for",number:9,type:14,label:1,typeName:".google.protobuf.FileOptions.OptimizeMode",defaultValue:"SPEED"},{name:"go_package",number:11,type:9,label:1},{name:"cc_generic_services",number:16,type:8,label:1,defaultValue:"false"},{name:"java_generic_services",number:17,type:8,label:1,defaultValue:"false"},{name:"py_generic_services",number:18,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:23,type:8,label:1,defaultValue:"false"},{name:"cc_enable_arenas",number:31,type:8,label:1,defaultValue:"true"},{name:"objc_class_prefix",number:36,type:9,label:1},{name:"csharp_namespace",number:37,type:9,label:1},{name:"swift_prefix",number:39,type:9,label:1},{name:"php_class_prefix",number:40,type:9,label:1},{name:"php_namespace",number:41,type:9,label:1},{name:"php_metadata_namespace",number:44,type:9,label:1},{name:"ruby_package",number:45,type:9,label:1},{name:"features",number:50,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"OptimizeMode",value:[{name:"SPEED",number:1},{name:"CODE_SIZE",number:2},{name:"LITE_RUNTIME",number:3}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"MessageOptions",field:[{name:"message_set_wire_format",number:1,type:8,label:1,defaultValue:"false"},{name:"no_standard_descriptor_accessor",number:2,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"map_entry",number:7,type:8,label:1},{name:"deprecated_legacy_json_field_conflicts",number:11,type:8,label:1,options:{deprecated:!0}},{name:"features",number:12,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"FieldOptions",field:[{name:"ctype",number:1,type:14,label:1,typeName:".google.protobuf.FieldOptions.CType",defaultValue:"STRING"},{name:"packed",number:2,type:8,label:1},{name:"jstype",number:6,type:14,label:1,typeName:".google.protobuf.FieldOptions.JSType",defaultValue:"JS_NORMAL"},{name:"lazy",number:5,type:8,label:1,defaultValue:"false"},{name:"unverified_lazy",number:15,type:8,label:1,defaultValue:"false"},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"weak",number:10,type:8,label:1,defaultValue:"false",options:{deprecated:!0}},{name:"debug_redact",number:16,type:8,label:1,defaultValue:"false"},{name:"retention",number:17,type:14,label:1,typeName:".google.protobuf.FieldOptions.OptionRetention"},{name:"targets",number:19,type:14,label:3,typeName:".google.protobuf.FieldOptions.OptionTargetType"},{name:"edition_defaults",number:20,type:11,label:3,typeName:".google.protobuf.FieldOptions.EditionDefault"},{name:"features",number:21,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"feature_support",number:22,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],nestedType:[{name:"EditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"value",number:2,type:9,label:1}]},{name:"FeatureSupport",field:[{name:"edition_introduced",number:1,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"edition_deprecated",number:2,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"deprecation_warning",number:3,type:9,label:1},{name:"edition_removed",number:4,type:14,label:1,typeName:".google.protobuf.Edition"}]}],enumType:[{name:"CType",value:[{name:"STRING",number:0},{name:"CORD",number:1},{name:"STRING_PIECE",number:2}]},{name:"JSType",value:[{name:"JS_NORMAL",number:0},{name:"JS_STRING",number:1},{name:"JS_NUMBER",number:2}]},{name:"OptionRetention",value:[{name:"RETENTION_UNKNOWN",number:0},{name:"RETENTION_RUNTIME",number:1},{name:"RETENTION_SOURCE",number:2}]},{name:"OptionTargetType",value:[{name:"TARGET_TYPE_UNKNOWN",number:0},{name:"TARGET_TYPE_FILE",number:1},{name:"TARGET_TYPE_EXTENSION_RANGE",number:2},{name:"TARGET_TYPE_MESSAGE",number:3},{name:"TARGET_TYPE_FIELD",number:4},{name:"TARGET_TYPE_ONEOF",number:5},{name:"TARGET_TYPE_ENUM",number:6},{name:"TARGET_TYPE_ENUM_ENTRY",number:7},{name:"TARGET_TYPE_SERVICE",number:8},{name:"TARGET_TYPE_METHOD",number:9}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"OneofOptions",field:[{name:"features",number:1,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumOptions",field:[{name:"allow_alias",number:2,type:8,label:1},{name:"deprecated",number:3,type:8,label:1,defaultValue:"false"},{name:"deprecated_legacy_json_field_conflicts",number:6,type:8,label:1,options:{deprecated:!0}},{name:"features",number:7,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"EnumValueOptions",field:[{name:"deprecated",number:1,type:8,label:1,defaultValue:"false"},{name:"features",number:2,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"debug_redact",number:3,type:8,label:1,defaultValue:"false"},{name:"feature_support",number:4,type:11,label:1,typeName:".google.protobuf.FieldOptions.FeatureSupport"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"ServiceOptions",field:[{name:"features",number:34,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],extensionRange:[{start:1e3,end:536870912}]},{name:"MethodOptions",field:[{name:"deprecated",number:33,type:8,label:1,defaultValue:"false"},{name:"idempotency_level",number:34,type:14,label:1,typeName:".google.protobuf.MethodOptions.IdempotencyLevel",defaultValue:"IDEMPOTENCY_UNKNOWN"},{name:"features",number:35,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"uninterpreted_option",number:999,type:11,label:3,typeName:".google.protobuf.UninterpretedOption"}],enumType:[{name:"IdempotencyLevel",value:[{name:"IDEMPOTENCY_UNKNOWN",number:0},{name:"NO_SIDE_EFFECTS",number:1},{name:"IDEMPOTENT",number:2}]}],extensionRange:[{start:1e3,end:536870912}]},{name:"UninterpretedOption",field:[{name:"name",number:2,type:11,label:3,typeName:".google.protobuf.UninterpretedOption.NamePart"},{name:"identifier_value",number:3,type:9,label:1},{name:"positive_int_value",number:4,type:4,label:1},{name:"negative_int_value",number:5,type:3,label:1},{name:"double_value",number:6,type:1,label:1},{name:"string_value",number:7,type:12,label:1},{name:"aggregate_value",number:8,type:9,label:1}],nestedType:[{name:"NamePart",field:[{name:"name_part",number:1,type:9,label:2},{name:"is_extension",number:2,type:8,label:2}]}]},{name:"FeatureSet",field:[{name:"field_presence",number:1,type:14,label:1,typeName:".google.protobuf.FeatureSet.FieldPresence",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPLICIT",edition:900},{value:"IMPLICIT",edition:999},{value:"EXPLICIT",edition:1e3}]}},{name:"enum_type",number:2,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnumType",options:{retention:1,targets:[6,1],editionDefaults:[{value:"CLOSED",edition:900},{value:"OPEN",edition:999}]}},{name:"repeated_field_encoding",number:3,type:14,label:1,typeName:".google.protobuf.FeatureSet.RepeatedFieldEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"EXPANDED",edition:900},{value:"PACKED",edition:999}]}},{name:"utf8_validation",number:4,type:14,label:1,typeName:".google.protobuf.FeatureSet.Utf8Validation",options:{retention:1,targets:[4,1],editionDefaults:[{value:"NONE",edition:900},{value:"VERIFY",edition:999}]}},{name:"message_encoding",number:5,type:14,label:1,typeName:".google.protobuf.FeatureSet.MessageEncoding",options:{retention:1,targets:[4,1],editionDefaults:[{value:"LENGTH_PREFIXED",edition:900}]}},{name:"json_format",number:6,type:14,label:1,typeName:".google.protobuf.FeatureSet.JsonFormat",options:{retention:1,targets:[3,6,1],editionDefaults:[{value:"LEGACY_BEST_EFFORT",edition:900},{value:"ALLOW",edition:999}]}},{name:"enforce_naming_style",number:7,type:14,label:1,typeName:".google.protobuf.FeatureSet.EnforceNamingStyle",options:{retention:2,targets:[1,2,3,4,5,6,7,8,9],editionDefaults:[{value:"STYLE_LEGACY",edition:900},{value:"STYLE2024",edition:1001}]}},{name:"default_symbol_visibility",number:8,type:14,label:1,typeName:".google.protobuf.FeatureSet.VisibilityFeature.DefaultSymbolVisibility",options:{retention:2,targets:[1],editionDefaults:[{value:"EXPORT_ALL",edition:900},{value:"EXPORT_TOP_LEVEL",edition:1001}]}}],nestedType:[{name:"VisibilityFeature",enumType:[{name:"DefaultSymbolVisibility",value:[{name:"DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",number:0},{name:"EXPORT_ALL",number:1},{name:"EXPORT_TOP_LEVEL",number:2},{name:"LOCAL_ALL",number:3},{name:"STRICT",number:4}]}]}],enumType:[{name:"FieldPresence",value:[{name:"FIELD_PRESENCE_UNKNOWN",number:0},{name:"EXPLICIT",number:1},{name:"IMPLICIT",number:2},{name:"LEGACY_REQUIRED",number:3}]},{name:"EnumType",value:[{name:"ENUM_TYPE_UNKNOWN",number:0},{name:"OPEN",number:1},{name:"CLOSED",number:2}]},{name:"RepeatedFieldEncoding",value:[{name:"REPEATED_FIELD_ENCODING_UNKNOWN",number:0},{name:"PACKED",number:1},{name:"EXPANDED",number:2}]},{name:"Utf8Validation",value:[{name:"UTF8_VALIDATION_UNKNOWN",number:0},{name:"VERIFY",number:2},{name:"NONE",number:3}]},{name:"MessageEncoding",value:[{name:"MESSAGE_ENCODING_UNKNOWN",number:0},{name:"LENGTH_PREFIXED",number:1},{name:"DELIMITED",number:2}]},{name:"JsonFormat",value:[{name:"JSON_FORMAT_UNKNOWN",number:0},{name:"ALLOW",number:1},{name:"LEGACY_BEST_EFFORT",number:2}]},{name:"EnforceNamingStyle",value:[{name:"ENFORCE_NAMING_STYLE_UNKNOWN",number:0},{name:"STYLE2024",number:1},{name:"STYLE_LEGACY",number:2}]}],extensionRange:[{start:1e3,end:9995},{start:9995,end:1e4},{start:1e4,end:10001}]},{name:"FeatureSetDefaults",field:[{name:"defaults",number:1,type:11,label:3,typeName:".google.protobuf.FeatureSetDefaults.FeatureSetEditionDefault"},{name:"minimum_edition",number:4,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"maximum_edition",number:5,type:14,label:1,typeName:".google.protobuf.Edition"}],nestedType:[{name:"FeatureSetEditionDefault",field:[{name:"edition",number:3,type:14,label:1,typeName:".google.protobuf.Edition"},{name:"overridable_features",number:4,type:11,label:1,typeName:".google.protobuf.FeatureSet"},{name:"fixed_features",number:5,type:11,label:1,typeName:".google.protobuf.FeatureSet"}]}]},{name:"SourceCodeInfo",field:[{name:"location",number:1,type:11,label:3,typeName:".google.protobuf.SourceCodeInfo.Location"}],nestedType:[{name:"Location",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"span",number:2,type:5,label:3,options:{packed:!0}},{name:"leading_comments",number:3,type:9,label:1},{name:"trailing_comments",number:4,type:9,label:1},{name:"leading_detached_comments",number:6,type:9,label:3}]}],extensionRange:[{start:536e6,end:536000001}]},{name:"GeneratedCodeInfo",field:[{name:"annotation",number:1,type:11,label:3,typeName:".google.protobuf.GeneratedCodeInfo.Annotation"}],nestedType:[{name:"Annotation",field:[{name:"path",number:1,type:5,label:3,options:{packed:!0}},{name:"source_file",number:2,type:9,label:1},{name:"begin",number:3,type:5,label:1},{name:"end",number:4,type:5,label:1},{name:"semantic",number:5,type:14,label:1,typeName:".google.protobuf.GeneratedCodeInfo.Annotation.Semantic"}],enumType:[{name:"Semantic",value:[{name:"NONE",number:0},{name:"SET",number:1},{name:"ALIAS",number:2}]}]}]}],enumType:[{name:"Edition",value:[{name:"EDITION_UNKNOWN",number:0},{name:"EDITION_LEGACY",number:900},{name:"EDITION_PROTO2",number:998},{name:"EDITION_PROTO3",number:999},{name:"EDITION_2023",number:1e3},{name:"EDITION_2024",number:1001},{name:"EDITION_1_TEST_ONLY",number:1},{name:"EDITION_2_TEST_ONLY",number:2},{name:"EDITION_99997_TEST_ONLY",number:99997},{name:"EDITION_99998_TEST_ONLY",number:99998},{name:"EDITION_99999_TEST_ONLY",number:99999},{name:"EDITION_MAX",number:2147483647}]},{name:"SymbolVisibility",value:[{name:"VISIBILITY_UNSET",number:0},{name:"VISIBILITY_LOCAL",number:1},{name:"VISIBILITY_EXPORT",number:2}]}]}),1);var u9,h9,p9,_9,E9,m9,f9,g9,S9,T9,R9,v9,y9,C9,b9,I9,A9,w9,O9,N9;!function(e){e[e.DECLARATION=0]="DECLARATION",e[e.UNVERIFIED=1]="UNVERIFIED"}(u9||(u9={})),function(e){e[e.DOUBLE=1]="DOUBLE",e[e.FLOAT=2]="FLOAT",e[e.INT64=3]="INT64",e[e.UINT64=4]="UINT64",e[e.INT32=5]="INT32",e[e.FIXED64=6]="FIXED64",e[e.FIXED32=7]="FIXED32",e[e.BOOL=8]="BOOL",e[e.STRING=9]="STRING",e[e.GROUP=10]="GROUP",e[e.MESSAGE=11]="MESSAGE",e[e.BYTES=12]="BYTES",e[e.UINT32=13]="UINT32",e[e.ENUM=14]="ENUM",e[e.SFIXED32=15]="SFIXED32",e[e.SFIXED64=16]="SFIXED64",e[e.SINT32=17]="SINT32",e[e.SINT64=18]="SINT64"}(h9||(h9={})),function(e){e[e.OPTIONAL=1]="OPTIONAL",e[e.REPEATED=3]="REPEATED",e[e.REQUIRED=2]="REQUIRED"}(p9||(p9={})),function(e){e[e.SPEED=1]="SPEED",e[e.CODE_SIZE=2]="CODE_SIZE",e[e.LITE_RUNTIME=3]="LITE_RUNTIME"}(_9||(_9={})),function(e){e[e.STRING=0]="STRING",e[e.CORD=1]="CORD",e[e.STRING_PIECE=2]="STRING_PIECE"}(E9||(E9={})),function(e){e[e.JS_NORMAL=0]="JS_NORMAL",e[e.JS_STRING=1]="JS_STRING",e[e.JS_NUMBER=2]="JS_NUMBER"}(m9||(m9={})),function(e){e[e.RETENTION_UNKNOWN=0]="RETENTION_UNKNOWN",e[e.RETENTION_RUNTIME=1]="RETENTION_RUNTIME",e[e.RETENTION_SOURCE=2]="RETENTION_SOURCE"}(f9||(f9={})),function(e){e[e.TARGET_TYPE_UNKNOWN=0]="TARGET_TYPE_UNKNOWN",e[e.TARGET_TYPE_FILE=1]="TARGET_TYPE_FILE",e[e.TARGET_TYPE_EXTENSION_RANGE=2]="TARGET_TYPE_EXTENSION_RANGE",e[e.TARGET_TYPE_MESSAGE=3]="TARGET_TYPE_MESSAGE",e[e.TARGET_TYPE_FIELD=4]="TARGET_TYPE_FIELD",e[e.TARGET_TYPE_ONEOF=5]="TARGET_TYPE_ONEOF",e[e.TARGET_TYPE_ENUM=6]="TARGET_TYPE_ENUM",e[e.TARGET_TYPE_ENUM_ENTRY=7]="TARGET_TYPE_ENUM_ENTRY",e[e.TARGET_TYPE_SERVICE=8]="TARGET_TYPE_SERVICE",e[e.TARGET_TYPE_METHOD=9]="TARGET_TYPE_METHOD"}(g9||(g9={})),function(e){e[e.IDEMPOTENCY_UNKNOWN=0]="IDEMPOTENCY_UNKNOWN",e[e.NO_SIDE_EFFECTS=1]="NO_SIDE_EFFECTS",e[e.IDEMPOTENT=2]="IDEMPOTENT"}(S9||(S9={})),function(e){e[e.DEFAULT_SYMBOL_VISIBILITY_UNKNOWN=0]="DEFAULT_SYMBOL_VISIBILITY_UNKNOWN",e[e.EXPORT_ALL=1]="EXPORT_ALL",e[e.EXPORT_TOP_LEVEL=2]="EXPORT_TOP_LEVEL",e[e.LOCAL_ALL=3]="LOCAL_ALL",e[e.STRICT=4]="STRICT"}(T9||(T9={})),function(e){e[e.FIELD_PRESENCE_UNKNOWN=0]="FIELD_PRESENCE_UNKNOWN",e[e.EXPLICIT=1]="EXPLICIT",e[e.IMPLICIT=2]="IMPLICIT",e[e.LEGACY_REQUIRED=3]="LEGACY_REQUIRED"}(R9||(R9={})),function(e){e[e.ENUM_TYPE_UNKNOWN=0]="ENUM_TYPE_UNKNOWN",e[e.OPEN=1]="OPEN",e[e.CLOSED=2]="CLOSED"}(v9||(v9={})),function(e){e[e.REPEATED_FIELD_ENCODING_UNKNOWN=0]="REPEATED_FIELD_ENCODING_UNKNOWN",e[e.PACKED=1]="PACKED",e[e.EXPANDED=2]="EXPANDED"}(y9||(y9={})),function(e){e[e.UTF8_VALIDATION_UNKNOWN=0]="UTF8_VALIDATION_UNKNOWN",e[e.VERIFY=2]="VERIFY",e[e.NONE=3]="NONE"}(C9||(C9={})),function(e){e[e.MESSAGE_ENCODING_UNKNOWN=0]="MESSAGE_ENCODING_UNKNOWN",e[e.LENGTH_PREFIXED=1]="LENGTH_PREFIXED",e[e.DELIMITED=2]="DELIMITED"}(b9||(b9={})),function(e){e[e.JSON_FORMAT_UNKNOWN=0]="JSON_FORMAT_UNKNOWN",e[e.ALLOW=1]="ALLOW",e[e.LEGACY_BEST_EFFORT=2]="LEGACY_BEST_EFFORT"}(I9||(I9={})),function(e){e[e.ENFORCE_NAMING_STYLE_UNKNOWN=0]="ENFORCE_NAMING_STYLE_UNKNOWN",e[e.STYLE2024=1]="STYLE2024",e[e.STYLE_LEGACY=2]="STYLE_LEGACY"}(A9||(A9={})),function(e){e[e.NONE=0]="NONE",e[e.SET=1]="SET",e[e.ALIAS=2]="ALIAS"}(w9||(w9={})),function(e){e[e.EDITION_UNKNOWN=0]="EDITION_UNKNOWN",e[e.EDITION_LEGACY=900]="EDITION_LEGACY",e[e.EDITION_PROTO2=998]="EDITION_PROTO2",e[e.EDITION_PROTO3=999]="EDITION_PROTO3",e[e.EDITION_2023=1e3]="EDITION_2023",e[e.EDITION_2024=1001]="EDITION_2024",e[e.EDITION_1_TEST_ONLY=1]="EDITION_1_TEST_ONLY",e[e.EDITION_2_TEST_ONLY=2]="EDITION_2_TEST_ONLY",e[e.EDITION_99997_TEST_ONLY=99997]="EDITION_99997_TEST_ONLY",e[e.EDITION_99998_TEST_ONLY=99998]="EDITION_99998_TEST_ONLY",e[e.EDITION_99999_TEST_ONLY=99999]="EDITION_99999_TEST_ONLY",e[e.EDITION_MAX=2147483647]="EDITION_MAX"}(O9||(O9={})),function(e){e[e.VISIBILITY_UNSET=0]="VISIBILITY_UNSET",e[e.VISIBILITY_LOCAL=1]="VISIBILITY_LOCAL",e[e.VISIBILITY_EXPORT=2]="VISIBILITY_EXPORT"}(N9||(N9={}));const D9={readUnknownFields:!0};function P9(e,t,n){const i=m6(e,void 0,!1);return L9(i,new W4(t),function(e){return e?Object.assign(Object.assign({},D9),e):D9}(n),!1,t.byteLength),i.message}function L9(e,t,n,i,r){var o;const s=i?t.len:t.pos+r;let a,c;const d=null!==(o=e.getUnknown())&&void 0!==o?o:[];for(;t.pos<s;){var l=l5(t.tag(),2);if(a=l[0],c=l[1],i&&c==U4.EndGroup)break;const r=e.findNumber(a);if(r)k9(e,t,r,c,n);else{const e=t.skip(c,a);n.readUnknownFields&&d.push({no:a,wireType:c,data:e})}}if(i&&(c!=U4.EndGroup||a!==r))throw new Error("invalid end group tag");d.length>0&&e.setUnknown(d)}function k9(e,t,n,i,r){var o;switch(n.fieldKind){case"scalar":e.set(n,U9(t,n.scalar));break;case"enum":const s=U9(t,GZ.INT32);if(n.enum.open)e.set(n,s);else if(IZ(n.enum).some((e=>e.number===s)))e.set(n,s);else if(r.readUnknownFields){const t=[];VZ(s,t);const r=null!==(o=e.getUnknown())&&void 0!==o?o:[];r.push({no:n.number,wireType:i,data:new Uint8Array(t)}),e.setUnknown(r)}break;case"message":e.set(n,M9(t,r,n,e.get(n)));break;case"list":!function(e,t,n,i){var r;const o=n.field();if("message"===o.listKind)return void n.add(M9(e,i,o));const s=null!==(r=o.scalar)&&void 0!==r?r:GZ.INT32;if(!(t==U4.LengthDelimited&&s!=GZ.STRING&&s!=GZ.BYTES))return void n.add(U9(e,s));const a=e.uint32()+e.pos;for(;e.pos<a;)n.add(U9(e,s))}(t,i,e.get(n),r);break;case"map":!function(e,t,n){const i=t.field();let r,o;const s=e.uint32(),a=e.pos+s;for(;e.pos<a;)switch(l5(e.tag(),1)[0]){case 1:r=U9(e,i.mapKey);break;case 2:switch(i.mapKind){case"scalar":o=U9(e,i.scalar);break;case"enum":o=e.int32();break;case"message":o=M9(e,n,i)}}if(void 0===r&&(r=WZ(i.mapKey,!1)),void 0===o)switch(i.mapKind){case"scalar":o=WZ(i.scalar,!1);break;case"enum":o=IZ(i.enum)[0].number;break;case"message":o=m6(i.message,void 0,!1)}t.set(r,o)}(t,e.get(n),r)}}function M9(e,t,n,i){const r=n.delimitedEncoding,o=null!=i?i:m6(n.message,void 0,!1);return L9(o,e,t,r,r?n.number:e.uint32()),o}function U9(e,t){switch(t){case GZ.STRING:return e.string();case GZ.BOOL:return e.bool();case GZ.DOUBLE:return e.double();case GZ.FLOAT:return e.float();case GZ.INT32:return e.int32();case GZ.INT64:return e.int64();case GZ.UINT64:return e.uint64();case GZ.FIXED64:return e.fixed64();case GZ.BYTES:return e.bytes();case GZ.FIXED32:return e.fixed32();case GZ.SFIXED32:return e.sfixed32();case GZ.SFIXED64:return e.sfixed64();case GZ.SINT64:return e.sint64();case GZ.UINT32:return e.uint32();case GZ.SINT32:return e.sint32()}}function V9(e,t){var n;const i=P9(l9,zq(e));return i.messageType.forEach(ZZ),i.dependency=null!==(n=null==t?void 0:t.map((e=>e.proto.name)))&&void 0!==n?n:[],dq(i,(e=>null==t?void 0:t.find((t=>t.proto.name===e)))).getFile(i.name)}const x9=d9(V9("Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYiJgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQnYKE2NvbS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAFaLGdvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL2FueXBiogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"),0);function F9(e){const t=e.lastIndexOf("/"),n=t>=0?e.substring(t+1):e;if(!n.length)throw new Error("invalid type url: ".concat(e));return n}const B9=V9("Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9idWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9idWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgBIAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToCOAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJvdG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoMc3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8KDHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RWYWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAAQn8KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAFaL2dvb2dsZS5nb2xhbmcub3JnL3Byb3RvYnVmL3R5cGVzL2tub3duL3N0cnVjdHBi+AEBogIDR1BCqgIeR29vZ2xlLlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM"),j9=d9(B9,0),G9=d9(B9,1),W9=d9(B9,2);var K9;!function(e){e[e.NULL_VALUE=0]="NULL_VALUE"}(K9||(K9={}));const H9=V9("CgpvcnRjLnByb3RvEgtpby5hZ29yYS5wYiKoAQoET1JUQxILCgNpY2UYASADKAkSJQoEZHRscxgCIAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSIQoEc2VuZBgDIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcBIhCgRyZWN2GAQgASgLMhMuaW8uYWdvcmEucGIuUnRwQ2FwEiYKCXNlbmRfcmVjdhgFIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcCLQAQoGUnRwQ2FwEjMKDGF1ZGlvX2NvZGVjcxgBIAMoCzIdLmlvLmFnb3JhLnBiLlBheWxvYWRBdHRyaWJ1dGUSMwoMdmlkZW9fY29kZWNzGAIgAygLMh0uaW8uYWdvcmEucGIuUGF5bG9hZEF0dHJpYnV0ZRItChBhdWRpb19leHRlbnNpb25zGAMgAygLMhMuaW8uYWdvcmEucGIuRXh0bWFwEi0KEHZpZGVvX2V4dGVuc2lvbnMYBCADKAsyEy5pby5hZ29yYS5wYi5FeHRtYXAiqQEKBkV4dG1hcBINCgVlbnRyeRgBIAEoDRIuCg5leHRlbnNpb25fbmFtZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZRIWCglkaXJlY3Rpb24YAyABKAlIAIgBARIhChRleHRlbnNpb25fYXR0cmlidXRlcxgEIAEoCUgBiAEBQgwKCl9kaXJlY3Rpb25CFwoVX2V4dGVuc2lvbl9hdHRyaWJ1dGVzIp4BChBQYXlsb2FkQXR0cmlidXRlEiQKB3J0cF9tYXAYASABKAsyEy5pby5hZ29yYS5wYi5SdHBNYXASHwoEZm10cBgCIAEoCzIRLmlvLmFnb3JhLnBiLkZtdHASLQoOcnRjcF9mZWVkYmFja3MYAyADKAsyFS5pby5hZ29yYS5wYi5GZWVkYmFjaxIUCgxwYXlsb2FkX3R5cGUYBCABKA0i4gEKBlJ0cE1hcBIfChJlbnVtX2VuY29kaW5nX25hbWUYASABKA1IAIgBARIhChRzdHJpbmdfZW5jb2RpbmdfbmFtZRgCIAEoCUgBiAEBEioKCmNsb2NrX3JhdGUYAyABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSIAoTZW5jb2RpbmdfcGFyYW1ldGVycxgEIAEoDUgCiAEBQhUKE19lbnVtX2VuY29kaW5nX25hbWVCFwoVX3N0cmluZ19lbmNvZGluZ19uYW1lQhYKFF9lbmNvZGluZ19wYXJhbWV0ZXJzIqoCCgRGbXRwEj4KD2VudW1fcGFyYW1ldGVycxgBIAMoCzIlLmlvLmFnb3JhLnBiLkZtdHAuRW51bVBhcmFtZXRlcnNFbnRyeRJCChFzdHJpbmdfcGFyYW1ldGVycxgCIAMoCzInLmlvLmFnb3JhLnBiLkZtdHAuU3RyaW5nUGFyYW1ldGVyc0VudHJ5Gk0KE0VudW1QYXJhbWV0ZXJzRW50cnkSCwoDa2V5GAEgASgNEiUKBXZhbHVlGAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlOgI4ARpPChVTdHJpbmdQYXJhbWV0ZXJzRW50cnkSCwoDa2V5GAEgASgJEiUKBXZhbHVlGAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlOgI4ASLMAQoIRmVlZGJhY2sSFgoJZW51bV90eXBlGAEgASgNSACIAQESGAoLc3RyaW5nX3R5cGUYAiABKAlIAYgBARIWCglwYXJhbWV0ZXIYAyABKAlIAogBARIXCgphZGRpdGlvbmFsGAQgASgJSAOIAQESFQoIaW50ZXJ2YWwYBSABKAlIBIgBAUIMCgpfZW51bV90eXBlQg4KDF9zdHJpbmdfdHlwZUIMCgpfcGFyYW1ldGVyQg0KC19hZGRpdGlvbmFsQgsKCV9pbnRlcnZhbCKBAQoRUnRwQ2FwQmVmb3JlTWVyZ2USIQoEc2VuZBgBIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcBIhCgRyZWN2GAIgASgLMhMuaW8uYWdvcmEucGIuUnRwQ2FwEiYKCXNlbmRfcmVjdhgDIAEoCzITLmlvLmFnb3JhLnBiLlJ0cENhcCKrEQoPT3J0Y05lZ290aWF0aW9uEk4KE2luX291dF9hdWRpb19wdF9tYXAYASADKAsyMS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uSW5PdXRBdWRpb1B0TWFwRW50cnkSTgoTaW5fb3V0X3ZpZGVvX3B0X21hcBgCIAMoCzIxLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5Jbk91dFZpZGVvUHRNYXBFbnRyeRJOChNvdXRfaW5fYXVkaW9fcHRfbWFwGAMgAygLMjEuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLk91dEluQXVkaW9QdE1hcEVudHJ5Ek4KE291dF9pbl92aWRlb19wdF9tYXAYBCADKAsyMS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uT3V0SW5WaWRlb1B0TWFwRW50cnkSYwoeaW5fb3V0X2F1ZGlvX2hlYWRlcl9leHRlbnNfbWFwGAUgAygLMjsuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLkluT3V0QXVkaW9IZWFkZXJFeHRlbnNNYXBFbnRyeRJjCh5vdXRfaW5fYXVkaW9faGVhZGVyX2V4dGVuc19tYXAYBiADKAsyOy5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uT3V0SW5BdWRpb0hlYWRlckV4dGVuc01hcEVudHJ5EmMKHmluX291dF92aWRlb19oZWFkZXJfZXh0ZW5zX21hcBgHIAMoCzI7LmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5Jbk91dFZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSYwoeb3V0X2luX3ZpZGVvX2hlYWRlcl9leHRlbnNfbWFwGAggAygLMjsuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLk91dEluVmlkZW9IZWFkZXJFeHRlbnNNYXBFbnRyeRJQChRydHBfcnR4X2F1ZGlvX3B0X21hcBgJIAMoCzIyLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SdHBSdHhBdWRpb1B0TWFwRW50cnkSUAoUcnRwX3J0eF92aWRlb19wdF9tYXAYCiADKAsyMi5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uUnRwUnR4VmlkZW9QdE1hcEVudHJ5ElAKFHJ0eF9ydHBfYXVkaW9fcHRfbWFwGAsgAygLMjIuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uLlJ0eFJ0cEF1ZGlvUHRNYXBFbnRyeRJQChRydHhfcnRwX3ZpZGVvX3B0X21hcBgMIAMoCzIyLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SdHhSdHBWaWRlb1B0TWFwRW50cnkSRQoOcnRwX3JlZF9wdF9tYXAYDSADKAsyLS5pby5hZ29yYS5wYi5PcnRjTmVnb3RpYXRpb24uUnRwUmVkUHRNYXBFbnRyeRJFCg5yZWRfcnRwX3B0X21hcBgOIAMoCzItLmlvLmFnb3JhLnBiLk9ydGNOZWdvdGlhdGlvbi5SZWRSdHBQdE1hcEVudHJ5Eg8KB2NmZ19ydHgYDyABKAgSFQoNaGFzX2F1ZGlvX3J0eBgQIAEoCBIVCg1oYXNfdmlkZW9fcnR4GBEgASgIEhAKCGNmZ19ycnRyGBIgASgIEhYKDmhhc192aWRlb19ycnRyGBMgASgIEhYKDmhhc19hdWRpb19ycnRyGBQgASgIEg8KB2NmZ19yZWQYFSABKAgSFQoNaGFzX2F1ZGlvX3JlZBgWIAEoCBIRCglpbl9yZWRfcHQYFyADKA0aNgoUSW5PdXRBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo2ChRJbk91dFZpZGVvUHRNYXBFbnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBGjYKFE91dEluQXVkaW9QdE1hcEVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaNgoUT3V0SW5WaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5Jbk91dEF1ZGlvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5PdXRJbkF1ZGlvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5Jbk91dFZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARpACh5PdXRJblZpZGVvSGVhZGVyRXh0ZW5zTWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHBSdHhBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHBSdHhWaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHhSdHBBdWRpb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARo3ChVSdHhSdHBWaWRlb1B0TWFwRW50cnkSCwoDa2V5GAEgASgNEg0KBXZhbHVlGAIgASgNOgI4ARoyChBSdHBSZWRQdE1hcEVudHJ5EgsKA2tleRgBIAEoDRINCgV2YWx1ZRgCIAEoDToCOAEaMgoQUmVkUnRwUHRNYXBFbnRyeRILCgNrZXkYASABKA0SDQoFdmFsdWUYAiABKA06AjgBKtACChJWaWRlb0V4dGVuc2lvbk5hbWUSGQoVVklERU9fRVhUX0hEUl9UT0ZGU0VUEAASGwoXVklERU9fRVhUX0FCU19TRU5EX1RJTUUQARIZChVWSURFT19FWFRfT1JJRU5UQVRJT04QAhISCg5WSURFT19FWFRfVFdDQxADEhsKF1ZJREVPX0VYVF9QTEFZT1VUX0RFTEFZEAQSGgoWVklERU9fRVhUX0NPTlRFTlRfVFlQRRAFEhoKFlZJREVPX0VYVF9WSURFT19USU1JTkcQBhIZChVWSURFT19FWFRfQ09MT1JfU1BBQ0UQBxIWChJWSURFT19FWFRfU0RFU19NSUQQCBIgChxWSURFT19FWFRfU0RFU19SVFBfU1RSRUFNX0lEEAkSKQolVklERU9fRVhUX1NERURfUkVQQUlSRURfUlRQX1NUUkVBTV9JRBAKKsQBChJBdWRpb0V4dGVuc2lvbk5hbWUSGQoVQVVESU9fRVhUX0FVRElPX0xFVkVMEAASGwoXQVVESU9fRVhUX0FCU19TRU5EX1RJTUUQARISCg5BVURJT19FWFRfVFdDQxACEhYKEkFVRElPX0VYVF9TREVTX01JRBADEiAKHEFVRElPX0VYVF9TREVTX1JUUF9TVFJFQU1fSUQQBBIoCiRBVURJT19FWFRfU0RTX1JFUEFJUkVEX1JUUF9TVFJFQU1fSUQQBSqBAwoMRW5jb2RpbmdOYW1lEh0KGUVOQ09ESU5HX05BTUVfVU5TUEVDSUZJRUQQABIVChFFTkNPRElOR19OQU1FX1ZQOBABEhUKEUVOQ09ESU5HX05BTUVfVlA5EAISFgoSRU5DT0RJTkdfTkFNRV9IMjY0EAMSFgoSRU5DT0RJTkdfTkFNRV9IMjY1EAQSFQoRRU5DT0RJTkdfTkFNRV9BVjEQBRIWChJFTkNPRElOR19OQU1FX0c3MTEQBhIWChJFTkNPRElOR19OQU1FX0c3MjIQBxIWChJFTkNPRElOR19OQU1FX09QVVMQCBIWChJFTkNPRElOR19OQU1FX1BDTVUQCRIWChJFTkNPRElOR19OQU1FX1BDTUEQChIUChBFTkNPRElOR19OQU1FX0NOEAsSIQodRU5DT0RJTkdfTkFNRV9URUxFUEhPTkVfRVZFTlQQDBIVChFFTkNPRElOR19OQU1FX1JUWBANEhUKEUVOQ09ESU5HX05BTUVfUkVEEA4qrgMKDUZtdHBQYXJhbWV0ZXISHgoaRk1UUF9QQVJBTUVURVJfVU5TUEVDSUZJRUQQABIbChdGTVRQX1BBUkFNRVRFUl9NSU5QVElNRRABEh8KG0ZNVFBfUEFSQU1FVEVSX1VTRUlOQkFOREZFQxACEhsKF0ZNVFBfUEFSQU1FVEVSX0xFVkVMX0lEEAMSHQoZRk1UUF9QQVJBTUVURVJfUFJPRklMRV9JRBAEEhwKGEZNVFBfUEFSQU1FVEVSX1RJRVJfRkxBRxAFEhoKFkZNVFBfUEFSQU1FVEVSX1RYX01PREUQBhIqCiZGTVRQX1BBUkFNRVRFUl9MRVZFTF9BU1lNTUVUUllfQUxMT1dFRBAHEiUKIUZNVFBfUEFSQU1FVEVSX1BBQ0tFVElaQVRJT05fTU9ERRAIEiMKH0ZNVFBfUEFSQU1FVEVSX1BST0ZJTEVfTEVWRUxfSUQQCRIcChhGTVRQX1BBUkFNRVRFUl9MRVZFTF9JRFgQChIaChZGTVRQX1BBUkFNRVRFUl9QUk9GSUxFEAsSFwoTRk1UUF9QQVJBTUVURVJfVElFUhAMKrEBCgxGZWVkYmFja1R5cGUSHQoZRkVFREJBQ0tfVFlQRV9VTlNQRUNJRklFRBAAEhsKF0ZFRURCQUNLX1RZUEVfR09PR19SRU1CEAESHgoaRkVFREJBQ0tfVFlQRV9UUkFOU1BPUlRfQ0MQAhIVChFGRUVEQkFDS19UWVBFX0NDTRADEhYKEkZFRURCQUNLX1RZUEVfTkFDSxAEEhYKEkZFRURCQUNLX1RZUEVfUlJUUhAFYgZwcm90bzM",[B9]);let Y9=function(e){return e[e.VIDEO_EXT_HDR_TOFFSET=0]="VIDEO_EXT_HDR_TOFFSET",e[e.VIDEO_EXT_ABS_SEND_TIME=1]="VIDEO_EXT_ABS_SEND_TIME",e[e.VIDEO_EXT_ORIENTATION=2]="VIDEO_EXT_ORIENTATION",e[e.VIDEO_EXT_TWCC=3]="VIDEO_EXT_TWCC",e[e.VIDEO_EXT_PLAYOUT_DELAY=4]="VIDEO_EXT_PLAYOUT_DELAY",e[e.VIDEO_EXT_CONTENT_TYPE=5]="VIDEO_EXT_CONTENT_TYPE",e[e.VIDEO_EXT_VIDEO_TIMING=6]="VIDEO_EXT_VIDEO_TIMING",e[e.VIDEO_EXT_COLOR_SPACE=7]="VIDEO_EXT_COLOR_SPACE",e[e.VIDEO_EXT_SDES_MID=8]="VIDEO_EXT_SDES_MID",e[e.VIDEO_EXT_SDES_RTP_STREAM_ID=9]="VIDEO_EXT_SDES_RTP_STREAM_ID",e[e.VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID=10]="VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID",e}({}),X9=function(e){return e[e.AUDIO_EXT_AUDIO_LEVEL=0]="AUDIO_EXT_AUDIO_LEVEL",e[e.AUDIO_EXT_ABS_SEND_TIME=1]="AUDIO_EXT_ABS_SEND_TIME",e[e.AUDIO_EXT_TWCC=2]="AUDIO_EXT_TWCC",e[e.AUDIO_EXT_SDES_MID=3]="AUDIO_EXT_SDES_MID",e[e.AUDIO_EXT_SDES_RTP_STREAM_ID=4]="AUDIO_EXT_SDES_RTP_STREAM_ID",e[e.AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID=5]="AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID",e}({}),J9=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.VP8=1]="VP8",e[e.VP9=2]="VP9",e[e.H264=3]="H264",e[e.H265=4]="H265",e[e.AV1=5]="AV1",e[e.G711=6]="G711",e[e.G722=7]="G722",e[e.OPUS=8]="OPUS",e[e.PCMU=9]="PCMU",e[e.PCMA=10]="PCMA",e[e.CN=11]="CN",e[e.TELEPHONE_EVENT=12]="TELEPHONE_EVENT",e[e.RTX=13]="RTX",e[e.RED=14]="RED",e}({}),z9=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.MINPTIME=1]="MINPTIME",e[e.USEINBANDFEC=2]="USEINBANDFEC",e[e.LEVEL_ID=3]="LEVEL_ID",e[e.PROFILE_ID=4]="PROFILE_ID",e[e.TIER_FLAG=5]="TIER_FLAG",e[e.TX_MODE=6]="TX_MODE",e[e.LEVEL_ASYMMETRY_ALLOWED=7]="LEVEL_ASYMMETRY_ALLOWED",e[e.PACKETIZATION_MODE=8]="PACKETIZATION_MODE",e[e.PROFILE_LEVEL_ID=9]="PROFILE_LEVEL_ID",e[e.LEVEL_IDX=10]="LEVEL_IDX",e[e.PROFILE=11]="PROFILE",e[e.TIER=12]="TIER",e}({}),Z9=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.GOOG_REMB=1]="GOOG_REMB",e[e.TRANSPORT_CC=2]="TRANSPORT_CC",e[e.CCM=3]="CCM",e[e.NACK=4]="NACK",e[e.RRTR=5]="RRTR",e}({});const q9=V9("CgxzaWduYWwucHJvdG8SC2lvLmFnb3JhLnBiIuUFCg5Vc2VyQXR0cmlidXRlcxIVCghmZWF0dXJlMRgBIAEoDUgAiAEBEhUKCGZlYXR1cmUyGAIgASgNSAGIAQESHAoPdG9wblNtb290aExldmVsGAMgASgNSAKIAQESIAoTdG9wbk5ld1NwZWFrZXJEZWxheRgEIAEoDUgDiAEBEh0KEHRvcG5Td2l0Y2hIb2xkTXMYBSABKA1IBIgBARIaCg10b3BuQXVkaW9HYWluGAYgASgNSAWIAQESHAoPbWF4U3Vic2NyaXB0aW9uGAcgASgNSAaIAQESJQoYc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOGAggASgNSAeIAQESFQoIcnRtMkZsYWcYCSABKA1ICIgBARIWCglwcmVTdWJOdW0YCiABKA1ICYgBARIpCglwcmVTdWJVaWQYCyADKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSFAoMZW5hYmxlU3ViU1ZDGAwgAygJEhkKEWVuYWJsZVN2Y0V4dGVuZGVkGA0gAygJEhsKDmF1ZGlvRHVwbGljYXRlGA4gASgNSAqIAQESGwoObnRwRml4ZWRPZmZzZXQYDyABKAVIC4gBARIxCgtleHBlcmltZW50cxgQIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RIDIgBAUILCglfZmVhdHVyZTFCCwoJX2ZlYXR1cmUyQhIKEF90b3BuU21vb3RoTGV2ZWxCFgoUX3RvcG5OZXdTcGVha2VyRGVsYXlCEwoRX3RvcG5Td2l0Y2hIb2xkTXNCEAoOX3RvcG5BdWRpb0dhaW5CEgoQX21heFN1YnNjcmlwdGlvbkIbChlfc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOQgsKCV9ydG0yRmxhZ0IMCgpfcHJlU3ViTnVtQhEKD19hdWRpb0R1cGxpY2F0ZUIRCg9fbnRwRml4ZWRPZmZzZXRCDgoMX2V4cGVyaW1lbnRzIrcBChZVc2VyQXR0cmlidXRlc1Jlc3BvbnNlEiwKC3ByZVN1YlNzcmNzGAEgAygLMhcuaW8uYWdvcmEucGIuUHJlU3ViU3NyYxIlChhzdWJzY3JpYmVBdWRpb0ZpbHRlclRvcE4YAiABKA1IAIgBARIrCgpleHRlbnNpb25zGAMgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdEIbChlfc3Vic2NyaWJlQXVkaW9GaWx0ZXJUb3BOInIKClByZVN1YlNzcmMSKAoDdWlkGAEgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlSACIAQESCQoBYRgCIAEoDRINCgVhX3J0eBgDIAEoDRIJCgF2GAQgASgNEg0KBXZfcnR4GAUgASgNQgYKBF91aWQizwYKDVNpZ25hbFJlcXVlc3QSFAoHbGljZW5zZRgBIAEoCUgAiAEBEg4KBnAycF9pZBgCIAEoDRISCgpzZXNzaW9uX2lkGAMgASgJEg4KBmFwcF9pZBgEIAEoCRITCgtjaGFubmVsX2tleRgFIAEoCRIUCgxjaGFubmVsX25hbWUYBiABKAkSEwoLc2RrX3ZlcnNpb24YByABKAkSFAoHYnJvd3NlchgIIAEoCUgBiAEBEioKCnByb2Nlc3NfaWQYCSABKAsyFi5nb29nbGUucHJvdG9idWYuVmFsdWUSDAoEbW9kZRgKIAEoCRINCgVjb2RlYxgLIAEoCRIRCgRyb2xlGAwgASgJSAKIAQESIAoTaGFzX2NoYW5nZWRfZ2F0ZXdheRgNIAEoCEgDiAEBEhMKBmV4dGVuZBgOIAEoCUgEiAEBEhkKDGNzZXJ2aWNlX21hcBgPIAEoCUgFiAEBEhoKDW9wdGlvbmFsX2luZm8YECABKAlIBogBARIZCgxhcHBfc2NlbmFyaW8YESABKAlIB4gBARIvCgphdHRyaWJ1dGVzGBIgASgLMhsuaW8uYWdvcmEucGIuVXNlckF0dHJpYnV0ZXMSEgoKcmVxdWVzdF90cxgTIAEoBBIXCgpzdHJpbmdfdWlkGBQgASgJSAiIAQESFQoIYWVzX21vZGUYFSABKAlICYgBARIXCgphZXNfc2VjcmV0GBYgASgJSAqIAQESGAoLYWVzX2VuY3J5cHQYFyABKAhIC4gBARIVCghhZXNfc2FsdBgYIAEoCUgMiAEBEiEKFGRlZmF1bHRfdmlkZW9fc3RyZWFtGBkgASgNSA2IAQFCCgoIX2xpY2Vuc2VCCgoIX2Jyb3dzZXJCBwoFX3JvbGVCFgoUX2hhc19jaGFuZ2VkX2dhdGV3YXlCCQoHX2V4dGVuZEIPCg1fY3NlcnZpY2VfbWFwQhAKDl9vcHRpb25hbF9pbmZvQg8KDV9hcHBfc2NlbmFyaW9CDQoLX3N0cmluZ191aWRCCwoJX2Flc19tb2RlQg0KC19hZXNfc2VjcmV0Qg4KDF9hZXNfZW5jcnlwdEILCglfYWVzX3NhbHRCFwoVX2RlZmF1bHRfdmlkZW9fc3RyZWFtIl8KEk11bHRpVW5pbGJzUmVxdWVzdBILCgN1cmkYASABKA0SJwoGZGV0YWlsGAIgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBITCgtzZXJ2aWNlX2lkcxgDIAMoDSKtAQoSU2RwRW5kcG9pbnRSZXF1ZXN0Ei8KBnVuaWxicxgBIAMoCzIfLmlvLmFnb3JhLnBiLk11bHRpVW5pbGJzUmVxdWVzdBILCgN1aWQYAiABKA0SDAoEb3BpZBgDIAEoBBIqCgZzaWduYWwYBCABKAsyGi5pby5hZ29yYS5wYi5TaWduYWxSZXF1ZXN0Eh8KBG9ydGMYBSABKAsyES5pby5hZ29yYS5wYi5PUlRDIvQCChNTZHBFbmRwb2ludFJlc3BvbnNlEicKBmRldGFpbBgBIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSEAoIZW50ZXJfdHMYAiABKAQSEAoIbGVhdmVfdHMYAyABKAQSDAoEb3BpZBgEIAEoBBI5Cg91bmlsYnNfcmVzcG9uc2UYBSADKAsyIC5pby5hZ29yYS5wYi5NdWx0aVVuaWxic1Jlc3BvbnNlEgsKA3VpZBgGIAEoDRJAChNhdHRyaWJ1dGVzX3Jlc3BvbnNlGAcgASgLMiMuaW8uYWdvcmEucGIuVXNlckF0dHJpYnV0ZXNSZXNwb25zZRIUCgxyZWpvaW5fdG9rZW4YCCABKAkSMAoIYWRkX29ydGMYCSABKAsyHi5pby5hZ29yYS5wYi5SdHBDYXBCZWZvcmVNZXJnZRIwCghkZWxfb3J0YxgKIAEoCzIeLmlvLmFnb3JhLnBiLlJ0cENhcEJlZm9yZU1lcmdlIq4BChNNdWx0aVVuaWxic1Jlc3BvbnNlEgwKBGNlcnQYASABKAkSCwoDY2lkGAIgASgNEgwKBGNvZGUYAyABKA0SJwoGZGV0YWlsGAQgASgLMhcuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdBIqCghzZXJ2aWNlcxgFIAMoCzIYLmlvLmFnb3JhLnBiLlNlcnZpY2VJbmZvEgwKBGZsYWcYBiABKA0SCwoDdXJpGAcgASgNIkkKC1NlcnZpY2VJbmZvEgoKAmlwGAEgASgJEgwKBHBvcnQYAiABKA0SEwoLZmluZ2VycHJpbnQYAyABKAkSCwoDaWNlGAQgAygJIn0KCkFQUmVzcG9uc2USCwoDdWlkGAEgASgNEgsKA2NpZBgCIAEoDRIMCgRjZXJ0GAMgASgJEicKBmRldGFpbBgEIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3QSEwoGdGlja2V0GAUgASgJSACIAQFCCQoHX3RpY2tldCK9AQoNSm9pbkZvcndhcmRlchISCgpyZWpvaW5fa2V5GAEgASgJEioKBnNpZ25hbBgCIAEoCzIaLmlvLmFnb3JhLnBiLlNpZ25hbFJlcXVlc3QSCwoDaWNlGAMgAygJEjEKC25lZ290aWF0aW9uGAQgASgLMhwuaW8uYWdvcmEucGIuT3J0Y05lZ290aWF0aW9uEiwKC2FwX3Jlc3BvbnNlGAUgASgLMhcuaW8uYWdvcmEucGIuQVBSZXNwb25zZSrbBQoVVXNlckF0dHJpYnV0ZUZlYXR1cmUxEg8KC1VOU1BFQ0lGSUVEEAASGgoWZW5hYmxlRW5jb2RlZFRyYW5zZm9ybRABEhcKE2VuYWJsZUF1ZGlvTWV0YWRhdGEQAhISCg5lbmFibGVBdWRpb1B0cxAEEh0KGWVuYWJsZU5ldHdvcmtRdWFsaXR5UHJvYmUQCBIbChdlbmFibGVQdWJsaXNoZWRVc2VyTGlzdBAQEhwKGGVuYWJsZVB1Ymxpc2hBdWRpb0ZpbHRlchAgEhoKFmVuYWJsZVVzZXJMaWNlbnNlQ2hlY2sQQBIOCgllbmFibGVSVFgQgAESFAoPZW5hYmxlTlRQUmVwb3J0EIACEhcKEmVuYWJsZUluc3RhbnRWaWRlbxCABBIZChRlbmFibGVGdWxsbGlua0F2U3luYxCACBIWChFlbmFibGVEYXRhU3RyZWFtMhCAEBIWChFlbmFibGVBdXRGZWVkYmFjaxCAIBIhChxlbmFibGVVc2VyQXV0b1JlYmFsYW5jZUNoZWNrEIBAEg4KCGVuYWJsZVhSEICAARIYChJlbmFibGVMb3NzYmFzZWRCd2UQgIACEhEKC2VuYWJsZUF1dENDEICABBIWChBlbmFibGVDQ0ZhbGxiYWNrEICACBIWChBlbmFibGVQcmVhbGxvY1BDEICAEBITCg1lbmFibGVQdWJUV0NDEICAIBITCg1lbmFibGVTdWJUV0NDEICAQBITCgxlbmFibGVQdWJSVFgQgICAARITCgxlbmFibGVTdWJSVFgQgICAAhIcChVlbmFibGVRdWFsaXR5RmFsbGJhY2sQgICABBIcChVzZW50dHNVc2VzQWJzU2VuZFRpbWUQgICACBIbChRlbmFibGVEdWFsU3RyZWFtRmxhZxCAgIAQEhEKCmRpc2FibGVGRUMQgICAIBIYChFlbmFibGVWb3NGYWxsYmFjaxCAgIBAYgZwcm90bzM",[B9,H9]),Q9=d9(q9,5),$9=d9(q9,6);let e8=function(e){return e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.enableEncodedTransform=1]="enableEncodedTransform",e[e.enableAudioMetadata=2]="enableAudioMetadata",e[e.enableAudioPts=4]="enableAudioPts",e[e.enableNetworkQualityProbe=8]="enableNetworkQualityProbe",e[e.enablePublishedUserList=16]="enablePublishedUserList",e[e.enablePublishAudioFilter=32]="enablePublishAudioFilter",e[e.enableUserLicenseCheck=64]="enableUserLicenseCheck",e[e.enableRTX=128]="enableRTX",e[e.enableNTPReport=256]="enableNTPReport",e[e.enableInstantVideo=512]="enableInstantVideo",e[e.enableFulllinkAvSync=1024]="enableFulllinkAvSync",e[e.enableDataStream2=2048]="enableDataStream2",e[e.enableAutFeedback=4096]="enableAutFeedback",e[e.enableUserAutoRebalanceCheck=8192]="enableUserAutoRebalanceCheck",e[e.enableXR=16384]="enableXR",e[e.enableLossbasedBwe=32768]="enableLossbasedBwe",e[e.enableAutCC=65536]="enableAutCC",e[e.enableCCFallback=131072]="enableCCFallback",e[e.enablePreallocPC=262144]="enablePreallocPC",e[e.enablePubTWCC=524288]="enablePubTWCC",e[e.enableSubTWCC=1048576]="enableSubTWCC",e[e.enablePubRTX=2097152]="enablePubRTX",e[e.enableSubRTX=4194304]="enableSubRTX",e[e.enableQualityFallback=8388608]="enableQualityFallback",e[e.senttsUsesAbsSendTime=16777216]="senttsUsesAbsSendTime",e[e.enableDualStreamFlag=33554432]="enableDualStreamFlag",e[e.disableFEC=67108864]="disableFEC",e[e.enableVosFallback=134217728]="enableVosFallback",e}({});const t8={VP8:J9.VP8,VP9:J9.VP9,H264:J9.H264,H265:J9.H265,AV1:J9.AV1,G711:J9.G711,G722:J9.G722,opus:J9.OPUS,PCMU:J9.PCMU,PCMA:J9.PCMA,CN:J9.CN,"telephone-event":J9.TELEPHONE_EVENT,rtx:J9.RTX,red:J9.RED};const n8={minptime:z9.MINPTIME,useinbandfec:z9.USEINBANDFEC,"level-id":z9.LEVEL_ID,"profile-id":z9.PROFILE_ID,"tier-flag":z9.TIER_FLAG,"tx-mode":z9.TX_MODE,"level-asymmetry-allowed":z9.LEVEL_ASYMMETRY_ALLOWED,"packetization-mode":z9.PACKETIZATION_MODE,"profile-level-id":z9.PROFILE_LEVEL_ID,"level-idx":z9.LEVEL_IDX,profile:z9.PROFILE,tier:z9.TIER};const i8={"goog-remb":Z9.GOOG_REMB,"transport-cc":Z9.TRANSPORT_CC,ccm:Z9.CCM,nack:Z9.NACK,rrtr:Z9.RRTR};function r8(e){if(e)return Object.keys(i8).find((t=>i8[t]===e))}const o8={"urn:ietf:params:rtp-hdrext:toffset":Y9.VIDEO_EXT_HDR_TOFFSET,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time":Y9.VIDEO_EXT_ABS_SEND_TIME,"urn:3gpp:video-orientation":Y9.VIDEO_EXT_ORIENTATION,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":Y9.VIDEO_EXT_TWCC,"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay":Y9.VIDEO_EXT_PLAYOUT_DELAY,"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type":Y9.VIDEO_EXT_CONTENT_TYPE,"http://www.webrtc.org/experiments/rtp-hdrext/video-timing":Y9.VIDEO_EXT_VIDEO_TIMING,"http://www.webrtc.org/experiments/rtp-hdrext/color-space":Y9.VIDEO_EXT_COLOR_SPACE,"urn:ietf:params:rtp-hdrext:sdes:mid":Y9.VIDEO_EXT_SDES_MID,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id":Y9.VIDEO_EXT_SDES_RTP_STREAM_ID,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id":Y9.VIDEO_EXT_SDED_REPAIRED_RTP_STREAM_ID},s8={"urn:ietf:params:rtp-hdrext:ssrc-audio-level":X9.AUDIO_EXT_AUDIO_LEVEL,"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time":X9.AUDIO_EXT_ABS_SEND_TIME,"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01":X9.AUDIO_EXT_TWCC,"urn:ietf:params:rtp-hdrext:sdes:mid":X9.AUDIO_EXT_SDES_MID,"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id":X9.AUDIO_EXT_SDES_RTP_STREAM_ID,"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id":X9.AUDIO_EXT_SDS_REPAIRED_RTP_STREAM_ID};function a8(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,"string");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:t+""}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c8(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function d8(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c8(Object(n),!0).forEach((function(t){a8(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c8(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function l8(e,t){return typeof xP(e)===t?xP(e):void 0}function u8(){try{const e=xP("EXPERIMENTS")||{};return"string"==typeof e||Array.isArray(e)?{}:d8({},e)}catch(e){return SL.debug("handle gateway attributes failed: ",e),{}}}function h8(e,t,n){var i,r;let o=n.mode,s=n.codec,a=n.joinGatewayStartTime,c=n.hasChangeBGPAddress;const d="apResponse"in t?Object.assign({},t.apResponse):void 0;let l=!1;var u,h;d&&(l=!!xP("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null===(u=d.detail)||void 0===u?void 0:u[5]),"CN"===(null===(h=d.detail)||void 0===h?void 0:h[3])&&xP("ENABLE_QUALITY_FALLBACK")&&xP("ENABLE_QUALITY_FALLBACK"));let p=xP("REPORT_APP_SCENARIO");if("string"!=typeof p)try{p=JSON.stringify(p)}catch(e){p=void 0}p&&p.length>128&&(p=void 0);const _="proxy3"===t.cloudProxyServer?"1":"proxy5"===t.cloudProxyServer?"2":void 0,E=function(e,t,n,i,r){var o,s,a,c;n=Object.assign({},n);const d=QL(e),l=$L(e),u=(null===(o=e.preSubOptions)||void 0===o?void 0:o.length)||0,h=u>0?null===(s=e.preSubOptions)||void 0===s?void 0:s.map((e=>e.uid)):void 0,p=l8("PRE_SUB_NUM","number")||1,_=u>p?u:p,E=u8(),m=(qO()||aN(18,4,!1))&&dN(18,6,!0)&&"h264"===t&&xP("ENABLE_ABSSENDTIME_AS_SENTTS"),f=!("CN"!==(null===(a=n.detail)||void 0===a?void 0:a[3])||!xP("ENABLE_QUALITY_FALLBACK"))&&xP("ENABLE_QUALITY_FALLBACK"),g=d8(d8({enableEncodedTransform:(!!xP("ENABLE_AUDIO_METADATA")||!!xP("ENABLE_AUDIO_PTS"))&&p8||!!xP("ENABLE_AUDIO_TOPN")&&iN(xO.CHROME,87,116)||void 0,enableAudioMetadata:!!xP("ENABLE_AUDIO_METADATA")&&p8,enableAudioPts:!!xP("ENABLE_AUDIO_PTS")&&p8,topnSmoothLevel:xP("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:xP("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:xP("TOPN_SWITCH_HOLD_MS"),topnAudioGain:xP("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:e.networkQualityProbe,enablePublishedUserList:xP("ENABLE_PUBLISHED_USER_LIST"),enableUserList:xP("ENABLE_USER_LIST"),maxSubscription:xP("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:l8("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:l8("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:l8("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===xP("USE_PUB_RTX")||!0===xP("USE_SUB_RTX")||void 0,disableFEC:xP("DISABLE_FEC"),enableNTPReport:!!xP("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:l,enableFulllinkAvSync:!!xP("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:l8("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:tk(),rtm2Flag:"number"==typeof i?i:void 0,enableUserAutoRebalanceCheck:!!xP("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:l8("USE_XR","boolean"),enableLossbasedBwe:l8("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:ek(),enableCCFallback:l8("ENABLE_CC_FALLBACK","boolean"),preSubUid:d?h:void 0,preSubNum:d?_:void 0,enablePubTWCC:l8("PUBLISH_TWCC","boolean"),enableSubTWCC:l8("SUBSCRIBE_TWCC","boolean"),enablePubRTX:l8("USE_PUB_RTX","boolean"),enableSubRTX:l8("USE_SUB_RTX","boolean"),enableSubSVC:xP("ENABLE_SVC")?xP("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(xP("SVC"))&&0!==xP("SVC").length?xP("SVC"):void 0,enableSvcExtended:xP("ENABLE_SVC")&&Array.isArray(xP("SVC_EXTENDED"))&&0!==xP("SVC_EXTENDED").length?xP("SVC_EXTENDED"):void 0,enableVosFallback:xP("ENABLE_VOS_FALLBACK"),enableQualityFallback:f},E),{},{audioDuplicate:l8("ENABLE_AUDIO_RED","boolean")?null!==(c=l8("AUDIO_DUPLICATE_NUM","number"))&&void 0!==c?c:2:void 0,senttsUsesAbsSendTime:!!m||void 0,enableDualStreamFlag:l8("ENABLE_DUAL_STREAM_FLAG","boolean"),enableAiClientMode:!!e.aiClientMode||void 0,enableAiClientBbrStrategy:!!e.aiClientMode||void 0,dcMediaStreamId:e.aiClientMode?e.mediaDcId:void 0});for(const e in g)void 0===g[e]&&delete g[e],Array.isArray(g[e])&&0===g[e].length&&delete g[e],"enablePreallocPC"===e&&delete g[e];return g.enablePreallocPC=!0,e.flexiblePC&&(g.flexiblePC=!0),g}(e,s,d,t.rtmFlag),m=d8(d8(d8(d8(d8({},t.license?{license:t.license}:{}),{},{p2pId:e.p2pId,sessionId:t.sid,appId:t.appId,channelKey:null!==(i=t.token)&&void 0!==i?i:t.appId,channelName:t.cname,sdkVersion:wP,processId:xP("PROCESS_ID"),mode:e.useP2P?"p2p":o,codec:s,role:null!==(r=t.role)&&void 0!==r?r:"audience",hasChangedGateway:l||c,extend:xP("JOIN_EXTEND")},_?{cservice_map:_}:{}),t.optionalInfo?{optionalInfo:t.optionalInfo}:{}),p?{appScenario:p}:{}),{},{attributes:_8(E),requestTs:(f=a,Number(f))});var f;return t.stringUid&&(m.stringUid=t.stringUid),t.aesmode&&t.aespassword&&(m.aesMode=t.aesmode,xP("ENCRYPT_AES")?(m.aesSecret=t.aespassword,m.aesEncrypt=!0):m.aesSecret=t.aespassword,t.aessalt&&(m.aesSalt=t.aessalt)),void 0!==t.defaultVideoStream&&(m.defaultVideoStream=t.defaultVideoStream),m}const p8=tN(87)||ZO()||oN(117);function _8(e){const t={enableSubSVC:[],enableSvcExtended:[]},n=["topnSmoothLevel","topnNewSpeakerDelay","topnSwitchHoldMs","topnAudioGain","maxSubscription","subscribeAudioFilterTopN","rtm2Flag","preSubNum","enableSubSVC","enableSvcExtended","audioDuplicate","preSubUid"],i={};for(const e in e8){const t=e8[e];"number"==typeof t&&0!==t&&(i[e]=t)}const r=[],o={};for(const s in e){const a=e[s];if(s in i&&!0===a){const e=i[s];let t,n;for(e<4294967296?(t=0,n=e):(t=1,n=1<<Math.floor(Math.log2(e))-32);r.length<=t;)r.push(0);r[t]|=n}else Ui(n).call(n,s)?t[s]=a:s in i||(o[s]=a)}r.length>0&&r.forEach(((e,n)=>{void 0!==e&&0!==e&&(t["feature".concat(n+1)]=e)}));const s=Object.keys(o);s.length>0&&(t.experiments=o,s.forEach((e=>{e in t&&delete t[e]})));for(const e in t)void 0===t[e]&&delete t[e],Array.isArray(t[e])&&0===t[e].length&&delete t[e];return t}function E8(e){var t,n,i,r;const o=function(e){if(e)return t8[e]||void 0}(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName),s=o||null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName,a=null===(i=e.rtpMap)||void 0===i?void 0:i.encodingParameters,c=null===(r=e.fmtp)||void 0===r?void 0:r.parameters;let d,l;c&&Object.keys(c).forEach((e=>{const t=function(e){if(e)return n8[e]||void 0}(e);t?(d||(d={}),d[t]=c[e]+""):(l||(l={}),l[e]=c[e]+"")}));const u=d||l?d8(d8({},d?{enumParameters:d}:{}),l?{stringParameters:l}:{}):void 0;return d8(d8({payloadType:e.payloadType,rtpMap:e.rtpMap?d8(d8(d8({},o?{enumEncodingName:o}:{}),s?{stringEncodingName:s}:{}),{},{clockRate:e.rtpMap.clockRate+""},a?{encodingParameters:a}:{}):void 0},u?{fmtp:u}:{}),{},{rtcpFeedbacks:e.rtcpFeedbacks.map((e=>{const t=function(e){if(e)return i8[e]||void 0}(e.type),n=d8(d8(d8({},"parameter"in e&&e.parameter?{parameter:e.parameter}:{}),"additional"in e&&e.additional?{additional:e.additional}:{}),"interval"in e&&e.interval?{interval:e.interval}:{});return d8(t?{enumType:t}:{stringType:e.type},n)}))})}function m8(e){let t;if(e.rtpMap){const n=e.rtpMap,i=n.enumEncodingName,r=n.stringEncodingName,o=n.clockRate,s=n.encodingParameters,a=i?function(e){if(e)return Object.keys(t8).find((t=>t8[t]===e))}(i):r;t={encodingName:null!=a?a:"",clockRate:(null==o?void 0:o.kind.value)+"",encodingParameters:s}}const n={parameters:{}};if(e.fmtp){const t=e.fmtp,i=t.enumParameters,r=t.stringParameters;i&&Object.keys(i).forEach((e=>{const t=function(e){if(e)return Object.keys(n8).find((t=>n8[t]===e))}(e);t&&(n.parameters[t]=i[e].kind.value+"")})),r&&Object.keys(r).forEach((e=>{n.parameters[e]=r[e].kind.value+""}))}let i=[];return e.rtcpFeedbacks&&(i=e.rtcpFeedbacks.map((e=>{const t=e.enumType,n=e.stringType,i=e.parameter,r=e.additional,o=e.interval,s=d8(d8(d8({},i?{parameter:i}:{}),r?{additional:r}:{}),o?{interval:o}:{});return d8(t?{type:r8(t)+""}:{type:n+""},s)}))),{payloadType:e.payloadType,rtpMap:t,fmtp:n,rtcpFeedbacks:i}}function f8(e,t){const n=function(e,t){if("video"===e){const e=o8[t];return"number"==typeof e?e:void 0}if("audio"===e){const e=o8[t];return"number"==typeof e?e:void 0}}(e,t.extensionName);return{entry:t.entry,extensionName:"number"==typeof n?n:t.extensionName}}function g8(e,t){var n,i;const r=function(e,t){if(t||"number"==typeof t)return"video"===e?Object.keys(o8).find((e=>o8[e]===t)):Object.keys(s8).find((e=>s8[e]===t))}(e,Number(null===(n=t.extensionName)||void 0===n?void 0:n.kind.value))||(null===(i=t.extensionName)||void 0===i?void 0:i.kind.value);return{entry:t.entry,extensionName:r+""}}function S8(e){var t,n,i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,C;const b={audioCodecs:null!==(t=null===(n=e.rtpCapabilities.send)||void 0===n?void 0:n.audioCodecs.map((e=>E8(e))))&&void 0!==t?t:[],videoCodecs:null!==(i=null===(r=e.rtpCapabilities.send)||void 0===r?void 0:r.videoCodecs.map((e=>E8(e))))&&void 0!==i?i:[],audioExtensions:null!==(o=null===(s=e.rtpCapabilities.send)||void 0===s?void 0:s.audioExtensions.map((e=>f8("audio",e))))&&void 0!==o?o:[],videoExtensions:null!==(a=null===(c=e.rtpCapabilities.send)||void 0===c?void 0:c.videoExtensions.map((e=>f8("video",e))))&&void 0!==a?a:[]},I={audioCodecs:null!==(d=null===(l=e.rtpCapabilities.recv)||void 0===l?void 0:l.audioCodecs.map((e=>E8(e))))&&void 0!==d?d:[],videoCodecs:null!==(u=null===(h=e.rtpCapabilities.recv)||void 0===h?void 0:h.videoCodecs.map((e=>E8(e))))&&void 0!==u?u:[],audioExtensions:null!==(p=null===(_=e.rtpCapabilities.recv)||void 0===_?void 0:_.audioExtensions.map((e=>f8("audio",e))))&&void 0!==p?p:[],videoExtensions:null!==(E=null===(m=e.rtpCapabilities.recv)||void 0===m?void 0:m.videoExtensions.map((e=>f8("video",e))))&&void 0!==E?E:[]},A={audioCodecs:null!==(f=null===(g=e.rtpCapabilities.sendrecv)||void 0===g?void 0:g.audioCodecs.map((e=>E8(e))))&&void 0!==f?f:[],videoCodecs:null!==(S=null===(T=e.rtpCapabilities.sendrecv)||void 0===T?void 0:T.videoCodecs.map((e=>E8(e))))&&void 0!==S?S:[],audioExtensions:null!==(R=null===(v=e.rtpCapabilities.sendrecv)||void 0===v?void 0:v.audioExtensions.map((e=>f8("audio",e))))&&void 0!==R?R:[],videoExtensions:null!==(y=null===(C=e.rtpCapabilities.sendrecv)||void 0===C?void 0:C.videoExtensions.map((e=>f8("video",e))))&&void 0!==y?y:[]};return{ice:[e.iceParameters.iceUfrag,e.iceParameters.icePwd],dtls:e.dtlsParameters.fingerprints.map((e=>({[e.hashFunction]:e.fingerprint}))),send:b,recv:I,sendRecv:A}}function T8(e,t,n){var i,r,o,s,a,c,d,l,u,h,p,_,E,m,f,g,S,T,R,v,y,C,b,I,A,w,O,N,D,P,L,k;t&&t.sendRecv&&(t.send={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(S=t.send)||void 0===S?void 0:S.audioCodecs)||[],...t.sendRecv.audioCodecs],videoCodecs:[...(null===(T=t.send)||void 0===T?void 0:T.videoCodecs)||[],...t.sendRecv.videoCodecs],audioExtensions:[...(null===(R=t.send)||void 0===R?void 0:R.audioExtensions)||[],...t.sendRecv.audioExtensions],videoExtensions:[...(null===(v=t.send)||void 0===v?void 0:v.videoExtensions)||[],...t.sendRecv.videoExtensions]},t.recv={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(y=t.recv)||void 0===y?void 0:y.audioCodecs)||[],...t.sendRecv.audioCodecs],videoCodecs:[...(null===(C=t.recv)||void 0===C?void 0:C.videoCodecs)||[],...t.sendRecv.videoCodecs],audioExtensions:[...(null===(b=t.recv)||void 0===b?void 0:b.audioExtensions)||[],...t.sendRecv.audioExtensions],videoExtensions:[...(null===(I=t.recv)||void 0===I?void 0:I.videoExtensions)||[],...t.sendRecv.videoExtensions]}),n&&n.sendRecv&&(n.send={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(A=n.send)||void 0===A?void 0:A.audioCodecs)||[],...n.sendRecv.audioCodecs],videoCodecs:[...(null===(w=n.send)||void 0===w?void 0:w.videoCodecs)||[],...n.sendRecv.videoCodecs],audioExtensions:[...(null===(O=n.send)||void 0===O?void 0:O.audioExtensions)||[],...n.sendRecv.audioExtensions],videoExtensions:[...(null===(N=n.send)||void 0===N?void 0:N.videoExtensions)||[],...n.sendRecv.videoExtensions]},n.recv={$typeName:"io.agora.pb.RtpCap",audioCodecs:[...(null===(D=n.recv)||void 0===D?void 0:D.audioCodecs)||[],...n.sendRecv.audioCodecs],videoCodecs:[...(null===(P=n.recv)||void 0===P?void 0:P.videoCodecs)||[],...n.sendRecv.videoCodecs],audioExtensions:[...(null===(L=n.recv)||void 0===L?void 0:L.audioExtensions)||[],...n.sendRecv.audioExtensions],videoExtensions:[...(null===(k=n.recv)||void 0===k?void 0:k.videoExtensions)||[],...n.sendRecv.videoExtensions]});const M=t?{send:{audioCodecs:(null===(i=t.send)||void 0===i?void 0:i.audioCodecs.map((e=>m8(e))))||[],videoCodecs:(null===(r=t.send)||void 0===r?void 0:r.videoCodecs.map((e=>m8(e))))||[],audioExtensions:(null===(o=t.send)||void 0===o?void 0:o.audioExtensions.map((e=>g8("audio",e))))||[],videoExtensions:(null===(s=t.send)||void 0===s?void 0:s.videoExtensions.map((e=>g8("video",e))))||[]},recv:{audioCodecs:(null===(a=t.recv)||void 0===a?void 0:a.audioCodecs.map((e=>m8(e))))||[],videoCodecs:(null===(c=t.recv)||void 0===c?void 0:c.videoCodecs.map((e=>m8(e))))||[],audioExtensions:(null===(d=t.recv)||void 0===d?void 0:d.audioExtensions.map((e=>g8("audio",e))))||[],videoExtensions:(null===(l=t.recv)||void 0===l?void 0:l.videoExtensions.map((e=>g8("video",e))))||[]}}:void 0,U=n?{send:{audioCodecs:(null===(u=n.send)||void 0===u?void 0:u.audioCodecs.map((e=>m8(e))))||[],videoCodecs:(null===(h=n.send)||void 0===h?void 0:h.videoCodecs.map((e=>m8(e))))||[],audioExtensions:(null===(p=n.send)||void 0===p?void 0:p.audioExtensions.map((e=>g8("audio",e))))||[],videoExtensions:(null===(_=n.send)||void 0===_?void 0:_.videoExtensions.map((e=>g8("video",e))))||[]},recv:{audioCodecs:(null===(E=n.recv)||void 0===E?void 0:E.audioCodecs.map((e=>m8(e))))||[],videoCodecs:(null===(m=n.recv)||void 0===m?void 0:m.videoCodecs.map((e=>m8(e))))||[],audioExtensions:(null===(f=n.recv)||void 0===f?void 0:f.audioExtensions.map((e=>g8("audio",e))))||[],videoExtensions:(null===(g=n.recv)||void 0===g?void 0:g.videoExtensions.map((e=>g8("video",e))))||[]}}:void 0,V={send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},x=e.send,F=e.recv,B=e.sendrecv;return x&&(V.send.audioCodecs.push(...x.audioCodecs),V.send.videoCodecs.push(...x.videoCodecs),V.send.audioExtensions.push(...x.audioExtensions),V.send.videoExtensions.push(...x.videoExtensions)),F&&(V.recv.audioCodecs.push(...F.audioCodecs),V.recv.videoCodecs.push(...F.videoCodecs),V.recv.audioExtensions.push(...F.audioExtensions),V.recv.videoExtensions.push(...F.videoExtensions)),B&&(V.send.audioCodecs.push(...B.audioCodecs),V.send.videoCodecs.push(...B.videoCodecs),V.send.audioExtensions.push(...B.audioExtensions),V.send.videoExtensions.push(...B.videoExtensions),V.recv.audioCodecs.push(...B.audioCodecs),V.recv.videoCodecs.push(...B.videoCodecs),V.recv.audioExtensions.push(...B.audioExtensions),V.recv.videoExtensions.push(...B.videoExtensions)),M&&(V.send.audioCodecs.push(...M.send.audioCodecs),V.send.videoCodecs.push(...M.send.videoCodecs),V.send.audioExtensions.push(...M.send.audioExtensions),V.send.videoExtensions.push(...M.send.videoExtensions),V.recv.audioCodecs.push(...M.recv.audioCodecs),V.recv.videoCodecs.push(...M.recv.videoCodecs),V.recv.audioExtensions.push(...M.recv.audioExtensions),V.recv.videoExtensions.push(...M.recv.videoExtensions)),U&&(U.send.audioCodecs.forEach((e=>{V.send.audioCodecs=V.send.audioCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.send.videoCodecs.forEach((e=>{V.send.videoCodecs=V.send.videoCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.send.audioExtensions.forEach((e=>{V.send.audioExtensions=V.send.audioExtensions.filter((t=>t.entry!==e.entry))})),U.send.videoExtensions.forEach((e=>{V.send.videoExtensions=V.send.videoExtensions.filter((t=>t.entry!==e.entry))})),U.recv.audioCodecs.forEach((e=>{V.recv.audioCodecs=V.recv.audioCodecs.filter((t=>t.payloadType!==e.payloadType))})),U.recv.videoCodecs.forEach((e=>{V.recv.videoCodecs=V.recv.videoCodecs.filter((t=>t.payloadType!==e.payloadType))}))),{send:V.recv,recv:V.send}}function R8(e,t){C8(t,e);const n=function(e,t){if(void 0===e)return[];if("enum"===t.fieldKind||"scalar"===t.fieldKind){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.number)return[e[n]];return[]}return e.filter((e=>e.no===t.number))}(e.$unknown,t),i=l5(y8(t),3),r=i[0],o=i[1],s=i[2];for(const e of n)k9(r,new W4(e.data),o,e.wireType,{readUnknownFields:!0});return s()}function v8(e,t,n){var i;C8(t,e);const r=(null!==(i=e.$unknown)&&void 0!==i?i:[]).filter((e=>e.no!==t.number)),o=l5(y8(t,n),2),s=o[0],a=o[1],c=new G4;F6(c,{writeUnknownFields:!0},s,a);const d=new W4(c.finish());for(;d.pos<d.len;){const e=l5(d.tag(),2),t=e[0],n=e[1],i=d.skip(n,t);r.push({no:t,wireType:n,data:i})}e.$unknown=r}function y8(e,t){const n=e.typeName,i=Object.assign(Object.assign({},e),{kind:"field",parent:e.extendee,localName:n}),r=Object.assign(Object.assign({},e.extendee),{fields:[i],members:[i],oneofs:[]}),o=s6(r,void 0!==t?{[n]:t}:void 0);return[m6(r,o),i,()=>{const t=o[n];if(void 0===t){const t=e.message;return t6(t)?WZ(t.fields[0].scalar,t.fields[0].longAsString):s6(t)}return t}]}function C8(e,t){if(e.extendee.typeName!=t.$typeName)throw new Error("extension ".concat(e.typeName," can only be applied to message ").concat(e.extendee.typeName))}const b8=3,I8=2,A8={alwaysEmitImplicit:!1,enumAsInteger:!1,useProtoFieldName:!1};function w8(e,t){var n;const i=function(e,t){var n;if(e.desc.typeName.startsWith("google.protobuf."))switch(e.desc.typeName){case"google.protobuf.Any":return function(e,t){if(""===e.typeUrl)return{};const n=t.registry;let i,r;if(n&&(i=function(e,t){if(""===e.typeUrl)return;const n="message"==t.kind?t:t.getMessage(F9(e.typeUrl));return n&&function(e,t){return""!==e.typeUrl&&("string"==typeof t?t:t.typeName)===F9(e.typeUrl)}(e,n)?P9(n,e.value):void 0}(e,n),i&&(r=n.getMessage(i.$typeName))),!r||!i)throw new Error("cannot encode message ".concat(e.$typeName,' to JSON: "').concat(e.typeUrl,'" is not in the type registry'));let o=w8(m6(r,i),t);return(r.typeName.startsWith("google.protobuf.")||null===o||Array.isArray(o)||"object"!=typeof o)&&(o={value:o}),o["@type"]=e.typeUrl,o}(e.message,t);case"google.protobuf.Timestamp":return function(e){const t=1e3*Number(e.seconds);if(t<Date.parse("0001-01-01T00:00:00Z")||t>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot encode message ".concat(e.$typeName," to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive"));if(e.nanos<0)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos must not be negative"));if(e.nanos>999999999)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos must not be greater than 99999999"));let n="Z";if(e.nanos>0){const t=(e.nanos+1e9).toString().substring(1);n="000000"===t.substring(3)?"."+t.substring(0,3)+"Z":"000"===t.substring(6)?"."+t.substring(0,6)+"Z":"."+t+"Z"}return new Date(t).toISOString().replace(".000Z",n)}(e.message);case"google.protobuf.Duration":return function(e){const t=Number(e.seconds),n=e.nanos;if(t>315576e6||t<-315576e6)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: value out of range"));if(t>0&&n<0||t<0&&n>0)throw new Error("cannot encode message ".concat(e.$typeName," to JSON: nanos sign must match seconds sign"));let i=e.seconds.toString();if(0!==n){let e=Math.abs(n).toString();e="0".repeat(9-e.length)+e,"000000"===e.substring(3)?e=e.substring(0,3):"000"===e.substring(6)&&(e=e.substring(0,6)),i+="."+e,n<0&&0==t&&(i="-"+i)}return i+"s"}(e.message);case"google.protobuf.FieldMask":return(n=e.message).paths.map((e=>{if(e.match(/_[0-9]?_/g)||e.match(/[A-Z]/g))throw new Error("cannot encode message ".concat(n.$typeName,' to JSON: lowerCamelCase of path name "')+e+'" is irreversible');return XW(e)})).join(",");case"google.protobuf.Struct":return L8(e.message);case"google.protobuf.Value":return k8(e.message);case"google.protobuf.ListValue":return M8(e.message);default:if(t6(e.desc)){const t=e.desc.fields[0];return D8(t,e.get(t))}return}}(e,t);if(void 0!==i)return i;const r={};for(const n of e.sortedFields){if(!e.isSet(n)){if(n.presence==b8)throw new Error("cannot encode ".concat(n," to JSON: required field not set"));if(!t.alwaysEmitImplicit||n.presence!==I8)continue}const i=O8(n,e.get(n),t);void 0!==i&&(r[P8(n,t)]=i)}if(t.registry){const i=new Set;for(const o of null!==(n=e.getUnknown())&&void 0!==n?n:[]){const n=o.no;if(!i.has(n)){i.add(n);const o=t.registry.getExtensionFor(e.desc,n);if(!o)continue;const s=l5(y8(o,R8(e.message,o)),2),a=s[0],c=s[1],d=O8(c,a.get(c),t);void 0!==d&&(r[o.jsonName]=d)}}}return r}function O8(e,t,n){switch(e.fieldKind){case"scalar":return D8(e,t);case"message":return w8(t,n);case"enum":return N8(e.enum,t,n.enumAsInteger);case"list":return function(e,t){const n=e.field(),i=[];switch(n.listKind){case"scalar":for(const t of e)i.push(D8(n,t));break;case"enum":for(const r of e)i.push(N8(n.enum,r,t.enumAsInteger));break;case"message":for(const n of e)i.push(w8(n,t))}return t.alwaysEmitImplicit||i.length>0?i:void 0}(t,n);case"map":return function(e,t){const n=e.field(),i={};switch(n.mapKind){case"scalar":for(const t of e){var r=l5(t,2);const e=r[0],o=r[1];i[e]=D8(n,o)}break;case"message":for(const n of e){var o=l5(n,2);const e=o[0],r=o[1];i[e]=w8(r,t)}break;case"enum":for(const r of e){var s=l5(r,2);const e=s[0],o=s[1];i[e]=N8(n.enum,o,t.enumAsInteger)}}return t.alwaysEmitImplicit||e.size>0?i:void 0}(t,n)}}function N8(e,t,n){var i;if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: expected number, got ").concat(q4(t)));if("google.protobuf.NullValue"==e.typeName)return null;if(n)return t;const r=e.value[t];return null!==(i=null==r?void 0:r.name)&&void 0!==i?i:t}function D8(e,t){var n,i,r,o,s,a;switch(e.scalar){case GZ.INT32:case GZ.SFIXED32:case GZ.SINT32:case GZ.FIXED32:case GZ.UINT32:if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(n=Y4(e,t))||void 0===n?void 0:n.message));return t;case GZ.FLOAT:case GZ.DOUBLE:if("number"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(i=Y4(e,t))||void 0===i?void 0:i.message));return Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t;case GZ.STRING:if("string"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(r=Y4(e,t))||void 0===r?void 0:r.message));return t;case GZ.BOOL:if("boolean"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(o=Y4(e,t))||void 0===o?void 0:o.message));return t;case GZ.UINT64:case GZ.FIXED64:case GZ.INT64:case GZ.SFIXED64:case GZ.SINT64:if("bigint"!=typeof t&&"string"!=typeof t)throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(s=Y4(e,t))||void 0===s?void 0:s.message));return t.toString();case GZ.BYTES:if(t instanceof Uint8Array)return function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"std";const n=$q(t),i="std"==t;let r,o="",s=0,a=0;for(let t=0;t<e.length;t++)switch(r=e[t],s){case 0:o+=n[r>>2],a=(3&r)<<4,s=1;break;case 1:o+=n[a|r>>4],a=(15&r)<<2,s=2;break;case 2:o+=n[a|r>>6],o+=n[63&r],s=0}return s&&(o+=n[a],i&&(o+="=",1==s&&(o+="="))),o}(t);throw new Error("cannot encode ".concat(e," to JSON: ").concat(null===(a=Y4(e,t))||void 0===a?void 0:a.message))}}function P8(e,t){return t.useProtoFieldName?e.name:e.jsonName}function L8(e){const t={};for(const i of Object.entries(e.fields)){var n=l5(i,2);const e=n[0],r=n[1];t[e]=k8(r)}return t}function k8(e){switch(e.kind.case){case"nullValue":return null;case"numberValue":if(!Number.isFinite(e.kind.value))throw new Error("".concat(e.$typeName," cannot be NaN or Infinity"));return e.kind.value;case"boolValue":case"stringValue":return e.kind.value;case"structValue":return L8(e.kind.value);case"listValue":return M8(e.kind.value);default:throw new Error("".concat(e.$typeName," must have a value"))}}function M8(e){return IZ(e).map(k8)}var U8="\t\n\v\f\r                 \u2028\u2029\ufeff",V8=SK,x8=n$,F8=U8,B8=sK("".replace),j8=RegExp("^["+F8+"]+"),G8=RegExp("(^|[^"+F8+"])["+F8+"]+$"),W8=function(e){return function(t){var n=x8(V8(t));return 1&e&&(n=B8(n,j8,"")),2&e&&(n=B8(n,G8,"$1")),n}},K8={start:W8(1),end:W8(2),trim:W8(3)},H8=$X.PROPER,Y8=eK,X8=U8,J8=zS(K8);XX({target:"String",proto:!0,forced:function(e){return Y8((function(){return!!X8[e]()||"​…᠎"!=="​…᠎"[e]()||H8&&X8[e].name!==e}))}("trim")},{trim:function(){return J8(this)}});var z8=gZ("String","trim"),Z8=tH,q8=z8,Q8=String.prototype,$8=qW((function(e){var t=zS(e);return"string"==typeof e||e===Q8||Z8(Q8,e)&&t===zS(Q8)?q8:t}));const e7={ignoreUnknownFields:!1};function t7(e,t,n){var i;if(function(e,t,n){if(!e.desc.typeName.startsWith("google.protobuf."))return!1;switch(e.desc.typeName){case"google.protobuf.Any":return function(e,t,n){var i;if(null===t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: expected object but got ").concat(q4(t)));if(0==Object.keys(t).length)return;const r=t["@type"];if("string"!=typeof r||""==r)throw new Error("cannot decode message ".concat(e.$typeName,' from JSON: "@type" is empty'));const o=A4(r).call(r,"/")?r.substring(r.lastIndexOf("/")+1):r;if(!o.length)throw new Error("cannot decode message ".concat(e.$typeName,' from JSON: "@type" is invalid'));const s=null===(i=n.registry)||void 0===i?void 0:i.getMessage(o);if(!s)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(r," is not in the type registry"));const a=m6(s);if(o.startsWith("google.protobuf.")&&Object.prototype.hasOwnProperty.call(t,"value"))t7(a,t.value,n);else{const e=Object.assign({},t);delete e["@type"],t7(a,e,n)}!function(e,t,n){var i;n||(n=s6(x9)),n.value=V6(e,t),n.typeUrl=(i=t.$typeName,"type.googleapis.com/".concat(i))}(a.desc,a.message,e)}(e.message,t,n),!0;case"google.protobuf.Timestamp":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(q4(t)));const n=t.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]{1,9}))?(?:Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: invalid RFC 3339 string"));const i=Date.parse(n[1]+"-"+n[2]+"-"+n[3]+"T"+n[4]+":"+n[5]+":"+n[6]+(n[8]?n[8]:"Z"));if(Number.isNaN(i))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: invalid RFC 3339 string"));if(i<Date.parse("0001-01-01T00:00:00Z")||i>Date.parse("9999-12-31T23:59:59Z"))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive"));e.seconds=FZ.parse(i/1e3),e.nanos=0,n[7]&&(e.nanos=parseInt("1"+n[7]+"0".repeat(9-n[7].length))-1e9)}(e.message,t),!0;case"google.protobuf.Duration":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(q4(t)));const n=t.match(/^(-?[0-9]+)(?:\.([0-9]+))?s/);if(null===n)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(q4(t)));const i=Number(n[1]);if(i>315576e6||i<-315576e6)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(q4(t)));if(e.seconds=FZ.parse(i),"string"!=typeof n[2])return;const r=n[2]+"0".repeat(9-n[2].length);e.nanos=parseInt(r),(i<0||Object.is(i,-0))&&(e.nanos=-e.nanos)}(e.message,t),!0;case"google.protobuf.FieldMask":return function(e,t){if("string"!=typeof t)throw new Error("cannot decode message ".concat(e.$typeName," from JSON: ").concat(q4(t)));""!==t&&(e.paths=t.split(",").map((function(t){if(A4(t).call(t,"_"))throw new Error("cannot decode message ".concat(e.$typeName," from JSON: path names must be lowerCamelCase"));const n=t.replace(/[A-Z]/g,(e=>"_"+e.toLowerCase()));return"_"===n[0]?n.substring(1):n})))}(e.message,t),!0;case"google.protobuf.Struct":return d7(e.message,t),!0;case"google.protobuf.Value":return l7(e.message,t),!0;case"google.protobuf.ListValue":return u7(e.message,t),!0;default:if(t6(e.desc)){const n=e.desc.fields[0];return null===t?e.clear(n):e.set(n,s7(n,t,!0)),!0}return!1}}(e,t,n))return;if(null==t||Array.isArray(t)||"object"!=typeof t)throw new Error("cannot decode ".concat(e.desc," from JSON: ").concat(q4(t)));const r=new Map,o=new Map;for(const t of e.desc.fields)o.set(t.name,t).set(t.jsonName,t);for(const a of Object.entries(t)){var s=l5(a,2);const t=s[0],c=s[1],d=o.get(t);if(d){if(d.oneof){if(null===c&&"scalar"==d.fieldKind)continue;const e=r.get(d.oneof);if(void 0!==e)throw new O4(d.oneof,"oneof set multiple times by ".concat(e.name," and ").concat(d.name));r.set(d.oneof,d)}n7(e,d,c,n)}else{let r;if(t.startsWith("[")&&t.endsWith("]")&&(r=null===(i=n.registry)||void 0===i?void 0:i.getExtension(t.substring(1,t.length-1)))&&r.extendee.typeName===e.desc.typeName){const t=l5(y8(r),3),i=t[0],o=t[1],s=t[2];n7(i,o,c,n),v8(e.message,r,s())}if(!r&&!n.ignoreUnknownFields)throw new Error("cannot decode ".concat(e.desc,' from JSON: key "').concat(t,'" is unknown'))}}}function n7(e,t,n,i){switch(t.fieldKind){case"scalar":!function(e,t,n){const i=s7(t,n,!1);i===o7?e.clear(t):e.set(t,i)}(e,t,n);break;case"enum":!function(e,t,n,i){const r=r7(t.enum,n,i.ignoreUnknownFields,!1);r===o7?e.clear(t):r!==i7&&e.set(t,r)}(e,t,n,i);break;case"message":!function(e,t,n,i){if(null===n&&"google.protobuf.Value"!=t.message.typeName)return void e.clear(t);const r=e.isSet(t)?e.get(t):m6(t.message);t7(r,n,i),e.set(t,r)}(e,t,n,i);break;case"list":!function(e,t,n){if(null===t)return;const i=e.field();if(!Array.isArray(t))throw new O4(i,"expected Array, got "+q4(t));for(const r of t){if(null===r)throw new O4(i,"list item must not be null");switch(i.listKind){case"message":const t=m6(i.message);t7(t,r,n),e.add(t);break;case"enum":const o=r7(i.enum,r,n.ignoreUnknownFields,!0);o!==i7&&e.add(o);break;case"scalar":e.add(s7(i,r,!0))}}}(e.get(t),n,i);break;case"map":!function(e,t,n){if(null===t)return;const i=e.field();if("object"!=typeof t||Array.isArray(t))throw new O4(i,"expected object, got "+q4(t));for(const o of Object.entries(t)){var r=l5(o,2);const t=r[0],s=r[1];if(null===s)throw new O4(i,"map value must not be null");let a;switch(i.mapKind){case"message":const e=m6(i.message);t7(e,s,n),a=e;break;case"enum":if(a=r7(i.enum,s,n.ignoreUnknownFields,!0),a===i7)return;break;case"scalar":a=s7(i,s,!0)}const c=a7(i.mapKey,t);e.set(c,a)}}(e.get(t),n,i)}}const i7=Symbol();function r7(e,t,n,i){if(null===t)return"google.protobuf.NullValue"==e.typeName?0:i?IZ(e)[0].number:o7;switch(typeof t){case"number":if(Number.isInteger(t))return t;break;case"string":const i=IZ(e).find((e=>e.name===t));if(void 0!==i)return i.number;if(n)return i7}throw new Error("cannot decode ".concat(e," from JSON: ").concat(q4(t)))}const o7=Symbol();function s7(e,t,n){if(null===t)return n?WZ(e.scalar,!1):o7;switch(e.scalar){case GZ.DOUBLE:case GZ.FLOAT:if("NaN"===t)return NaN;if("Infinity"===t)return Number.POSITIVE_INFINITY;if("-Infinity"===t)return Number.NEGATIVE_INFINITY;if("number"==typeof t){if(Number.isNaN(t))throw new O4(e,"unexpected NaN number");if(!Number.isFinite(t))throw new O4(e,"unexpected infinite number");break}if("string"==typeof t){if(""===t)break;if($8(t).call(t).length!==t.length)break;const e=Number(t);if(!Number.isFinite(e))break;return e}break;case GZ.INT32:case GZ.FIXED32:case GZ.SFIXED32:case GZ.SINT32:case GZ.UINT32:return c7(t);case GZ.BYTES:if("string"==typeof t){if(""===t)return new Uint8Array(0);try{return zq(t)}catch(t){const n=t instanceof Error?t.message:String(t);throw new O4(e,n)}}}return t}function a7(e,t){switch(e){case GZ.BOOL:switch(t){case"true":return!0;case"false":return!1}return t;case GZ.INT32:case GZ.FIXED32:case GZ.UINT32:case GZ.SFIXED32:case GZ.SINT32:return c7(t);default:return t}}function c7(e){if("string"==typeof e){if(""===e)return e;if($8(e).call(e).length!==e.length)return e;const t=Number(e);return Number.isNaN(t)?e:t}return e}function d7(e,t){if("object"!=typeof t||null==t||Array.isArray(t))throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(q4(t)));for(const i of Object.entries(t)){var n=l5(i,2);const t=n[0],r=n[1],o=s6(G9);l7(o,r),e.fields[t]=o}}function l7(e,t){switch(typeof t){case"number":e.kind={case:"numberValue",value:t};break;case"string":e.kind={case:"stringValue",value:t};break;case"boolean":e.kind={case:"boolValue",value:t};break;case"object":if(null===t)e.kind={case:"nullValue",value:K9.NULL_VALUE};else if(Array.isArray(t)){const n=s6(W9);u7(n,t),e.kind={case:"listValue",value:n}}else{const n=s6(j9);d7(n,t),e.kind={case:"structValue",value:n}}break;default:throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(q4(t)))}return e}function u7(e,t){if(!Array.isArray(t))throw new Error("cannot decode message ".concat(e.$typeName," from JSON ").concat(q4(t)));for(const n of t){const t=s6(G9);l7(t,n),IZ(e).push(t)}}function h7(e,t,n,i,r){let o,s=r.opid,a=r.mode,c=r.codec,d=r.hasChangeBGPAddress,l=void 0!==d&&d,u=r.ortc;t.multiIP&&t.multiIP.gateway_ip&&(o=JSON.stringify({vocs_ip:[t.multiIP.uni_lbs_ip],vos_ip:[t.multiIP.gateway_ip]}));const h="host"===t.role?"1":"audience"===t.role?"2":void 0,p={opid:s,unilbs:[{uri:22,detail:d8(d8(d8(d8(d8(d8(d8({},n?{11:n,22:n}:{}),o?{5:o}:{}),xP("USE_NEW_TOKEN")?{12:"1"}:{}),h?{17:h}:{}),t.apRequestDetail?{33:t.apRequestDetail}:{}),t.apRTM?{26:"RTM2"}:{}),t.apRequestDetailExtend),serviceIds:i}],uid:t.uid||0,signal:h8(e,t,{mode:a,codec:c,joinGatewayStartTime:Date.now(),hasChangeBGPAddress:l}),ortc:S8(u)},_=function(e,t,n){const i=m6(e);try{t7(i,t,function(e){return e?Object.assign(Object.assign({},e7),e):e7}(n))}catch(e){if((r=e)instanceof Error&&A4(w4).call(w4,r.name)&&"field"in r&&"function"==typeof r.field)throw new Error("cannot decode ".concat(e.field()," from JSON: ").concat(e.message),{cause:e});throw e}var r;return i.message}(Q9,p),E=V6(Q9,_),m=xP("ENABLE_AP_COMPRESS")?WW(E,{raw:!0}):E;return xP("ENABLE_SDP_ENDPOINT_LOG")&&SL.debug("[sdp-endpoint] request json",p," sdpEndpointRequestJson,length is ".concat(m.length)),m}function p7(e,t,n){var i,r,o;const s=xP("ENABLE_AP_COMPRESS")?HW(n,{raw:!0}):n,a=P9($9,new Uint8Array(s));xP("ENABLE_SDP_ENDPOINT_LOG")&&SL.debug("[sdp-endpoint] response json",function(e,t,n){return w8(m6(e,t),function(e){return e?Object.assign(Object.assign({},A8),e):A8}(n))}($9,a)," sdpEndpointResponseJson,length is ".concat(n.byteLength));const c=(null===(i=a.attributesResponse)||void 0===i?void 0:i.preSubSsrcs.map((e=>({a:e.a,a_rtx:e.aRtx,v:e.v,v_rtx:e.vRtx}))))||[],d=null===(r=a.attributesResponse)||void 0===r?void 0:r.subscribeAudioFilterTopN,l=null===(o=a.attributesResponse)||void 0===o?void 0:o.extensions,u=a.unilbsResponse[0].detail?Number(a.unilbsResponse[0].detail[8]):void 0;return{detail:a.detail,enter_ts:Number(a.enterTs),leave_ts:Number(a.leaveTs),opid:Number(a.opid),response_body:a.unilbsResponse.map((t=>({buffer:{cert:t.cert,cid:t.cid,cname:e.cname,code:t.code,detail:t.detail||{},edges_services:t.services.map((e=>({ip:e.ip,port:e.port,fingerprint:e.fingerprint,iceUfrag:e.ice[0],icePwd:e.ice[1]}))),flag:t.flag,uid:a.uid},uri:t.uri}))),signalResponse:{attributes:{userAttributes:d8(d8({preSubSsrcs:c},"number"==typeof d?{subscribeAudioFilterTopN:d}:{}),l)},rejoin_token:a.rejoinToken,return_vosip:!1,uid:e.stringUid?e.stringUid:a.uid,intUid:a.uid,vid:u,rtpCapabilities:T8(t.rtpCapabilities,a.addOrtc,a.delOrtc)}}}function _7(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function E7(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?_7(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_7(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let m7=0;function f7(e){const t=xP("TURN_DOMAINS");m7=(m7+1)%t.length;const n=t[m7]||"edge.agora.io";return e.match(/^[\.\:\d]+$/)?"".concat(e.replace(/[^\d]/g,"-"),".").concat(n):(SL.debug("Cannot recognized as ip address: ".concat(e,", use as host2")),e)}function g7(e){try{const t=xP("TURN_DOMAINS"),n=xP("GATEWAY_DOMAINS").concat(t).find((t=>Ui(e).call(e,t)));if(n){return e.split(".".concat(n))[0].replace(/-/g,".")}return e}catch(t){return SL.debug("serverUrlToIp error, fallback to url",e),e}}function S7(e,t){e.addresses||(e.addresses=[]);const n=function(e,t){if(xP("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return e.map((e=>{let t=e.ip,n=e.port;return{address:"".concat(t,":").concat(n)}}));const n=xP("GATEWAY_DOMAINS");let i=n[1]&&Ui(t).call(t,n[1])?1:0;return e.map((e=>{let t=e.domain_prefix,r=e.port,o=e.ip;if(t)return{address:"".concat(t,".").concat(n[i++%n.length],":").concat(r)};const s=/^[\.\:\d]+$/.test(o),a=s?"".concat(o.replace(/[^\d]/g,"-"),".").concat(n[i++%n.length],":").concat(r):"".concat(o,":").concat(r);return s||SL.debug("Cannot recognized as ip address: ".concat(o,", use as host3")),{ip:o,port:r,address:a}}))}(e.addresses,t),i=Array.isArray(e.detail)&&e.detail[18];if(i&&"string"==typeof i){const e=i.split(";");for(let t=0;t<e.length;t++){var r;const i=zS(r=e[t]).call(r);n[t]&&i&&(n[t].ip6=i)}}const o=e.detail&&e.detail.candidate;let s;if(o){const e=KC(o.split(":"),2),t=e[0],n=e[1];t&&n&&(s={port:Number(n),ip:t,address:"".concat(t,":").concat(n)})}return{gatewayAddrs:n,apGatewayAddress:s,uid:e.uid,cid:e.cid,cert:e.cert,vid:e.detail&&e.detail[8],uni_lbs_ip:e.detail&&e.detail[1],res:e,csIp:e.detail&&e.detail[502]}}function T7(e){return"number"==typeof e?e:e.exact||e.ideal||e.max||e.min||0}function R7(e){const t=e._encoderConfig;if(!t)return{};const n={resolution:t.width&&t.height?"".concat(T7(t.width),"x").concat(T7(t.height)):void 0,maxVideoBW:t.bitrateMax,minVideoBW:t.bitrateMin};return"number"==typeof t.frameRate?(n.maxFrameRate=t.frameRate,n.minFrameRate=t.frameRate):t.frameRate&&(n.maxFrameRate=t.frameRate.max||t.frameRate.ideal||t.frameRate.exact||t.frameRate.min,n.minFrameRate=t.frameRate.min||t.frameRate.ideal||t.frameRate.exact||t.frameRate.max),n}function v7(e){return e>=0&&e<.17?1:e>=.17&&e<.36?2:e>=.36&&e<.59?3:e>=.59&&e<=1?4:e>1?5:0}function y7(e,t){let n,i,r;switch(t){case YW.CHOOSE_SERVER:i=4096,r="choose server";break;case YW.CLOUD_PROXY:i=1048576,r="proxy";break;case YW.CLOUD_PROXY_5:i=4194304,r="proxy5";break;case YW.CLOUD_PROXY_FALLBACK:i=4194310,r="proxy fallback";break;default:throw new YL(wN.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:e.detail&&e.detail[502],retry:!1})}if(e.response_body.forEach((t=>{t.buffer&&t.buffer.flag===i&&(n={code:t.buffer.code,addresses:(t.buffer.edges_services||[]).map((e=>E7(E7({},e),{},{ticket:t.buffer.cert}))),server_ts:e.enter_ts,uid:t.buffer.uid,cid:t.buffer.cid,cname:t.buffer.cname,detail:E7(E7({},t.buffer.detail),e.detail),flag:t.buffer.flag,opid:e.opid,cert:t.buffer.cert,signalResponse:"signalResponse"in e?e.signalResponse:void 0})})),!n)throw new YL(wN.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:e.detail&&e.detail[502]});return n}async function C7(e,t){return await cp.all(e.addresses.map((async e=>({address:f7(e.ip),tcpport:e.port,udpport:e.port,username:t&&xP("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?t.toString():DP.username,password:t&&xP("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?await HN(t.toString()):DP.password}))))}function b7(e,t){const n=t.getMediaStreamTrack(!0).getSettings(),i=t.videoHeight||n.height,r=t.videoWidth||n.width;return i&&r?Math.max(Math.min(i,r)/Math.min(T7(e.height),T7(e.width)),1):(SL.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function I7(e){let t=e.candidateType,n=e.relayProtocol,i=e.type,r=e.address,o=e.port;const s={candidateType:t,relayProtocol:n,protocol:e.protocol};if("local-candidate"!==i){const e=r.split(".");e.length>=4&&(e[1]="*",e[2]="*"),s.address=e.join("."),s.port=o}return s}function A7(e){const t=e.split(":"),n=e.split(/[-.]/),i=Ui(e).call(e,"-")?"-":".";let r=e;return t.length>1?n.length>1?(n[1]="**",r=n[0]+i+"**:"+t[t.length-1]):r=t.length>2?t[0]+i+"**:"+t[t.length-1]:"**:"+t[t.length-1]:n.length>1&&(r=n[0]+i+"**"),r}function w7(e,t){return e.getTransceivers().find((e=>e.sender.track===t||e.receiver.track===t))}function O7(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:xP("SVC_MODE");if(xP("ENABLE_SVC"))return function(e){return e in gP}(e)?e:gP.L1T3}const N7={[UF.VIDEO]:[{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"},{key:"video-orientation",extensionName:"urn:3gpp:video-orientation"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"playout-delay",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},{key:"video-content-type",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type"},{key:"color-space",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/color-space"},{key:"video-timing",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing"}],[UF.AUDIO]:[{key:"ssrc-audio-level",extensionName:"urn:ietf:params:rtp-hdrext:ssrc-audio-level"},{key:"draft-holmer-rmcat-transport-wide-cc-extensions-01",extensionName:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"},{key:"abs-send-time",extensionName:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"}]};function D7(e){e.send&&(k7(UF.VIDEO,e.send.videoExtensions),k7(UF.AUDIO,e.send.audioExtensions)),e.recv&&(k7(UF.VIDEO,e.recv.videoExtensions),k7(UF.AUDIO,e.recv.audioExtensions)),e.sendrecv&&(k7(UF.VIDEO,e.sendrecv.videoExtensions),k7(UF.AUDIO,e.sendrecv.audioExtensions))}function P7(e,t){e.send&&(L7(UF.VIDEO,e.send.videoExtensions,t.send.videoExtensions),L7(UF.AUDIO,e.send.audioExtensions,t.send.audioExtensions)),e.recv&&(L7(UF.VIDEO,e.recv.videoExtensions,t.recv.videoExtensions),L7(UF.AUDIO,e.recv.audioExtensions,t.recv.audioExtensions))}function L7(e,t,n){t.forEach((t=>{var i;const r=N7[e].find((e=>{var n;let i=e.key;return Ui(n=t.extensionName).call(n,i)}));if(!r)return;const o=n.find((e=>{let t=e.extensionName;return Ui(t).call(t,r.key)}));o&&Ui(i=o.extensionName).call(i,"gdpr_forbidden")&&(t.extensionName=o.extensionName)}))}function k7(e,t){t.forEach((t=>{var n;const i=N7[e].find((e=>{var n;let i=e.key;return Ui(n=t.extensionName).call(n,i)}));Ui(n=t.extensionName).call(n,"gdpr_forbidden")&&i&&(t.extensionName=i.extensionName)}))}function M7(e){return"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"===e||Ui(e).call(e,"abs-send-time")}function U7(e){return"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"===e||Ui(e).call(e,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}function V7(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function x7(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?V7(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):V7(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function F7(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3?arguments[3]:void 0;const r=t.filterRTX,o=t.filterVideoFec,s=t.filterAudioFec,a=t.filterAudioCodec,c=t.filterVideoCodec,d=t.unsupportedVideoUplinkCodec,l=t.unsupportedVideoDownlinkCodec,u=n.useXR;let h=[],p=[],_=[],E=[],m=!1,f=!1;if(zP(e).mediaDescriptions.forEach((e=>{i&&i!==e.attributes.direction||("video"!==e.media.mediaType||m||(p=e.attributes.payloads,E=e.attributes.extmaps,m=!0),"audio"!==e.media.mediaType||f||(h=e.attributes.payloads,_=e.attributes.extmaps,f=!0))})),!E||0===p.length)throw new Error("Cannot get video capabilities from SDP.");if(!_||0===h.length)throw new Error("Cannot get audio capabilities from SDP.");if(p.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),h.forEach((e=>{var t;null!==(t=e.rtpMap)&&void 0!==t&&t.clockRate&&(e.rtpMap.clockRate=parseInt(e.rtpMap.clockRate)),u&&e.rtcpFeedbacks.push({type:"rrtr"})})),r&&(h=h.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})),p=p.filter((e=>{var t;return"rtx"!==(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())}))),o){const e=p.filter((e=>{var t;return/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")})),t=oee(e,p).map((e=>e.payloadType)),n=[...e.map((e=>e.payloadType)),...t];p=p.filter((e=>!Ui(n).call(n,e.payloadType)))}if(s&&(h=h.filter((e=>{var t;return!/(red)|(ulpfec)|(flexfec)/i.test((null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName)||"")}))),a&&(null==a?void 0:a.length)>0&&(h=h.filter((e=>{var t;return Ui(a).call(a,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}))),c&&(null==c?void 0:c.length)>0){const e=p.filter((e=>{var t;return Ui(c).call(c,(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())||"")}));p=e.concat(r?[]:oee(e,p))}const g=xP("UNSUPPORTED_VIDEO_CODEC");if(g&&g.length>0){const e=p.filter((e=>e.rtpMap&&Ui(g).call(g,e.rtpMap.encodingName.toLowerCase()))),t=oee(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Ui(n).call(n,e.payloadType))),SL.debug("unsupportedVideoCodec: ".concat(g,", toBeRemoved: ").concat(n))}if(d&&d.length>0&&"sendonly"===i){const e=p.filter((e=>e.rtpMap&&Ui(d).call(d,e.rtpMap.encodingName.toLowerCase()))),t=oee(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Ui(n).call(n,e.payloadType))),SL.debug("unsupportedVideoUplinkCodec: ".concat(d,", toBeRemoved: ").concat(n))}if(l&&l.length>0&&"recvonly"===i){const e=p.filter((e=>e.rtpMap&&Ui(l).call(l,e.rtpMap.encodingName.toLowerCase()))),t=oee(e,p),n=e.concat(t).map((e=>e.payloadType));p=p.filter((e=>!Ui(n).call(n,e.payloadType))),SL.debug("unsupportedVideoDownlinkCodec: ".concat(l,", toBeRemoved: ").concat(n))}return{audioCodecs:h,videoCodecs:p,audioExtensions:_,videoExtensions:E}}function B7(e){const t=zP(e);let n,i;for(const e of t.mediaDescriptions){if(!n){const t=e.attributes.iceUfrag,i=e.attributes.icePwd;if(!t||!i)throw new Error("Cannot get iceUfrag or icePwd from SDP.");n={iceUfrag:t,icePwd:i}}if(!i){const t=e.attributes.fingerprints;t.length>0&&(i={fingerprints:t})}}if(!i&&t.attributes.fingerprints.length>0&&(i={fingerprints:t.attributes.fingerprints}),!i||!n)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:n,dtlsParameters:i}}function j7(e,t){const n=[],i=e.attributes.ssrcGroups.filter((e=>"FID"===e.semantic)),r=e.attributes.ssrcGroups.find((e=>"SIM"===e.semantic)),o=e.attributes.ssrcs;if(r)r.ssrcIds.forEach((e=>{var r;const o=null===(r=i.find((t=>t.ssrcIds[0]===e)))||void 0===r?void 0:r.ssrcIds[1];n.push({ssrcId:e,rtx:t?o:void 0})}));else if(i.length>0){const e=i[0].ssrcIds[0],r=i[0].ssrcIds[1];n.push({ssrcId:e,rtx:t?r:void 0})}else{if(0===o.length)throw new Error("No ssrcs found on local media description.");n.push({ssrcId:o[0].ssrcId})}return n}function G7(e,t,n){const i=e.cname;let r=[];t&&(r=K7(t)),0===r.length&&(r=e.iceParameters.candidates.map((e=>({foundation:e.foundation,componentId:"1",transport:e.protocol,priority:e.priority.toString(),connectionAddress:e.ip,port:e.port.toString(),type:e.type,extension:{}}))),SL.debug("Using candidates from gateway."));const o={fingerprints:e.dtlsParameters.fingerprints.map((e=>({hashFunction:e.algorithm,fingerprint:e.fingerprint})))},s={iceUfrag:e.iceParameters.iceUfrag,icePwd:e.iceParameters.icePwd};let a;switch(e.dtlsParameters.role){case"server":a="passive";break;case"client":a="active";break;case"auto":a="actpass"}return{dtlsParameters:o,iceParameters:s,candidates:r,rtpCapabilities:nee(e.rtpCapabilities),setup:a,cname:i,preSSRCs:W7(n)}}function W7(e){const t=[];return Array.isArray(e)&&e.length>0&&e.forEach((e=>{t.push({kind:UF.VIDEO,ssrcMsg:[{ssrcId:e.v,rtx:e.v_rtx}],mslabel:"".concat(e.v,"_").concat(e.a)},{kind:UF.AUDIO,ssrcMsg:[{ssrcId:e.a}],mslabel:"".concat(e.v,"_").concat(e.a)})})),t}function K7(e){let t=[];return e.ip&&"number"==typeof e.port&&(t=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip,port:e.port.toString(),type:"host",extension:{}}],SL.debug("Using remote candidate from AP ".concat(A7(e.ip),":").concat(e.port)),e.ip6&&(t.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:e.ip6,port:e.port.toString(),type:"host",extension:{}}),SL.debug("Using IPV6 remote candidate from AP ".concat(A7(e.ip6),":").concat(e.port)))),t}function H7(e,t,n){const i=[],r=[];return e.forEach((e=>{let o=e.ssrcId,s=e.rtx;const a=kD(8,"track-"),c={ssrcId:o,attributes:x7({label:a,mslabel:n=n||kD(10,""),msid:"".concat(n," ").concat(a)},t&&{cname:t})};if(i.push(c),void 0!==s){const e={ssrcId:s,attributes:x7({label:a,mslabel:n,msid:"".concat(n," ").concat(a)},t&&{cname:t})};i.push(e),r.push({semantic:"FID",ssrcIds:[o,s]})}})),e.length>1&&r.push({semantic:"SIM",ssrcIds:e.map((e=>e.ssrcId))}),{ssrcs:i,ssrcGroups:r}}function Y7(e,t){t instanceof IU&&e.attributes.payloads.forEach((e=>{var n;const i=null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase();if(!i||-1===["opus","pcmu","pcma","g722"].indexOf(i))return;e.fmtp||(e.fmtp={parameters:{}}),"opus"===i&&"number"==typeof xP("OPUS_PTIME")?e.fmtp.parameters.ptime=xP("OPUS_PTIME"):e.fmtp.parameters.minptime="10",e.fmtp.parameters.useinbandfec="1";const r=t._encoderConfig;r&&("pcmu"!==i&&"pcma"!==i&&"g722"!==i&&(r.bitrate&&!$O()&&(e.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*r.bitrate))),r.sampleRate&&(e.fmtp.parameters.maxplaybackrate="".concat(r.sampleRate),e.fmtp.parameters["sprop-maxcapturerate"]="".concat(r.sampleRate)),r.stereo&&(e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1")),t instanceof AU&&"opus"===i&&t._config.DTX&&(e.fmtp.parameters.usedtx="1"))}))}function X7(e){const t=e.attributes.unrecognized.findIndex((e=>"x-google-flag"===e.attField&&"conference"===e.attValue));-1!==t&&e.attributes.unrecognized.splice(t,1)}function J7(e,t){var n;if(e.attributes.payloads.forEach((e=>{var t;"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())&&e.fmtp&&e.fmtp.parameters&&xP("ENABLE_UP_SPS_PPS")&&(e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),!(t instanceof TV&&t._encoderConfig&&-1===t._hints.indexOf(Rk.SCREEN_TRACK)))return;const i=t._encoderConfig;JL().supportMinBitrate&&i.bitrateMin&&e.attributes.payloads.forEach((e=>{var t,n;Ui(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-min-bitrate"]="".concat(i.bitrateMin))})),JL().supportMinBitrate&&!Ui(n=t._hints).call(n,Rk.LOW_STREAM)&&i.bitrateMax&&e.attributes.payloads.forEach((e=>{var t,n;Ui(t=["h264","h265","vp8","vp9","av1"]).call(t,(null===(n=e.rtpMap)||void 0===n?void 0:n.encodingName.toLowerCase())||"")&&(e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["x-google-start-bitrate"]="".concat(xP("X_GOOGLE_START_BITRATE")||Math.floor(i.bitrateMax)))}))}function z7(e){if("video"!==e.media.mediaType)return;const t=GO();if(t.name!==xO.SAFARI&&t.os!==VO.IOS)return;const n=e.attributes.extmaps.findIndex((e=>/video-orientation/g.test(e.extensionName)));-1!==n&&e.attributes.extmaps.splice(n,1)}function Z7(e,t,n){if(!t)return;let i,r;if("video"===e.media.mediaType?(i=n.videoExtensions,r=n.videoCodecs):(i=n.audioExtensions,r=n.audioCodecs),!0===t.twcc){const t=i.find((e=>U7(e.extensionName)));if(t){const n=t.extensionName;e.attributes.extmaps.find((e=>U7(e.extensionName)))||e.attributes.extmaps.push({entry:t.entry,extensionName:n});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"transport-cc"===e.type))||e.rtcpFeedbacks.push({type:"transport-cc"})}))}}else if(!1===t.twcc){const t=e.attributes.extmaps.findIndex((e=>U7(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}if(!0===t.remb){const t=i.find((e=>M7(e.extensionName)));if(t){const n=t.extensionName;e.attributes.extmaps.find((e=>e.extensionName===n))||e.attributes.extmaps.push({entry:t.entry,extensionName:n});const i=function(e,t){return t.filter((t=>!!e.find((e=>e.payloadType===t.payloadType&&!!e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))))))}(r,e.attributes.payloads);i.forEach((e=>{e.rtcpFeedbacks.find((e=>"goog-remb"===e.type))||e.rtcpFeedbacks.push({type:"goog-remb"})}))}}else if(!1===t.remb){const t=e.attributes.extmaps.findIndex((e=>M7(e.extensionName)));-1!==t&&e.attributes.extmaps.splice(t,1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"goog-remb"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}}function q7(e,t,n){if($O())return;if("video"!==e.media.mediaType)return;if(!(t instanceof TV))return;if("vp9"!==n&&"vp8"!==n)return;if("vp8"===n&&!xP("SIMULCAST"))return;if("vp9"===n&&xP("ENABLE_SVC"))return;if(void 0===t._scalabilityMode||t._scalabilityMode.numSpatialLayers<=1)return;const i="vp8"===n?2:t._scalabilityMode.numSpatialLayers,r=e.attributes.ssrcs[0],o=e.attributes.ssrcGroups.find((e=>"FID"===e.semantic&&e.ssrcIds[0]===r.ssrcId)),s={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let t=1;t<i;t++)e.attributes.ssrcs.push({ssrcId:r.ssrcId+t,attributes:vD(r.attributes)}),s.ssrcIds.push(r.ssrcId+t),o&&(e.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+t,attributes:vD(r.attributes)}),e.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+t,o.ssrcIds[1]+t]}));e.attributes.ssrcGroups.unshift(s)}async function Q7(){try{const e=new RTCPeerConnection;e.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:gP.L1T3}]});const t=await e.createOffer();if(!t.sdp)return void e.close();const n=zP(t.sdp).mediaDescriptions[0];if(!n)return;const i=n.attributes.extmaps.find((e=>"https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"===e.extensionName));return e.close(),i}catch(e){return}}async function $7(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=new RTCPeerConnection;n.addTransceiver("video",{direction:"sendonly"}),n.addTransceiver("audio",{direction:"sendonly"}),n.addTransceiver("video",{direction:"recvonly"}),n.addTransceiver("audio",{direction:"recvonly"});const i=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0;const i=F7(n,e,t,"sendonly"),r=F7(n,e,t,"recvonly"),o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},s={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},a={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(tee(i,r,"videoExtensions",o,s,a),tee(i,r,"videoCodecs",o,s,a),tee(i,r,"audioExtensions",o,s,a),tee(i,r,"audioCodecs",o,s,a),xP("RAISE_H264_BASELINE_PRIORITY")){const e=[],t=[];if(a.videoCodecs.forEach(((n,i)=>{var r;if("h264"===(null===(r=n.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){var o,s;const r=a.videoCodecs[i+1],c=r&&uee(n,r),d=null===(o=n.fmtp)||void 0===o?void 0:o.parameters["profile-level-id"],l=null===(s=n.fmtp)||void 0===s?void 0:s.parameters["packetization-mode"];!d||d!==xP("FIRST_H264_PROFILE_LEVEL_ID")||xP("FIRST_PACKETIZATION_MODE")&&l!==xP("FIRST_PACKETIZATION_MODE")?c?t.push([n,r]):t.push([n]):c?e.push([n,r]):e.push([n])}})),e.length>0&&t.length>0){SL.debug("raising H264 baseline profile priority"),a.videoCodecs.forEach(((n,i)=>{var r;if("h264"===(null===(r=n.rtpMap)||void 0===r?void 0:r.encodingName.toLocaleLowerCase())){const r=uee(n,a.videoCodecs[i+1]),o=e.shift()||t.shift()||[];o.length>0&&(r?a.videoCodecs.splice(i,2,...o):a.videoCodecs.splice(i,1,...o))}}));const n=s.videoCodecs.filter((e=>{var t,n;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(n=e.fmtp)||void 0===n?void 0:n.parameters["profile-level-id"])!==xP("FIRST_H264_PROFILE_LEVEL_ID")}));if(n.length>0){const e=oee(n,s.videoCodecs).map((e=>e.payloadType)),t=[...n.map((e=>e.payloadType)),...e];s.videoCodecs=s.videoCodecs.filter((e=>!Ui(t).call(t,e.payloadType)))}xP("FILTER_SEND_H264_BASELINE")&&(o.videoCodecs=o.videoCodecs.filter((e=>{var t,n;return!("h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLocaleLowerCase())&&(null===(n=e.fmtp)||void 0===n?void 0:n.parameters["profile-level-id"])!==xP("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:o,recv:s,sendrecv:a}}return{send:o,recv:s,sendrecv:a}}(e,t,(await n.createOffer()).sdp),r=i.send,o=i.recv,s=i.sendrecv;try{n.close()}catch(e){}return{send:r,recv:o,sendrecv:s}}function eee(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=F7(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"recvonly"),n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(tee(e,t,"videoExtensions",n,i,r),tee(e,t,"videoCodecs",n,i,r),tee(e,t,"audioExtensions",n,i,r),tee(e,t,"audioCodecs",n,i,r),xP("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t<e){SL.debug("raising H264 baseline profile priority");const n=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,n)}-1!==t&&(i.videoCodecs=i.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:n,recv:i,sendrecv:r}}function tee(e,t,n,i,r,o){if("videoExtensions"===n||"audioExtensions"===n){const s=[];return e[n].forEach((e=>{t[n].some(((t,n)=>{if(e.entry===t.entry&&e.extensionName===t.extensionName)return s.push(n),!0}))?o[n].push(e):i[n].push(e)})),void t[n].forEach(((e,t)=>{-1===s.indexOf(t)&&r[n].push(e)}))}if("videoCodecs"===n||"audioCodecs"===n){const s=[];return e[n].forEach((e=>{t[n].some(((t,n)=>{if(e.payloadType===t.payloadType&&JSON.stringify(e)===JSON.stringify(t))return s.push(n),!0}))?o[n].push(e):i[n].push(e)})),void t[n].forEach(((e,t)=>{-1===s.indexOf(t)&&r[n].push(e)}))}}function nee(e){const t=e.send,n=e.recv,i=e.sendrecv;if(!i){if(!t||!n)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:t,recv:n}}let r,o;return t?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...t.audioCodecs,...i.audioCodecs],r.videoCodecs=[...t.videoCodecs,...i.videoCodecs],r.audioExtensions=[...t.audioExtensions,...i.audioExtensions],r.videoExtensions=[...t.videoExtensions,...i.videoExtensions]):r=vD(i),n?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...n.audioCodecs,...i.audioCodecs],o.videoCodecs=[...n.videoCodecs,...i.videoCodecs],o.audioExtensions=[...n.audioExtensions,...i.audioExtensions],o.videoExtensions=[...n.videoExtensions,...i.videoExtensions]):o=vD(i),{send:r,recv:o}}function iee(e){if("audio"!==e.media.mediaType)return;e.attributes.payloads.filter((e=>{var t;return"opus"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"}))}function ree(e,t,n,i){let r=[];if(e===UF.VIDEO){if(xP("H264_PROFILE_LEVEL_ID")&&"h264"===i&&(r=t.videoCodecs.filter((e=>{var t;return Ui(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,i)&&e&&e.fmtp&&e.fmtp.parameters["profile-level-id"]===xP("H264_PROFILE_LEVEL_ID")}))),!Array.isArray(r)||0===r.length){let e=[];const o=[],s=[],a=[];if(n.videoCodecs.forEach((t=>{const n=t.rtpMap&&t.rtpMap.encodingName.toLowerCase()||"";Ui(n).call(n,i)?e.push(t):Ui(n).call(n,"vp9")?o.push(t):Ui(n).call(n,"vp8")?s.push(t):Ui(n).call(n,"h264")&&a.push(t)})),0===e.length){let t="";0!==o.length?(e=o,t="vp9"):0!==s.length?(e=s,t="vp8"):0!==a.length&&(e=a,t="h264"),SL.warning("codec ".concat(i," not included in rtpCapabilities, fallback to default payloads: ").concat(t))}0!==e.length&&(r=t.videoCodecs.filter((t=>e.some((e=>e.payloadType===t.payloadType)))))}if(0===r.length&&(SL.warning("codec ".concat(i," not included in rtpCapabilities, fallback to default payloads: ").concat(t.videoCodecs[0].rtpMap&&t.videoCodecs[0].rtpMap.encodingName)),r=t.videoCodecs),xP("USE_PUB_RTX")||xP("USE_SUB_RTX")){const e=oee(r,t.videoCodecs);r=[...r,...e]}}else{r=t.audioCodecs.filter((e=>{var t;return Ui(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,i)}));const e=t.audioCodecs.filter((e=>{var t;return Ui(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"red")}));0===r.length&&(SL.warning("codec ".concat(i," not included in rtpCapabilities, fallback to opus")),r=t.audioCodecs.filter((e=>{var t;return Ui(t=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(t,"opus")}))),xP("ENABLE_AUDIO_RED")&&0!==e.length&&(r=[...e,...r])}return r}function oee(e,t){const n=e.map((e=>e.payloadType.toString()));return t.filter((e=>e.rtpMap&&"rtx"===e.rtpMap.encodingName&&e.fmtp&&e.fmtp.parameters.apt&&Ui(n).call(n,e.fmtp&&e.fmtp.parameters.apt)))}async function see(e,t,n){const i=t.toString(),r=cee(i,"offer","remote","exchangeSDP");await e.setRemoteDescription({type:"offer",sdp:i});const o=await e.createAnswer();if(!o.sdp)throw new Error("cannot get answer sdp");let s=o.sdp;s=aee(s,n||{}),null==r||r(s||""),await e.setLocalDescription({type:"answer",sdp:s})}function aee(e,t,n){if(xP("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=zP(e),r=t.useXR;return i.mediaDescriptions.forEach((e=>{var t;e.attributes.mid&&(Array.isArray(n)&&!Ui(n).call(n,e.attributes.mid)||("audio"===e.media.mediaType&&iee(e),"video"===e.media.mediaType&&function(e){if("video"!==e.media.mediaType)return;if(!xP("ENABLE_DOWN_SPS_PPS"))return;e.attributes.payloads.filter((e=>{var t;return"h264"===(null===(t=e.rtpMap)||void 0===t?void 0:t.encodingName.toLowerCase())})).forEach((e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1"}))}(e),r&&Ui(t=["audio","video"]).call(t,e.media.mediaType)&&e.attributes.payloads.forEach((e=>{-1===e.rtcpFeedbacks.findIndex((e=>"rrtr"===e.type))&&e.rtcpFeedbacks.push({type:"rrtr"})}))))})),ZP(i)}function cee(e,t,n,i){if(xP("SDP_LOGGING"))return SL.upload("exchanging ".concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{cee(e,"answer","local"===n?"remote":"local",i)}:void 0}async function dee(e,t,n){try{var i;if(!JL().supportSetRtpSenderParameters)return;if(!function(e){return"vp9"===e||"av1"===e}(e)||!xP("ENABLE_SVC"))return;const r={},o={},s=t.getParameters(),a=null===(i=s.encodings)||void 0===i?void 0:i[0];o.scalabilityMode=O7(n),a&&Object.assign(a,o),Object.assign(s,r),await t.setParameters(s),SL.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(s.encodings)))}catch(e){SL.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",e)}}function lee(e){const t=xP("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(t)&&t.length>0)&&t.some((t=>Ui(e).call(e,t)))}function uee(e,t){try{var n;return(null===(n=e.fmtp)||void 0===n?void 0:n.parameters.apt)===t.payloadType.toString()}catch(e){return!1}}var hee,pee;const _ee={};function Eee(e){(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])&&SL.debug("install service ".concat(e.name)),_ee[e.name]=e}function mee(e){const t=_ee[e];if(!t)throw new ON(wN.INVALID_OPERATION,"".concat(e," not found, please use AgoraRTC.use(").concat(e,"Service) to load it first"));return t}function fee(e){return!!_ee[e]}function gee(e,t){return mee("DataStream").create(e,t)}function See(){return mee("InterceptFrame").create()}const Tee=null!==(pee=(hee=Ub).__aiClientControllerCallbacks)&&void 0!==pee?pee:hee.__aiClientControllerCallbacks={onMute:null,onUnmute:null,onPlay:null,onStop:null},Ree={registerCallbacks(e){Tee.onMute=e.onMute,Tee.onUnmute=e.onUnmute,Tee.onPlay=e.onPlay,Tee.onStop=e.onStop},unregisterCallbacks(){Tee.onMute=null,Tee.onUnmute=null,Tee.onPlay=null,Tee.onStop=null},mute(){var e;null===(e=Tee.onMute)||void 0===e||e.call(Tee)},unmute(){var e;null===(e=Tee.onUnmute)||void 0===e||e.call(Tee)},play(){var e;null===(e=Tee.onPlay)||void 0===e||e.call(Tee)},stop(){var e;null===(e=Tee.onStop)||void 0===e||e.call(Tee)}};function vee(e,t){return!(e.length<4||e.length>256)&&!(t.length<22||t.length>256)}function yee(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Cee(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?yee(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yee(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const bee=new Map;class Iee extends YN{get state(){return this._state}set state(e){if(e===this._state)return;const t=this._state;this._state=e,"DISCONNECTED"===e&&this._disconnectedReason?this.emit(bF.CONNECTION_STATE_CHANGE,e,t,this._disconnectedReason):this.emit(bF.CONNECTION_STATE_CHANGE,e,t)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){SL.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,t){var n,i,r;super(),zA(this,"store",void 0),zA(this,"joinInfo",void 0),zA(this,"key",void 0),zA(this,"ntpOffset",0),zA(this,"usingProxy",!1),zA(this,"signal",void 0),zA(this,"role",void 0),zA(this,"isPreallocation",void 0),zA(this,"isPreSub",void 0),zA(this,"inChannelInfo",{joinAt:null,duration:0}),zA(this,"spec",void 0),zA(this,"_state","DISCONNECTED"),zA(this,"_statsCollector",void 0),zA(this,"_disconnectedReason",void 0),zA(this,"isSignalRecover",!1),zA(this,"hasChangeBGPAddress",!1),zA(this,"trafficStatsInterval",void 0),zA(this,"networkQualityInterval",void 0),zA(this,"_joinGatewayStartTime",0),zA(this,"_signalTimeout",!1),zA(this,"_clientRoleOptions",void 0),zA(this,"_isProactiveJoin",!1),zA(this,"_sdpEndpointJoin",void 0),this.store=e,this.spec=t,this.signal=this.store.useP2P?(n={spec:Cee(Cee({},t),{},{retryConfig:t.websocketRetryConfig}),store:e},null===(i=(r=mee("P2PChannel")).createSubmodule)||void 0===i?void 0:i.call(r,n)):this.store.useDcSignal?function(e){return mee("DataChannelSignal").create(e)}({spec:Cee(Cee({},t),{},{retryConfig:t.websocketRetryConfig}),store:e}):new SB(Cee(Cee({},t),{},{retryConfig:t.websocketRetryConfig}),e),this._statsCollector=t.statsCollector,this.role=t.role||"audience",this._clientRoleOptions=t.clientRoleOptions,this.handleSignalEvents()}setUsingProxy(e){this.usingProxy=e}join(e,t){return this.joinInternal(e,t)}joinWithSDPEndpoint(e,t,n){return this.joinInternal(e,t,n)}async joinInternal(e,t,n){if(this.store.useDcSignal){let t=!1;const n=e.apResponse.addresses[0],i=n.iceUfrag||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert),r=n.icePwd||"".concat(e.apResponse.cid,"_").concat(e.apResponse.cert);"disabled"!==e.cloudProxyServer?(SL.debug("[".concat(this.store.clientId,"] Dc is not supported, because cloudProxyServer are not supported (").concat(e.cloudProxyServer,")")),t=!0):vee(i,r)?e.apResponse.addresses.some((e=>e.fingerprint))||xP("FINGERPRINT")||(SL.debug("[".concat(this.store.clientId,"] Dc is not supported, because fingerprint does not exist")),t=!0):(SL.debug("[".concat(this.store.clientId,"] Dc is not supported, because ticket length is incorrect, it has to be between 22 and 255")),t=!0),t&&this.resetSignal()}this.store.joinGatewayStart(),"disabled"!==e.cloudProxyServer&&(this.hasChangeBGPAddress=!0);const i=Date.now();let r=bee.get(e.cname);if(r||(r=new Map,bee.set(e.cname,r)),this._isProactiveJoin=!0,r.has(e.uid)){const t=new YL(wN.UID_CONFLICT);throw HL.joinGateway(e.sid,{lts:i,succ:!1,ec:t.code,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!e.proxyServer||this.usingProxy,signalChannel:this.store.useDcSignal?"1":"0",preload:e.preload}),t}r.set(e.uid,!0),this.joinInfo=e,this.key=t;const o=n?{attempt:n,startAt:i,initialRole:n.initialRole,roleReplaySent:!1,timingReported:!1}:void 0;this._sdpEndpointJoin=o,o&&n.channelReady.then((e=>{var t;let n=e.proof;this._sdpEndpointJoin===o&&(null!==(t=o.iceConnectedAt)&&void 0!==t||(o.iceConnectedAt=n.at),this.reportSDPEndpointJoinTiming())}));let s=0;this.joinGatewayStartTime=i;const a=e.proxyServer,c=this.store.useDcSignal?"datachannel":"websocket";try{SL.debug("[".concat(this.store.clientId,"] use ").concat(c," ").concat(o?"with sdpednpoint":""," join uid ").concat(s));const t=e.gatewayAddrs.map((t=>{const n=KC(t.address.split(":"),2),i={host:n[0],port:n[1]};return e.proxyServer&&(i.proxy=e.proxyServer),i}));let i;this.store.useDcSignal?i=await this.signal.init(e.apResponse.addresses):o?(this.handlePrePc(n),i=await this.initSDPEndpointSignal(t,o)):(function(e){return!(ZL()||xP("USE_NEW_TOKEN")||!xP("ENABLE_PREALLOC_PC")&&(null==e||!e.autoSubscribe||xP("FORCE_DISABLE_AUTO_SUB")))}(this.store)&&this.handlePrePc(),i=await this.signal.init(t)),s=i.uid,SL.debug("[".concat(this.store.clientId,"] ").concat(c," join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(t){var d;if(t.code===wN.INIT_DATACHANNEL_TIMEOUT&&"AgoraRTCSignal"===this.signal.__name__);else HL.joinGateway(e.sid,{lts:i,succ:!1,ec:(null===(d=t.data)||void 0===d?void 0:d.desc)||t.code,errorMsg:t.message,addr:this.signal.reportUrl,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!a||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:e.preload});if(t&&t.code===wN.INIT_DATACHANNEL_TIMEOUT)throw SL.warning("[".concat(this.store.clientId,"] User join datachannel failed"),t.toString()),this.resetSignal(),t;throw SL.error("[".concat(this.store.clientId,"] User join failed"),t.toString()),r.delete(e.uid),this.signal.close(),t}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),SL.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval((()=>{this.updateTrafficStats().catch((e=>{SL.warning("[".concat(this.store.clientId,"] get traffic stats error"),e.toString())}))}),3e3),this.networkQualityInterval=window.setInterval((()=>{navigator&&void 0!==navigator.onLine&&!navigator.onLine?this.emit(bF.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(bF.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):"CONNECTED"===this.state&&this._statsCollector.trafficStats?this.emit(bF.NETWORK_QUALITY,{uplinkNetworkQuality:v7(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:v7(this._statsCollector.trafficStats.B_dnq)}):this.emit(bF.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})}),2e3),this.store.joinGatewayEnd(),s}async initSDPEndpointSignal(e,t){var n;const i=this.signal.init(e,{queryReconnectingWhenConnecting:!0}).then((e=>{var n,i;const r=null!==(n=this.store.keyMetrics.joinRep)&&void 0!==n?n:Date.now();return null!==(i=t.joinResponseAt)&&void 0!==i||(t.joinResponseAt=r),this.reportSDPEndpointJoinTiming(),{kind:"joinres",response:e,at:r}})),r=xP("ENABLE_ICE_EARLY_JOIN")?await cp.race([i,t.attempt.channelReady]):await i;var o;return"ice"===r.kind?this._sdpEndpointJoin!==t?(await i).response:(null!==(o=t.iceConnectedAt)&&void 0!==o||(t.iceConnectedAt=r.proof.at),t.winner={type:"ice",at:r.proof.at},this.reportSDPEndpointJoinTiming(),t.attempt.preJoinResponse):(null!==(n=t.joinResponseAt)&&void 0!==n||(t.joinResponseAt=r.at),t.winner={type:"joinres",at:r.at},this.reportSDPEndpointJoinTiming(),r.response)}async leave(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1?arguments[1]:void 0;if("DISCONNECTED"!==this.state){t!==$N.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==nF.CONNECTED||await function(e,t){return t===1/0?e:cp.race([e,PD(t)])}(this.signal.request(rF.LEAVE,void 0,!0),3e3)}catch(e){SL.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),e)}this.signal.close(t),t!==$N.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}}async publish(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const i={state:"offer",p2p_id:this.store.p2pId,ortc:t,mode:this.spec.mode,extend:xP("PUB_EXTEND"),twcc:!!xP("PUBLISH_TWCC"),rtx:!!xP("USE_PUB_RTX")};try{return(await this.signal.request(rF.PUBLISH,i,!0))._message}catch(i){if(n&&i.data&&i.data.code===tF.ERR_PUBLISH_REQUEST_INVALID)return SL.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),i.toString()),await this.tryUnpubBeforeRepub(e,t),this.publish(e,t,!1);throw i}}async publishDataChannel(e,t,n){var i;if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={stream_id:t.streamId,ordered:t.ordered?1:0,max_retrans_times:null!==(i=t.maxRetransmits)&&void 0!==i?i:10,channel_id:t.channelId,metadata:t.metadata};try{await this.signal.request(rF.PUBLISH_DATASTREAM,r,!0)}catch(i){if(n&&i.data&&i.data.code===tF.ERR_PUBLISH_REQUEST_INVALID)return SL.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),i.toString()),await this.tryUnpubDataChannelBeforeRepub(e,t),this.publishDataChannel(e,t,!1);throw i}}async unpublish(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await this.signal.request(rF.UNPUBLISH,{stream_id:t,ortc:e},!0)}catch(e){SL.warning("[".concat(this.store.clientId,"] unpublish warning: "),e)}}async unpublishDataChannel(e){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await cp.all(e.map((e=>this.signal.request(rF.UNPUBLISH_DATASTREAM,{channel_id:e},!0))))}catch(e){SL.warning("unpublish datachannels warning: ",e)}}async presubscribe(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const i={stream_id:e,stream_type:t,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!xP("SUBSCRIBE_TWCC"),rtx:!!xP("USE_SUB_RTX")||void 0,extend:xP("SUB_EXTEND"),svc:Array.isArray(xP("SVC"))&&0!==xP("SVC").length?xP("SVC"):void 0,dc_media_stream_id:this.store.aiClientMode?this.store.mediaDcId:void 0};try{return await this.signal.request(rF.PRE_SUBSCRIBE,i,!0)}catch(i){if(n&&i.data&&i.data.code===tF.ERR_SUBSCRIBE_REQUEST_INVALID)return SL.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),i.toString()),this.presubscribe(e,t,!1);throw i}}async subscribe(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const i={stream_id:e,stream_type:t.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!xP("SUBSCRIBE_TWCC"),rtx:!!xP("USE_SUB_RTX"),extend:xP("SUB_EXTEND"),ssrcId:t.ssrcId,svc:Array.isArray(xP("SVC"))&&0!==xP("SVC").length?xP("SVC"):void 0,dc_media_stream_id:this.store.aiClientMode?this.store.mediaDcId:void 0};try{return(await this.signal.request(rF.SUBSCRIBE,i,!0))._message}catch(i){if(n&&i.data&&i.data.code===tF.ERR_SUBSCRIBE_REQUEST_INVALID)return SL.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),i.toString()),await this.tryUnsubBeforeResub(e,t),await this.subscribe(e,t,!1);throw i}}async subscribeDataChannel(e,t,n){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const i={uid:e,stream_id:t.id,channel_id:t.datachannelId};try{return void await this.signal.request(rF.SUBSCRIBE_DATASTREAM,i,!0)}catch(i){if(n&&i.data&&i.data.code===tF.ERR_SUBSCRIBE_REQUEST_INVALID)return SL.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),i.toString()),await this.tryUnsubDataChannelBeforeResub(e,t),await this.subscribeDataChannel(e,t,!1);throw i}}async subscribeAll(e,t){if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const n={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!xP("USE_SUB_RTX"),twcc:!!xP("SUBSCRIBE_TWCC"),svc:Array.isArray(xP("SVC"))&&0!==xP("SVC").length?xP("SVC"):void 0};try{return await this.signal.request(rF.SUBSCRIBE_STREAMS,n,!0)}catch(n){if(t&&n.data&&n.data.code===tF.ERR_SUBSCRIBE_REQUEST_INVALID)return SL.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),n.toString()),await this.tryMassUnsubBeforeResub(e),await this.subscribeAll(e,!1);throw n}}async setVideoProfile(e){const t=function(e){if(!(e.bitrateMax&&e.bitrateMin&&e.frameRate&&e.height&&e.width))return;let t=e.frameRate,n=e.width,i=e.height,r=!0;return"number"!=typeof t&&(t=t.exact||t.ideal||t.max||t.min||0,t||(r=!1)),"number"!=typeof n&&(n=n.exact||n.ideal||n.max||n.min||0,n||(r=!1)),"number"!=typeof i&&(i=i.exact||i.ideal||i.max||i.min||0,i||(r=!1)),r?{stream_type:0,width:n,height:i,fps:t,start_bps:1e3*e.bitrateMax,min_bps:1e3*e.bitrateMin,target_bps:1e3*e.bitrateMax}:void 0}(e);if(t)return this.signal.request(rF.SET_VIDEO_PROFILE,t);SL.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))}async unsubscribe(e,t){try{await this.signal.request(rF.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:t},!0)}catch(e){SL.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),e)}}async unsubscribeDataChannel(e,t){try{if("CONNECTED"!==this.state&&"RECONNECTING"!==this.state)throw new YL(wN.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));await cp.all(e.map((e=>this.signal.request(rF.UNSUBSCRIBE_DATASTREAM,{stream_id:e,uid:t},!0))))}catch(e){SL.warning("unsubscribeDataChannel warning: ",e)}}async massUnsubscribe(e){try{await this.signal.request(rF.UNSUBSCRIBE_STREAMS,e,!0)}catch(e){SL.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),e)}}async reconnectPC(e){const t=e.iceParameters,n=e.dtlsParameters,i=e.rtpCapabilities;return{gatewayEstablishParams:await this.signal.request(rF.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:t,dtlsParameters:n,rtpCapabilities:i}},!0),gatewayAddress:this.getCurrentGatewayAddress()}}getGatewayInfo(){return this.signal.request(rF.GATEWAY_INFO)}async renewToken(e){await this.signal.request(rF.RENEW_TOKEN,e),this.key=e.token}updateClientRole(e,t){t&&(this._clientRoleOptions=Object.assign({},t)),xP("CLIENT_ROLE_OPTIONS")&&(SL.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(xP("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},xP("CLIENT_ROLE_OPTIONS"))),this.role=e}async setClientRole(e,t){if(t&&(this._clientRoleOptions=Object.assign({},t)),xP("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},xP("CLIENT_ROLE_OPTIONS")),SL.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(xP("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),"CONNECTED"!==this.state)return void(this.role=e);let n,i=0;"audience"===e?this._clientRoleOptions&&this._clientRoleOptions.delay?(n=this._clientRoleOptions.delay,i=1):i=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:i=0;const r=Object.assign({},t);delete r.delay,delete r.level,await this.signal.request(rF.SET_CLIENT_ROLE,Cee(Cee({role:e,level:i,delay:n},r),{},{client_ts:Date.now()})),this.role=e}async setDualStreamMode(e,t,n){await this.signal.request(rF.SET_DUAL_STREAM_MODE,{mode:e},n,t)}async setRemoteVideoStreamType(e,t){await this.signal.request(rF.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:t})}async setDefaultRemoteVideoStreamType(e){await this.signal.request(rF.DEFAULT_VIDEO_STREAM,{stream_type:e})}async setStreamFallbackOption(e,t){await this.signal.request(rF.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:t})}async pickSVCLayer(e,t){await this.signal.request(rF.PICK_SVC_LAYER,{stream_id:e,spatial_layer:t.spatialLayer,temporal_layer:t.temporalLayer})}async setRTM2Flag(e){await this.signal.request(rF.SET_RTM2_FLAG,{rtm2_flag:e})}async sendExtensionMessage(e,t,n){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,t,n)}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),Cee({},this.inChannelInfo)}async setConfigure(e){if(e&&Array.isArray(e)&&0!==e.length)return this.signal.request(rF.CONFIGURE,e)}async getGatewayVersion(){return(await this.signal.request(rF.GATEWAY_INFO)).version}reset(){if(this._sdpEndpointJoin=void 0,this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt,this.inChannelInfo.joinAt=null),this.trafficStatsInterval&&(window.clearInterval(this.trafficStatsInterval),this.trafficStatsInterval=void 0),this.joinInfo){const e=bee.get(this.joinInfo.cname);e&&e.delete(this.joinInfo.uid)}this.joinInfo=void 0,this.key=void 0,this.networkQualityInterval&&(window.clearInterval(this.networkQualityInterval),this.networkQualityInterval=void 0),this.usingProxy=!1}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(e){let t;return t=e.startsWith("dc")?e.match(/(dc\:\/\/)?([^:]+):(\d+)/):e.match(/(wss\:\/\/)?([^:]+):(\d+)/),t?{username:DP.username,password:DP.password,turnServerURL:t[2],tcpport:parseInt(t[3])+30,udpport:parseInt(t[3])+30,forceturn:!1}:null}(("disabled"===this.joinInfo.cloudProxyServer?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&"off"!==this.joinInfo.turnServer.mode&&"disabled"===this.joinInfo.cloudProxyServer&&this.joinInfo.turnServer.serversFromGateway.push(Cee(Cee({},DP),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}async updateTrafficStats(){if("CONNECTED"!==this.state)return;const e=await this.signal.request(rF.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),null!=e.ntp_offset&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach((e=>{const t=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find((t=>t.peer_uid===e.peer_uid));t&&t.B_st!==e.B_st&&RD((()=>{this.emit(bF.STREAM_TYPE_CHANGE,e.peer_uid,e.B_st)}))})),this._statsCollector.updateTrafficStats(e)}getJoinMessage(e){var t,n;if(!this.joinInfo||!this.key)throw new YL(wN.UNEXPECTED_ERROR,"can not generate join message, no join info");this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(bF.UPDATE_GATEWAY_CONFIG),n=this.store.clientId,Ui(Dx).call(Dx,n)||Dx.push(n);const i=function(e,t,n,i){var r,o,s,a,c;let d=i.key,l=i.role,u=i.joinGatewayStartTime,h=i.hasChangeBGPAddress,p=i.isPreallocation,_=i.ortc,E=i.currentURLIndex;const m=Object.assign({},t.apResponse);"signalResponse"in m&&m.signalResponse&&(p=!1,delete m.signalResponse);let f=xP("REPORT_APP_SCENARIO");if("string"!=typeof f)try{f=JSON.stringify(f)}catch(e){f=void 0}f&&f.length>128&&(f=void 0);const g=QL(e),S=$L(e),T=(null===(r=e.preSubOptions)||void 0===r?void 0:r.length)||0,R=T>0?null===(o=e.preSubOptions)||void 0===o?void 0:o.map((e=>e.uid)):void 0,v=l8("PRE_SUB_NUM","number")||1,y=T>v?T:v,C=u8(),b=tN(87)||ZO()||oN(117),I=(qO()||aN(18,4,!1))&&dN(18,6,!0)&&"h264"===n.codec&&xP("ENABLE_ABSSENDTIME_AS_SENTTS"),A=!("CN"!==(null===(s=m.detail)||void 0===s?void 0:s[3])||!xP("ENABLE_QUALITY_FALLBACK"))&&xP("ENABLE_QUALITY_FALLBACK"),w=!!xP("ENABLE_AP_MULTI_IP")&&"multi-ip"===(null===(a=m.detail)||void 0===a?void 0:a[5]),O={license:t.license,p2p_id:e.p2pId,session_id:t.sid,app_id:t.appId,channel_key:d,channel_name:t.cname,sdk_version:wP,browser:navigator.userAgent,process_id:xP("PROCESS_ID"),mode:e.useP2P?"p2p":n.mode,codec:n.codec,role:l,has_changed_gateway:w||h,ap_response:m,extend:xP("JOIN_EXTEND"),details:{6:t.stringUid,cservice_map:"proxy3"===t.cloudProxyServer?"1":"proxy5"===t.cloudProxyServer?"2":void 0},features:{rejoin:!0},optionalInfo:t.optionalInfo,appScenario:f,attributes:{userAttributes:d8(d8({enableEncodedTransform:(!!xP("ENABLE_AUDIO_METADATA")||!!xP("ENABLE_AUDIO_PTS"))&&b||!!xP("ENABLE_AUDIO_TOPN")&&iN(xO.CHROME,87,116)||void 0,enableAudioMetadata:!!xP("ENABLE_AUDIO_METADATA")&&b,enableAudioPts:!!xP("ENABLE_AUDIO_PTS")&&b,topnSmoothLevel:xP("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:xP("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:xP("TOPN_SWITCH_HOLD_MS"),topnAudioGain:xP("TOPN_AUDIO_GAIN"),enableNetworkQualityProbe:e.networkQualityProbe,enablePublishedUserList:xP("ENABLE_PUBLISHED_USER_LIST"),enableUserList:xP("ENABLE_USER_LIST"),maxSubscription:xP("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:l8("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:l8("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:l8("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:!0===xP("USE_PUB_RTX")||!0===xP("USE_SUB_RTX")||void 0,disableFEC:xP("DISABLE_FEC"),enableNTPReport:!!xP("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:S,enableFulllinkAvSync:!!xP("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:l8("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:tk(),rtm2Flag:"number"==typeof t.rtmFlag?t.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!xP("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:l8("USE_XR","boolean"),enableLossbasedBwe:l8("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:ek(),enableCCFallback:l8("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:p,preSubUid:g?R:void 0,preSubNum:g?y:void 0,enablePubTWCC:l8("PUBLISH_TWCC","boolean"),enableSubTWCC:l8("SUBSCRIBE_TWCC","boolean"),enablePubRTX:l8("USE_PUB_RTX","boolean"),enableSubRTX:l8("USE_SUB_RTX","boolean"),enableSubSVC:xP("ENABLE_SVC")?xP("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(xP("SVC"))&&0!==xP("SVC").length?xP("SVC"):void 0,enableSvcExtended:xP("ENABLE_SVC")&&Array.isArray(xP("SVC_EXTENDED"))&&0!==xP("SVC_EXTENDED").length?xP("SVC_EXTENDED"):void 0,enableVosFallback:xP("ENABLE_VOS_FALLBACK"),enableQualityFallback:A,flexiblePC:e.flexiblePC||void 0},C),{},{audioDuplicate:l8("ENABLE_AUDIO_RED","boolean")?null!==(c=l8("AUDIO_DUPLICATE_NUM","number"))&&void 0!==c?c:2:void 0,senttsUsesAbsSendTime:!!I||void 0,enableDualStreamFlag:l8("ENABLE_DUAL_STREAM_FLAG","boolean"),enableAiClientMode:!!e.aiClientMode||void 0,enableAiClientBbrStrategy:!!e.aiClientMode||void 0,dcMediaStreamId:e.aiClientMode?e.mediaDcId:void 0})},join_ts:u,ortc:_||{}};return t.stringUid&&(O.string_uid=t.stringUid),t.aesmode&&t.aespassword&&(O.aes_mode=t.aesmode,xP("ENCRYPT_AES")?(O.aes_secret=t.aespassword,O.aes_encrypt=!0):O.aes_secret=t.aespassword,t.aessalt&&(O.aes_salt=t.aessalt)),m.addresses[E]&&(O.ap_response.ticket=m.addresses[E].ticket,delete m.addresses),void 0!==t.defaultVideoStream&&(O.default_video_stream=t.defaultVideoStream),O}(this.store,this.joinInfo,this.spec,{key:this.key,role:this.role,joinGatewayStartTime:this.joinGatewayStartTime,hasChangeBGPAddress:this.hasChangeBGPAddress,isPreallocation:!(null===(t=this.isPreallocation)||void 0===t||!t.call(this)),ortc:e,currentURLIndex:this.signal.currentURLIndex});return i}getRejoinMessage(){if(!this.joinInfo)throw new YL(wN.UNEXPECTED_ERROR,"can not generate rejoin message, no join info");return{session_id:this.joinInfo.sid,channel_name:this.joinInfo.cname,cid:this.joinInfo.cid,uid:this.joinInfo.uid,vid:Number(this.joinInfo.vid)}}handlePrePc(e,t,n){if(this.joinInfo){var i,r;this.updateTurnConfigFromSignal();const u=this.getCurrentGatewayAddress(),h=vD(null===(i=this.joinInfo)||void 0===i?void 0:i.turnServer);if(xP("NEW_TURN_MODE")&&h&&"disabled"===(null===(r=this.joinInfo)||void 0===r?void 0:r.cloudProxyServer)){var o;let e=h.servers.map((e=>"turnServerURL"in e&&xP("USE_TURN_IP")?Cee(Cee({},e),{},{turnServerURL:g7(e.turnServerURL)}):e)),t=null===(o=h.serversFromGateway)||void 0===o?void 0:o.map((e=>xP("USE_TURN_IP")?Cee(Cee({},e),{},{turnServerURL:g7(e.turnServerURL)}):e));const n=this.signal.currentURLIndex;if(e.length>0){e=[e[n%e.length]],h.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],h.serversFromGateway=t),SL.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(n,",in pre pc"))}const p=this.joinInfo.apResponse.addresses[this.signal.currentURLIndex],_=xP("FINGERPRINT")||p.fingerprint;if(u&&_){var s,a,c,d,l;const i=K7(u);dD(this,bF.PRE_CONNECT_PC,{candidates:i,fingerprint:_,turnServer:h,iceUfrag:p.iceUfrag,icePwd:p.icePwd,originalPreSubSsrcs:null!==(s=null==e||null===(a=e.preJoinResponse.attributes)||void 0===a||null===(a=a.userAttributes)||void 0===a?void 0:a.preSubSsrcs)&&void 0!==s?s:null===(c=this.joinInfo.apResponse.signalResponse)||void 0===c||null===(c=c.attributes)||void 0===c||null===(c=c.userAttributes)||void 0===c?void 0:c.preSubSsrcs,rtpCapabilities:null!==(d=null==e?void 0:e.preJoinResponse.rtpCapabilities)&&void 0!==d?d:null===(l=this.joinInfo.apResponse.signalResponse)||void 0===l?void 0:l.rtpCapabilities,isSDPEndpoint:!!e}).then((e=>{null==t||t(e)})).catch(n||(()=>{}))}}}handleSignalEvents(){this.signal.on(iF.SHOULD_ENTER_RECONNECTING,((e,t)=>{var n;t("ice"===(null===(n=this._sdpEndpointJoin)||void 0===n||null===(n=n.winner)||void 0===n?void 0:n.type)&&"CONNECTED"===this.state&&this.signal.connectionState===nF.CONNECTING)})),this.signal.on(iF.WS_RECONNECT_CREATE_CONNECTION,(e=>{this.joinGatewayStartTime=Date.now()})),this.signal.on(iF.WS_RECONNECTING,(e=>{this.joinInfo&&HL.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||sD.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",HL.sessionInit(this.joinInfo.sid,{lts:(new Date).getTime(),extend:this.isSignalRecover?{recover:!0}:{rejoin:!0},cname:this.joinInfo.cname,appid:this.joinInfo.appId,mode:this.spec.mode,stringUid:this.joinInfo.stringUid,channelProfile:"live"===this.spec.mode?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:"audience"===this.role?2:1,buildFormat:2}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())})),this.signal.on(iF.WS_CLOSED,(e=>{let t;switch(e){case $N.LEAVE:t=sD.LEAVE;break;case $N.UID_BANNED:case $N.IP_BANNED:case $N.CHANNEL_BANNED:case $N.SERVER_ERROR:t=sD.SERVER_ERROR;break;case $N.FALLBACK:t=sD.FALLBACK;break;case $N.LICENSE_MISSING:case $N.LICENSE_EXPIRED:case $N.LICENSE_MINUTES_EXCEEDED:case $N.LICENSE_PERIOD_INVALID:case $N.LICENSE_MULTIPLE_SDK_SERVICE:case $N.LICENSE_ILLEGAL:case $N.TOKEN_EXPIRE:t=e;break;default:t=sD.NETWORK_ERROR}SL.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(t||"undefined -> "+sD.NETWORK_ERROR)),this.joinInfo&&HL.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===$N.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:t}),this._disconnectedReason=e,e!==$N.FALLBACK&&(this.state="DISCONNECTED"),this.reset()})),this.signal.on(iF.WS_CONNECTED,(()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",!this.joinInfo)return;const e=this._sdpEndpointJoin;if(e&&!e.roleReplaySent&&e.initialRole!==this.role){const t=this.role,n=xP("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e.roleReplaySent=!0,SL.debug("[".concat(this.store.clientId,"] JoinV4 role changed during early join, replay set client role: ").concat(t)),this.setClientRole(t,n).catch((e=>{SL.debug("[".concat(this.store.clientId,"] JoinV4 role replay failed"),e)}))}else if("audience"===this.role){const e=xP("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(SL.debug("[".concat(this.store.clientId,"] patch to send set client role, role: ").concat(this.role,", mode: ").concat(this.spec.mode,", level: ").concat(e.level,", delay: ").concat(e.delay)),this.setClientRole(this.role,e))}if(HL.joinGateway(this.joinInfo.sid,Cee({lts:this.joinGatewayStartTime,succ:!0,ec:null,vid:this.joinInfo.vid,addr:this.signal.url,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:e?"2":"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess},null!=e&&e.winner?{winner:e.winner.type,winnerAt:e.winner.at}:{})),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&1===this.joinInfo.setLocalAPVersion){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void SL.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));VP("EVENT_REPORT_DOMAIN",e[1]),VP("EVENT_REPORT_BACKUP_DOMAIN",e[1]),VP("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}})),this.signal.on(sF.ON_UPLINK_STATS,(e=>{this._statsCollector.updateUplinkStats(e)})),this.signal.on(sF.ON_P2P_OK,(()=>{var e;const t=this._sdpEndpointJoin;t&&(null!==(e=t.p2pOkAt)&&void 0!==e||(t.p2pOkAt=Date.now()),this.reportSDPEndpointJoinTiming())})),this.signal.on(iF.REQUEST_RECOVER,((e,t,n)=>{if(!this.joinInfo)return n(new YL(wN.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,this._sdpEndpointJoin=void 0,dD(this,bF.REQUEST_NEW_GATEWAY_LIST).then(t).catch(n)})),this.signal.on(iF.REQUEST_JOIN_INFO,(async(e,t,n)=>{var i,r,o;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage());const s=vD(null===(i=this.joinInfo)||void 0===i?void 0:i.turnServer);if(xP("NEW_TURN_MODE")&&s&&"disabled"===(null===(r=this.joinInfo)||void 0===r?void 0:r.cloudProxyServer)){var a;let e=s.servers.map((e=>"turnServerURL"in e&&xP("USE_TURN_IP")?Cee(Cee({},e),{},{turnServerURL:g7(e.turnServerURL)}):e)),t=null===(a=s.serversFromGateway)||void 0===a?void 0:a.map((e=>xP("USE_TURN_IP")?Cee(Cee({},e),{},{turnServerURL:g7(e.turnServerURL)}):e));const n=this.signal.currentURLIndex;if(e.length>0){e=[e[n%e.length]],s.servers=e}Array.isArray(t)&&t.length>0&&(t=[t[0]],s.serversFromGateway=t),SL.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(n))}const c=await dD(this,bF.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:s,cloudProxyServer:null===(o=this.joinInfo)||void 0===o?void 0:o.cloudProxyServer}),d=c.iceParameters,l=c.dtlsParameters,u=c.rtpCapabilities;try{e(this.getJoinMessage({iceParameters:d,dtlsParameters:l,rtpCapabilities:u,version:"2"}))}catch(e){t(e)}})),this.signal.on(iF.REQUEST_REJOIN_INFO,(e=>{e(this.getRejoinMessage())})),this.signal.on(iF.REPORT_JOIN_GATEWAY,((e,t)=>{if(!this.joinInfo)return;let n,i="";var r;e instanceof YL?(n=(null===(r=e.data)||void 0===r?void 0:r.desc)||e.code,i=e.message):n=e;HL.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:n,errorMsg:i,addr:t,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer||this.usingProxy,signalChannel:"DataChannelSignal"===this.signal.__name__?"1":"0",preload:this.joinInfo.preload})})),this.signal.on(iF.IS_P2P_DISCONNECTED,(e=>{e(hD(this,bF.IS_P2P_DISCONNECTED))})),this.signal.on(iF.DISCONNECT_P2P,(()=>{this._sdpEndpointJoin=void 0,this.emit(bF.DISCONNECT_P2P)})),this.signal.on(iF.REQUEST_SUCCESS,(()=>{this._signalTimeout=!1})),this.signal.on(iF.REQUEST_TIMEOUT,(()=>{this._signalTimeout=!0})),this.signal.on(iF.JOIN_RESPONSE,(e=>{const t=this.getCurrentGatewayAddress();this.emit(bF.JOIN_RESPONSE,e,t)})),this.signal.on(iF.PRE_CONNECT_PC,(async(e,t)=>{this.handlePrePc(void 0,e,t)})),this.signal.on(iF.RECOVER_NOTIFICATION,(e=>{this.joinInfo&&"string"==typeof xP("AP_REQUEST_DETAIL")&&(this.joinInfo.apRequestDetail="".concat(xP("AP_REQUEST_DETAIL"),";").concat(e))})),this.signal.on(iF.VOS_FALLBACK,(e=>{this.emit(bF.VOS_FALLBACK,e)})),this.signal.on(iF.DATACHANNEL_FAILBACK,(e=>{SL.warning("[".concat(this.store.clientId,"] User join datachannel failed")),this.reset(),this.resetSignal(),this.emit(bF.DATACHANNEL_FAILBACK)}))}async tryUnsubBeforeResub(e,t){try{await this.signal.request(rF.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[t]},!0)}catch(e){throw SL.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),e),e}}async tryUnsubDataChannelBeforeResub(e,t){try{await this.signal.request(rF.UNSUBSCRIBE,{stream_id:t.id},!0)}catch(e){throw SL.warning("unsubscribe datachannel warning",e),e}}async tryUnpubBeforeRepub(e,t){try{await this.signal.request(rF.UNPUBLISH,{stream_id:e,ortc:t},!0)}catch(e){throw SL.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),e),e}}async tryUnpubDataChannelBeforeRepub(e,t){try{await this.signal.request(rF.UNPUBLISH_DATASTREAM,{channnel_id:t.channelId},!0)}catch(e){throw SL.warning("unpublish datastream warning: ",e),e}}async tryMassUnsubBeforeResub(e){const t={users:e.map((e=>({stream_id:e.stream_id,stream_type:e.stream_type})))};try{await this.signal.request(rF.UNSUBSCRIBE_STREAMS,t,!0)}catch(e){throw SL.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),e),e}}async muteLocal(e,t){const n={action:e.find((e=>e.stream_type===CF.Audio))?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(rF.CONTROL,n,!0,!0)}catch(e){throw SL.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),e),e}}async unmuteLocal(e,t){const n={action:e.find((e=>e.stream_type===CF.Audio))?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:t};try{await this.signal.request(rF.CONTROL,n,!0,!0)}catch(e){throw SL.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),e),e}}async muteRemote(e,t){const n={action:e===UF.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(rF.CONTROL,n,!0,!0)}catch(e){throw SL.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),e),e}}async unmuteRemote(e,t){const n={action:e===UF.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:t};try{await this.signal.request(rF.CONTROL,n,!0,!0)}catch(e){throw SL.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),e),e}}uploadWRTCStats(e){this.signal.uploadWRTCStats(e)}upload(e,t){this.signal.upload(e,t)}getSignalRTT(){return this.signal.rtt}async restartICE(e){const t={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return await this.signal.request(rF.RESTART_ICE,t,!0)}catch(e){throw SL.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),e),e}}reconnect(e,t){"CONNECTED"===this.state&&this.signal.reconnect(e||void 0,t||sD.P2P_FAILED)}getCurrentGatewayAddress(){var e,t;if(!xP("GATEWAY_WSS_ADDRESS"))return xP("USE_CANDIDATE_FROM_AP_DETAIL")&&null!==(e=this.joinInfo)&&void 0!==e&&e.apGatewayAddress?(SL.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):null!==(t=this.joinInfo)&&void 0!==t&&t.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}reportSDPEndpointJoinTiming(){const e=this._sdpEndpointJoin,t=this.joinInfo;e&&t&&!e.timingReported&&e.winner&&e.p2pOkAt&&void 0!==e.iceConnectedAt&&void 0!==e.joinResponseAt&&(e.timingReported=!0,HL.joinGateway(t.sid,{lts:e.startAt,succ:!0,ec:null,vid:t.vid,addr:this.signal.url,uid:t.uid,cid:t.cid,firstSuccess:this._isProactiveJoin,isProxy:!!t.proxyServer||this.usingProxy,signalChannel:"2",preload:t.preload,isABTestSuccess:this.store.isABTestSuccess,iceConnectedAt:e.iceConnectedAt,joinResponseAt:e.joinResponseAt,winnerAt:e.winner.at,winner:e.winner.type,reportAt:e.p2pOkAt}),this._isProactiveJoin=!1,this._sdpEndpointJoin===e&&(this._sdpEndpointJoin=void 0))}async setPublishAudioFilterEnabled(e){await this.signal.request(rF.SET_PARAMETER,{enablePublishAudioFilter:e})}downgradeCodec(e){this.signal.downgradeCodec(e)}resetSignal(){this.signal&&(this.signal.removeAllListeners(),this.signal.close($N.FALLBACK)),this.store.useDcSignal=!1,this.signal=new SB(Cee(Cee({},this.spec),{},{retryConfig:this.spec.websocketRetryConfig}),this.store),this.handleSignalEvents(),this.emit(bF.RESET_SIGNAL)}}let Aee=function(e){return e.NATIVE_RTC="native_rtc",e.NATIVE_RTM="native_rtm",e.WEB_RTC="web_rtc",e.WEB_RTM="web_rtm",e}({}),wee=0,Oee=0;function Nee(e,t,n,i){return new cp(((r,o)=>{t.timeout=t.timeout||xP("HTTP_CONNECT_TIMEOUT"),t.responseType=t.responseType||"json",t.data&&!n?(t.data=JSON.stringify(t.data),wee+=ND(t.data)):n&&(t.data.size?wee+=t.data.size:t.data instanceof FormData?wee+=DD(t.data):wee+=ND(JSON.stringify(t.data))),t.headers=t.headers||{},t.headers["Content-Type"]=t.headers["Content-Type"]||"application/json",t.method="POST",t.url=e,DO.request(t).then((e=>{"string"==typeof e.data?Oee+=ND(e.data):e.data instanceof ArrayBuffer||e.data instanceof Uint8Array?Oee+=e.data.byteLength:Oee+=ND(JSON.stringify(e.data)),i&&r({data:e.data,headers:e.headers}),r(e.data)})).catch((e=>{DO.isCancel(e)?o(new YL(wN.OPERATION_ABORTED,"cancel token canceled")):"ECONNABORTED"===e.code?o(new YL(wN.NETWORK_TIMEOUT,e.message)):e.response?o(new YL(wN.NETWORK_RESPONSE_ERROR,e.response.status)):o(new YL(wN.NETWORK_ERROR,e.message))}))}))}
/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */!function(){var e;function n(e){var t=0;return function(){return t<e.length?{done:!1,value:e[t++]}:{done:!0}}}var i="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e};var r,o=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof t&&t];for(var n=0;n<e.length;++n){var i=e[n];if(i&&i.Math==Math)return i}throw Error("Cannot find global object")}(this);function s(e,t){if(t)e:{var n=o;e=e.split(".");for(var r=0;r<e.length-1;r++){var s=e[r];if(!(s in n))break e;n=n[s]}(t=t(r=n[e=e[e.length-1]]))!=r&&null!=t&&i(n,e,{configurable:!0,writable:!0,value:t})}}function a(e){return(e={next:e})[Symbol.iterator]=function(){return this},e}function c(e){var t="undefined"!=typeof Symbol&&Symbol.iterator&&e[Symbol.iterator];return t?t.call(e):{next:n(e)}}if(s("Symbol",(function(e){function t(e,t){this.A=e,i(this,"description",{configurable:!0,writable:!0,value:t})}if(e)return e;t.prototype.toString=function(){return this.A};var n="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",r=0;return function e(i){if(this instanceof e)throw new TypeError("Symbol is not a constructor");return new t(n+(i||"")+"_"+r++,i)}})),s("Symbol.iterator",(function(e){if(e)return e;e=Symbol("Symbol.iterator");for(var t="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),r=0;r<t.length;r++){var s=o[t[r]];"function"==typeof s&&"function"!=typeof s.prototype[e]&&i(s.prototype,e,{configurable:!0,writable:!0,value:function(){return a(n(this))}})}return e})),"function"==typeof Object.setPrototypeOf)r=Object.setPrototypeOf;else{var d;e:{var l={};try{l.__proto__={a:!0},d=l.a;break e}catch(e){}d=!1}r=d?function(e,t){if(e.__proto__=t,e.__proto__!==t)throw new TypeError(e+" is not extensible");return e}:null}var u=r;function h(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function p(e){if(e.m)throw new TypeError("Generator is already running");e.m=!0}function _(e,t){return e.h=3,{value:t}}function E(e){this.g=new h,this.G=e}function m(e,t,n,i){try{var r=t.call(e.g.j,n);if(!(r instanceof Object))throw new TypeError("Iterator result "+r+" is not an object");if(!r.done)return e.g.m=!1,r;var o=r.value}catch(t){return e.g.j=null,e.g.s(t),f(e)}return e.g.j=null,i.call(e.g,o),f(e)}function f(e){for(;e.g.h;)try{var t=e.G(e.g);if(t)return e.g.m=!1,{value:t.value,done:!1}}catch(t){e.g.v=void 0,e.g.s(t)}if(e.g.m=!1,e.g.l){if(t=e.g.l,e.g.l=null,t.F)throw t.D;return{value:t.return,done:!0}}return{value:void 0,done:!0}}function g(e){this.next=function(t){return e.o(t)},this.throw=function(t){return e.s(t)},this.return=function(t){return function(e,t){p(e.g);var n=e.g.j;return n?m(e,"return"in n?n.return:function(e){return{value:e,done:!0}},t,e.g.return):(e.g.return(t),f(e))}(e,t)},this[Symbol.iterator]=function(){return this}}function S(e,t){return t=new g(new E(t)),u&&e.prototype&&u(t,e.prototype),t}if(h.prototype.o=function(e){this.v=e},h.prototype.s=function(e){this.l={D:e,F:!0},this.h=this.C||this.u},h.prototype.return=function(e){this.l={return:e},this.h=this.u},E.prototype.o=function(e){return p(this.g),this.g.j?m(this,this.g.j.next,e,this.g.o):(this.g.o(e),f(this))},E.prototype.s=function(e){return p(this.g),this.g.j?m(this,this.g.j.throw,e,this.g.o):(this.g.s(e),f(this))},s("Array.prototype.entries",(function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var n=0,i=!1,r={next:function(){if(!i&&n<e.length){var r=n++;return{value:t(r,e[r]),done:!1}}return i=!0,{done:!0,value:void 0}}};return r[Symbol.iterator]=function(){return r},r}(this,(function(e,t){return[e,t]}))}})),"undefined"!=typeof Blob&&("undefined"==typeof FormData||!FormData.prototype.keys)){var T=function(e,t){for(var n=0;n<e.length;n++)t(e[n])},R=function(e){return e.replace(/\r?\n|\r/g,"\r\n")},v=function(e,t,n){return t instanceof Blob?(n=void 0!==n?String(n+""):"string"==typeof t.name?t.name:"blob",t.name===n&&"[object Blob]"!==Object.prototype.toString.call(t)||(t=new File([t],n)),[String(e),t]):[String(e),String(t)]},y=function(e,t){if(e.length<t)throw new TypeError(t+" argument required, but only "+e.length+" present.")},C="object"==typeof globalThis?globalThis:"object"==typeof window?window:"object"==typeof self?self:this,b=C.FormData,I=C.XMLHttpRequest&&C.XMLHttpRequest.prototype.send,A=C.Request&&C.fetch,w=C.navigator&&C.navigator.sendBeacon,O=C.Element&&C.Element.prototype,N=C.Symbol&&Symbol.toStringTag;N&&(Blob.prototype[N]||(Blob.prototype[N]="Blob"),"File"in C&&!File.prototype[N]&&(File.prototype[N]="File"));try{new File([],"")}catch(e){C.File=function(e,t,n){return e=new Blob(e,n||{}),Object.defineProperties(e,{name:{value:t},lastModified:{value:+(n&&void 0!==n.lastModified?new Date(n.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),N&&Object.defineProperty(e,N,{value:"File"}),e}}var D=function(e){return e.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},P=function(e){this.i=[];var t=this;e&&T(e.elements,(function(e){if(e.name&&!e.disabled&&"submit"!==e.type&&"button"!==e.type&&!e.matches("form fieldset[disabled] *"))if("file"===e.type){var n=e.files&&e.files.length?e.files:[new File([],"",{type:"application/octet-stream"})];T(n,(function(n){t.append(e.name,n)}))}else"select-multiple"===e.type||"select-one"===e.type?T(e.options,(function(n){!n.disabled&&n.selected&&t.append(e.name,n.value)})):"checkbox"===e.type||"radio"===e.type?e.checked&&t.append(e.name,e.value):(n="textarea"===e.type?R(e.value):e.value,t.append(e.name,n))}))};if((e=P.prototype).append=function(e,t,n){y(arguments,2),this.i.push(v(e,t,n))},e.delete=function(e){y(arguments,1);var t=[];e=String(e),T(this.i,(function(n){n[0]!==e&&t.push(n)})),this.i=t},e.entries=function e(){var t,n=this;return S(e,(function(e){if(1==e.h&&(t=0),3!=e.h)return t<n.i.length?e=_(e,n.i[t]):(e.h=0,e=void 0),e;t++,e.h=2}))},e.forEach=function(e,t){y(arguments,1);for(var n=c(this),i=n.next();!i.done;i=n.next()){var r=c(i.value);i=r.next().value,r=r.next().value,e.call(t,r,i,this)}},e.get=function(e){y(arguments,1);var t=this.i;e=String(e);for(var n=0;n<t.length;n++)if(t[n][0]===e)return t[n][1];return null},e.getAll=function(e){y(arguments,1);var t=[];return e=String(e),T(this.i,(function(n){n[0]===e&&t.push(n[1])})),t},e.has=function(e){y(arguments,1),e=String(e);for(var t=0;t<this.i.length;t++)if(this.i[t][0]===e)return!0;return!1},e.keys=function e(){var t,n,i,r,o=this;return S(e,(function(e){if(1==e.h&&(t=c(o),n=t.next()),3!=e.h)return n.done?void(e.h=0):(i=n.value,r=c(i),_(e,r.next().value));n=t.next(),e.h=2}))},e.set=function(e,t,n){y(arguments,2),e=String(e);var i=[],r=v(e,t,n),o=!0;T(this.i,(function(t){t[0]===e?o&&(o=!i.push(r)):i.push(t)})),o&&i.push(r),this.i=i},e.values=function e(){var t,n,i,r,o=this;return S(e,(function(e){if(1==e.h&&(t=c(o),n=t.next()),3!=e.h)return n.done?void(e.h=0):(i=n.value,(r=c(i)).next(),_(e,r.next().value));n=t.next(),e.h=2}))},P.prototype._asNative=function(){for(var e=new b,t=c(this),n=t.next();!n.done;n=t.next()){var i=c(n.value);n=i.next().value,i=i.next().value,e.append(n,i)}return e},P.prototype._blob=function(){var e="----formdata-polyfill-"+Math.random(),t=[],n="--"+e+'\r\nContent-Disposition: form-data; name="';return this.forEach((function(e,i){return"string"==typeof e?t.push(n+D(R(i))+'"\r\n\r\n'+R(e)+"\r\n"):t.push(n+D(R(i))+'"; filename="'+D(e.name)+'"\r\nContent-Type: '+(e.type||"application/octet-stream")+"\r\n\r\n",e,"\r\n")})),t.push("--"+e+"--"),new Blob(t,{type:"multipart/form-data; boundary="+e})},P.prototype[Symbol.iterator]=function(){return this.entries()},P.prototype.toString=function(){return"[object FormData]"},O&&!O.matches&&(O.matches=O.matchesSelector||O.mozMatchesSelector||O.msMatchesSelector||O.oMatchesSelector||O.webkitMatchesSelector||function(e){for(var t=(e=(this.document||this.ownerDocument).querySelectorAll(e)).length;0<=--t&&e.item(t)!==this;);return-1<t}),N&&(P.prototype[N]="FormData"),I){var L=C.XMLHttpRequest.prototype.setRequestHeader;C.XMLHttpRequest.prototype.setRequestHeader=function(e,t){L.call(this,e,t),"content-type"===e.toLowerCase()&&(this.B=!0)},C.XMLHttpRequest.prototype.send=function(e){e instanceof P?(e=e._blob(),this.B||this.setRequestHeader("Content-Type",e.type),I.call(this,e)):I.call(this,e)}}A&&(C.fetch=function(e,t){return t&&t.body&&t.body instanceof P&&(t.body=t.body._blob()),A.call(this,e,t)}),w&&(C.navigator.sendBeacon=function(e,t){return t instanceof P&&(t=t._asNative()),w.call(this,e,t)}),C.FormData=P}}();const Dee=()=>{const e=xP("AREAS");0===e.length&&e.push(wF.GLOBAL);return sr(e).call(e,((e,t,n)=>{const i=Pee(t);return i?0===n?i:"".concat(e,",").concat(i):e}),"")},Pee=e=>e===wF.OVERSEA?"".concat(NF.ASIA,",").concat(NF.EUROPE,",").concat(NF.AFRICA,",").concat(NF.NORTH_AMERICA,",").concat(NF.SOUTH_AMERICA,",").concat(NF.OCEANIA):NF[e],Lee=e=>{const t={CODE:"",WEBCS_DOMAIN:[],WEBCS_DOMAIN_BACKUP_LIST:[],PROXY_CS:[],CDS_AP:[],ACCOUNT_REGISTER:[],UAP_AP:[],EVENT_REPORT_DOMAIN:[],EVENT_REPORT_BACKUP_DOMAIN:[],LOG_UPLOAD_SERVER:[],PROXY_SERVER_TYPE3:[]};return e.map((e=>{const n=DF[e],i=Object.keys(n);i&&i.map((e=>{"CODE"!==e&&(t[e]=t[e].concat(n[e]))}))})),t},kee={GLOBAL:{ASIA:[wF.CHINA,wF.JAPAN,wF.INDIA,wF.KOREA,wF.HKMC],EUROPE:[],NORTH_AMERICA:[wF.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},Mee=Object.keys(kee[wF.GLOBAL]),Uee=[wF.CHINA,wF.NORTH_AMERICA,wF.EUROPE,wF.ASIA,wF.JAPAN,wF.INDIA,wF.OCEANIA,wF.SOUTH_AMERICA,wF.AFRICA,wF.KOREA,wF.HKMC,wF.US],Vee=function(e,t){let n=[];if(Ui(e).call(e,wF.GLOBAL)){const o=[wF.GLOBAL,wF.OVERSEA],s=Object.keys(DF);if(t===wF.GLOBAL)throw new YL(wN.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(t===wF.CHINA)n=[wF.OVERSEA];else if(r=t,Ui(Mee).call(Mee,r)){const e=(i=t,kee[wF.GLOBAL][i]||[]),r=[...o,t,...e];n=s.filter((e=>!Ui(r).call(r,e)))}else if(function(e){let t=!1;return Mee.forEach((n=>{var i;Ui(i=kee[wF.GLOBAL][n]).call(i,e)&&(t=!0)})),t}(t)){const e=function(e){let t;return Mee.forEach((n=>{var i;Ui(i=kee[wF.GLOBAL][n]).call(i,e)&&(t=n)})),t}(t),i=[...o,e,t];n=s.filter((e=>!Ui(i).call(i,e)))}else n=e;n=function(e){const t=[];return Uee.forEach((n=>{Ui(e).call(e,n)&&t.push(n)})),t.concat(e.filter((e=>!Ui(Uee).call(Uee,e))))}(n)}else n=e;var i,r;return n};function xee(e){var t,n;if(!e&&Ui(t=xP("AREAS")).call(t,wF.EXTENSIONS))return SL.debug("update area from ap : reset"),void Fee(wx,!0);if(!Ui(n=xP("AREAS")).call(n,wF.GLOBAL)||!e)return;let i=DF.EXTENSIONS;i&&(i={CODE:Pee(wF.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(e,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(e,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(e,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(e,".agora.io"),"cds-ap-web-2-".concat(e,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(e,".agora.io"),"sua-ap-web-2-".concat(e,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(e,".agora.io"),"uap-ap-web-2-".concat(e,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(e,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(e,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(e,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(e,".agora.io")]},SL.debug("update area from ap success: ".concat(e,",config is "),i),VP("AREAS",[wF.EXTENSIONS],!0),Object.keys(i).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){VP(e,i[e][0])}else VP(e,i[e])})))}function Fee(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=HL.reportApiInvoke(null,{name:zN.SET_AREA,options:e,tag:ZN.TRACER});try{let i=[];if("string"==typeof e&&(i=[e]),Array.isArray(e)&&(e.forEach((e=>{if(!Ui(OF).call(OF,e))throw new YL(wN.INVALID_PARAMS,"invalid area code")})),i=e),"[object Object]"===Object.prototype.toString.call(e)){const t=e,n=t.areaCode,r=t.excludedArea;if(!n)throw new YL(wN.INVALID_PARAMS,"area code is needed");let o=n;"string"==typeof n&&(o=[n]),i=r?Vee(o,r):o}if(!t){if(BP.AREAS){const e=new YL(wN.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return n.onError(e),void SL.warning("setArea is prohibited because of config-distribute")}if(Ui(i).call(i,wF.GLOBAL)&&xP("AREAS")===wF.EXTENSIONS){const e=new YL(wN.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return n.onError(e),void SL.warning("setArea is prohibited because of ap extensions")}}VP("AREAS",i,t);const r=Lee(i);Object.keys(r).map((e=>{if("LOG_UPLOAD_SERVER"===e||"EVENT_REPORT_DOMAIN"===e||"EVENT_REPORT_BACKUP_DOMAIN"===e||"PROXY_SERVER_TYPE3"===e){VP(e,r[e][0])}else VP(e,r[e])})),SL.debug("set area success:",i.join(","))}catch(e){throw n.onError(e),e}n.onSuccess()}function Bee(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function jee(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Bee(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Bee(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let Gee=1;function Wee(e,t,n,i,r){Gee+=1;const o={sid:n.sid,command:"convergeAllocateEdge",uid:"666",appId:n.appId,ts:Math.floor(Date.now()/1e3),seq:Gee,requestId:Gee,version:wP,cname:n.cname},s={service_name:t,json_body:JSON.stringify(o)};let a,c,d=e[0];return QD((async()=>{a=Date.now();const e=await Nee(d,{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,0!==e.code){const t=new YL(wN.UNEXPECTED_RESPONSE,"live streaming ap error, code"+e.code,{retry:!0,responseTime:c});throw SL.error(t.toString()),t}const n=JSON.parse(e.json_body);if(200!==n.code){const e=new YL(wN.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(n.code,", reason: ").concat(n.reason),{code:n.code,responseTime:c});throw SL.error(e.toString()),e}if(!n.servers||0===n.servers.length){const e=new YL(wN.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:n.code,responseTime:c});throw SL.error(e.toString()),e}const r=function(e,t){return{addressList:e.servers.map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(xP("WORKER_DOMAIN"),":").concat(e.wss,"?serviceName=").concat(encodeURIComponent(t)))),workerToken:e.workerToken,vid:e.vid}}(n,t);return xP("LIVE_STREAMING_ADDRESS")&&(r.addressList=xP("LIVE_STREAMING_ADDRESS")instanceof Array?xP("LIVE_STREAMING_ADDRESS"):[xP("LIVE_STREAMING_ADDRESS")]),jee(jee({},r),{},{responseTime:c})}),((i,r)=>(HL.apworkerEvent(n.sid,{success:!0,sc:200,serviceName:t,responseDetail:JSON.stringify(i.addressList),firstSuccess:0===r,responseTime:c,serverIp:e[r%e.length]}),!1)),((i,r)=>(HL.apworkerEvent(n.sid,{success:!1,sc:i.data&&i.data.code||200,serviceName:t,responseTime:c,serverIp:e[r%e.length]}),!!(i.code!==wN.OPERATION_ABORTED&&i.code!==wN.UNEXPECTED_RESPONSE||i.data&&i.data.retry)&&(d=e[(r+1)%e.length],!0))),r)}let Kee=1;function Hee(e,t,n,i,r,o,s){let a=e.url,c=e.areaCode;const d=Date.now();let l;const u=n.role,h=KC(Qee(r,n,i,c,Array.isArray(t)?t:[t]),2),p=h[0],_=h[1];let E=pD.networkState;return QD((async()=>{E&&pD.networkState===aD.OFFLINE&&pD.onlineWaiter&&await cp.race([pD.onlineWaiter,LD(s&&s.maxRetryTimeout||ZD.maxRetryTimeout)]),E=pD.networkState;const e=await Nee(a,{data:p,cancelToken:o,responseType:"arraybuffer",headers:{"Content-Type":"text/plain;"}},!0,!0),r=e.data,c=e.headers;let u;l="1"===c.http3?1:-1,HL.reportResourceTiming(a,n.sid,n.clientId);const h=c["content-type"]||c["Content-Type"]||"",_=Ui(h).call(h,"application/json");try{u=_?function(e){const t=xP("ENABLE_AP_COMPRESS")?HW(e,{raw:!0}):e,n=(new TextDecoder).decode(t);return JSON.parse(n)}(r):p7(n,i,r)}catch(e){throw new YL(wN.PB_ERROR,"sdp enpoint response transformer get unknown res",{retry:!1})}Jee(u,a,n,d,Array.isArray(t)?t:[t],l);const m=y7(u,YW.CHOOSE_SERVER);let f;Array.isArray(t)&&t.length>1&&(f=y7(u,"proxy5"===n.cloudProxyServer?YW.CLOUD_PROXY_5:"proxy3"===n.cloudProxyServer||"proxy4"===n.cloudProxyServer?YW.CLOUD_PROXY:YW.CLOUD_PROXY_FALLBACK));const g=performance.getEntriesByName(a),S=g[g.length-1];let T;return S&&(T={name:S.name,protocol:"nextHopProtocol"in S?S.nextHopProtocol:"",dnscost:"domainLookupEnd"in S&&"domainLookupStart"in S&&"number"==typeof S.domainLookupEnd&&"number"==typeof S.domainLookupStart?S.domainLookupEnd-S.domainLookupStart:-1,tcpTlsCost:"connectEnd"in S&&"connectStart"in S&&"number"==typeof S.connectEnd&&"number"==typeof S.connectStart?S.connectEnd-S.connectStart:-1,reqCost:"requestStart"in S&&"number"==typeof S.requestStart&&"responseEnd"in S&&"number"==typeof S.responseEnd?S.responseEnd-S.requestStart:-1,handleCost:"leave_ts"in u&&"enter_ts"in u&&"number"==typeof u.leave_ts&&"number"==typeof u.enter_ts?u.leave_ts-u.enter_ts:-1}),zee(m),Array.isArray(t)?{gatewayInfo:S7(m,a),proxyInfo:f,url:a,resourceTimingInfo:T}:S7(m,a)}),(e=>{const i="gatewayInfo"in e?e.gatewayInfo:e,r="proxyInfo"in e?e.proxyInfo:void 0,o="resourceTimingInfo"in e?e.resourceTimingInfo:void 0;return i&&HL.joinChooseServer(n.sid,{role:u,lts:d,succ:!0,csAddr:a,serverList:i.gatewayAddrs.map((e=>e.address)),ec:null,opid:_,cid:i.cid.toString(),uid:i.uid.toString(),csIp:i.csIp,unilbsServerIds:t.toString(),isHttp3:l,corssRegionTagReq:n.apRequestDetail,corssRegionTagRes:i.res.detail&&i.res.detail[38],vid:null==i?void 0:i.vid,resourceTimingInfo:o?JSON.stringify(o):void 0}),r&&HL.joinWebProxyAP(n.sid,{lts:d,sucess:1,apServerAddr:a,turnServerAddrList:r.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:n.cloudProxyServer,unilbsServerIds:t.toString()}),!1}),(e=>e.code!==wN.PB_ERROR&&(e.code!==wN.OPERATION_ABORTED&&(e.code===wN.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(HL.joinWebProxyAP(n.sid,{lts:d,sucess:0,apServerAddr:a,turnServerAddrList:null,errorCode:e.code,eventType:n.cloudProxyServer,unilbsServerIds:t.toString(),extend:JSON.stringify({networkState:E})}),SL.warning("[".concat(n.clientId,"] multi unilbs network error, retry"),e),!0)))),s)}function Yee(e,t,n,i){let r=e.url,o=e.areaCode;const s=t.clientId,a=t.sid,c=Date.now();let d;const l=t.role,u=KC(qee(t,o,[YW.CHOOSE_SERVER]),2),h=u[0],p=u[1];let _=pD.networkState;return QD((async()=>{_&&pD.networkState===aD.OFFLINE&&pD.onlineWaiter&&await cp.race([pD.onlineWaiter,LD(i&&i.maxRetryTimeout||ZD.maxRetryTimeout)]),_=pD.networkState;const e=await Nee(r,{data:h,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),o=e.data,l=e.headers;d="1"===l.http3?1:-1,HL.reportResourceTiming(r,a,s),Jee(o,r,t,c,[YW.CHOOSE_SERVER],d);const u=y7(o,YW.CHOOSE_SERVER);return zee(u),S7(u,r)}),(e=>(e&&HL.joinChooseServer(a,{role:l,lts:c,succ:!0,csAddr:r,opid:p,serverList:e.gatewayAddrs.map((e=>e.address)),ec:null,cid:e.cid.toString(),uid:e.uid.toString(),csIp:e.csIp,unilbsServerIds:[YW.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.res.detail&&e.res.detail[38],vid:e.vid}),!1)),(e=>e.code!==wN.OPERATION_ABORTED&&(e.code===wN.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(HL.joinChooseServer(a,{role:l,lts:c,succ:!1,csAddr:r,serverList:null,opid:p,ec:e.code,csIp:e.data&&e.data.csIp,unilbsServerIds:[YW.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:_}),isHttp3:d,corssRegionTagReq:t.apRequestDetail}),SL.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),e),!0))),i)}function Xee(e,t,n,i){let r,o=e.url,s=e.areaCode,a=e.serviceIds;const c=Date.now(),d=t.role,l=KC(qee(t,s,a),2),u=l[0],h=l[1];let p;return QD((async()=>{p&&pD.networkState===aD.OFFLINE&&pD.onlineWaiter&&await cp.race([pD.onlineWaiter,LD(i&&i.maxRetryTimeout||ZD.maxRetryTimeout)]),p=pD.networkState;const e=await Nee(o,{data:u,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),s=e.data,d=e.headers;r="1"===d.http3?1:-1,HL.reportResourceTiming(o,t.sid,t.clientId),Jee(s,o,t,c,a,r);const l=y7(s,YW.CHOOSE_SERVER),h=y7(s,"proxy5"===t.cloudProxyServer?YW.CLOUD_PROXY_5:"proxy3"===t.cloudProxyServer||"proxy4"===t.cloudProxyServer?YW.CLOUD_PROXY:YW.CLOUD_PROXY_FALLBACK),_=performance.getEntriesByName(o),E=_[_.length-1];let m;return E&&(m={name:E.name,protocol:"nextHopProtocol"in E?E.nextHopProtocol:"",dnscost:"domainLookupEnd"in E&&"domainLookupStart"in E&&"number"==typeof E.domainLookupEnd&&"number"==typeof E.domainLookupStart?E.domainLookupEnd-E.domainLookupStart:-1,tcpTlsCost:"connectEnd"in E&&"connectStart"in E&&"number"==typeof E.connectEnd&&"number"==typeof E.connectStart?E.connectEnd-E.connectStart:-1,reqCost:"requestStart"in E&&"number"==typeof E.requestStart&&"responseEnd"in E&&"number"==typeof E.responseEnd?E.responseEnd-E.requestStart:-1,handleCost:"leave_ts"in s&&"enter_ts"in s&&"number"==typeof s.leave_ts&&"number"==typeof s.enter_ts?s.leave_ts-s.enter_ts:-1}),zee(l),{gatewayInfo:S7(l,o),proxyInfo:h,url:o,resourceTimingInfo:m}}),(e=>{var n;return e.gatewayInfo&&HL.joinChooseServer(t.sid,{role:d,lts:c,succ:!0,csAddr:o,serverList:e.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,opid:h,cid:e.gatewayInfo.cid.toString(),uid:e.gatewayInfo.uid.toString(),csIp:e.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r,corssRegionTagReq:t.apRequestDetail,corssRegionTagRes:e.gatewayInfo.res.detail&&e.gatewayInfo.res.detail[38],vid:null===(n=e.gatewayInfo)||void 0===n?void 0:n.vid,resourceTimingInfo:e.resourceTimingInfo?JSON.stringify(e.resourceTimingInfo):void 0}),e.proxyInfo&&HL.joinWebProxyAP(t.sid,{lts:c,sucess:1,apServerAddr:o,turnServerAddrList:e.proxyInfo.addresses.map((e=>e.ip)).join(","),errorCode:null,eventType:t.cloudProxyServer,unilbsServerIds:a.toString()}),!1}),(e=>e.code!==wN.OPERATION_ABORTED&&(e.code===wN.CAN_NOT_GET_GATEWAY_SERVER?e.data.retry:(HL.joinWebProxyAP(t.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:e.code,eventType:t.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:p})}),SL.warning("[".concat(t.clientId,"] multi unilbs network error, retry"),e),!0))),i)}const Jee=(e,t,n,i,r,o)=>{const s=n.sid,a=n.clientId,c=n.cloudProxyServer,d=[],l=a=>{4096===a.flag?HL.joinChooseServer(s,{role:n.role,lts:i,succ:!1,csAddr:t,opid:e.opid,serverList:null,ec:a.error.message,csIp:a.error.data&&a.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:o,corssRegionTagReq:n.apRequestDetail}):1048576!==a.flag&&4194304!==a.flag&&4194310!==a.flag||HL.joinWebProxyAP(s,{lts:i,sucess:0,apServerAddr:t,turnServerAddrList:null,errorCode:a.error.code,eventType:c,unilbsServerIds:r.toString()})};if(e.response_body.forEach((t=>{const n=t.buffer.code;if(23===t.uri&&0===n&&!t.buffer.edges_services)if(4194310===t.buffer.flag)SL.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),t.buffer.edges_services=[];else{const n={error:new YL(wN.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:xP("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:t.buffer.flag};d.push(n),l(n)}if(0!==n){const i=iB(n),r={error:new YL(wN.CAN_NOT_GET_GATEWAY_SERVER,i.desc,{desc:i.desc,retry:i.retry,csIp:e.detail[502]}),flag:t.buffer.flag};4194310===t.buffer.flag?SL.warning(r.error.toString()):d.push(r),l(r)}})),d.length)throw SL.warning("[".concat(a||"sid-".concat(s.slice(0,6)),"] multi unilbs ").concat(t," failed, ").concat(d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message,", retry: ").concat(e.error.data.retry))).join(" | "))),new YL(wN.CAN_NOT_GET_GATEWAY_SERVER,d.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!d.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(d.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})},zee=e=>{var t,n,i,r;if(e.addresses&&0===e.addresses.length&&0===e.code)throw new YL(wN.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:e.detail&&e.detail[502]});xP("AP_AREA")&&(null!==(i=e.detail)&&void 0!==i&&i[23]&&"string"==typeof(null===(r=e.detail)||void 0===r?void 0:r[23])?xee(e.detail[23].toLowerCase()):xee());if(null!==(t=e.detail)&&void 0!==t&&t[19]&&"string"==typeof(null===(n=e.detail)||void 0===n?void 0:n[19])){const t=e.detail[19],n=null==t?void 0:t.split(";");for(let t=0;t<n.length;t++){var o;const i=zS(o=n[t]).call(o),r=e.addresses[t];r&&n&&!r.fingerprint&&(e.addresses[t].fingerprint=i)}}if(xP("GATEWAY_ADDRESS")&&xP("GATEWAY_ADDRESS").length>0){SL.debug("assign gateway address to",xP("GATEWAY_ADDRESS"));const t=xP("GATEWAY_ADDRESS").map((t=>{var n,i,r,o;const s=null!==(n=null===(i=e.addresses.find((e=>e.ip===t.ip&&e.port===t.port)))||void 0===i?void 0:i.fingerprint)&&void 0!==n?n:"";return{ip:t.ip,port:t.port,ticket:e.addresses[0]&&e.addresses[0].ticket,fingerprint:s,iceUfrag:null===(r=e.addresses[0])||void 0===r?void 0:r.iceUfrag,icePwd:null===(o=e.addresses[0])||void 0===o?void 0:o.icePwd}}));e.addresses=t}},Zee=(e,t)=>{if(e.response_body&&e.response_body.length){const t=e.response_body[0];if(0!==t.buffer.code){const e=iB(t.buffer.code);throw new YL(wN.UPDATE_TICKET_FAILED,"[".concat(t.buffer.code,"]: ").concat(e.desc),{retry:e.retry})}return t.buffer.ticket}throw SL.debug("update ticket request received ap response without response body:",t),new YL(wN.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},qee=(e,t,n)=>{var i;const r=Math.floor(Math.random()*10**12),o="host"===e.role?"1":"audience"===e.role?"2":void 0,s={appid:e.appId,client_ts:Date.now(),opid:r,sid:e.sid,request_bodies:[{uri:22,buffer:{cname:e.cname,detail:jee(jee(jee(jee(jee({6:e.stringUid},null!==(i=e.multiIP)&&void 0!==i&&i.gateway_ip?{5:JSON.stringify({vocs_ip:[e.multiIP.uni_lbs_ip],vos_ip:[e.multiIP.gateway_ip]})}:{}),{},{11:t,12:xP("USE_NEW_TOKEN")?"1":void 0},o?{17:o}:{}),{},{22:t},e.apRequestDetail?{33:e.apRequestDetail}:{}),e.apRTM?{26:"RTM2"}:{}),e.apRequestDetailExtend),key:e.token,service_ids:n,uid:e.uid||0}}]},a=new FormData;return a.append("request",JSON.stringify(s)),[a,r]},Qee=(e,t,n,i,r)=>{const o=Math.floor(Math.random()*10**12);return[h7(e,t,i,r,{opid:o,mode:e.mode,codec:e.codec,hasChangeBGPAddress:!1,ortc:n}),o]},$ee=(e,t)=>{const n=Math.floor(Math.random()*10**12),i={appid:e.appId,client_ts:Date.now(),opid:n,sid:e.sid,request_bodies:[{uri:28,buffer:{cname:e.cname,detail:{1:"",6:e.stringUid,12:"1"},token:e.token,service_ids:t,uid:e.uid||0,edges_services:e.apResponse.addresses.map((e=>({ip:e.ip,port:e.port})))}}]},r=new FormData;return r.append("request",JSON.stringify(i)),[r,n]};let ete=0;function tte(e){return cp.all(e.map((e=>e.then((e=>{throw e}),(e=>e))))).then((e=>{throw e}),(e=>e))}const nte=async e=>{let t=e.fragementLength,n=e.referenceList,i=e.asyncMapHandler,r=e.allFailedhandler,o=e.promisesCollector,s=0;const a=t;let c,d=0;const l=async()=>{const e=(()=>{const e=s*a,t=e+a;return n.slice(e,t).map(i)})();o&&o.push(...e);try{c=await tte(e)}catch(e){if(d+=a,s++,!(d>=n.length))return void await l();r(e)}e.forEach((e=>e.cancel()))};return await l(),c},ite=async e=>{let t=e.referenceList,n=e.asyncMapHandler,i=e.closeFn;const r=t.length;let o=0;const s=async()=>{const e=n(t.shift());try{return await e}catch(e){if(o++,o>=r||null!=i&&i(e))throw e;return s()}};return s()};async function rte(){if("undefined"==typeof VideoDecoder)return!0;let e;const t=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,85,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,149,160,133,4,144,43,122,168,159,120,159,205,39,82,131,57,52,87,187,68,23,248,134,204,226,97,17,49,183,55,236,219,249,221,98,208,215,190,59,179,167,213,47,1,246,150,14,194,245,159,83,35,64,103,218,38,21,82,3,135,21,185,84,248,134],n=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,148,62,134,140,92,172,141,77,35,94,181,164,65,169,65,156,154,43,221,162,11,252,67,102,113,48,136,137,219,62,43,113,239,23,126,250,186,252,10,138,218,25,193,244,74,68,194,209,107,23,52,206,199,78,72,98,103,151,71,96,62,51,210,158,72,231,158],i=[18,0,10,13,0,0,0,3,180,253,144,6,136,8,8,8,32,50,87,16,66,128,2,8,32,132,0,8,0,180,90,204,169,166,242,109,241,190,143,143,233,163,51,196,98,95,151,224,22,134,33,240,150,248,67,18,34,196,142,81,238,173,140,80,205,232,132,144,67,12,131,157,4,171,243,86,122,35,6,166,184,243,85,126,13,206,103,152,62,168,160,187,2,241,138,52,211,72,121,128,151,63,147,128,19,42],r=[18,0,50,138,1,48,192,64,253,248,65,17,67,192,32,0,16,0,0,0,0,0,0,0,195,12,48,144,64,32,0,209,75,61,9,204,25,115,79,226,115,63,63,208,70,210,220,153,126,241,237,37,107,195,153,1,99,112,230,189,209,169,130,10,11,22,167,215,159,205,197,7,183,162,26,48,254,141,134,103,32,16,235,45,1,15,18,119,169,110,206,251,51,115,202,60,148,1,46,39,109,25,28,86,168,15,77,211,239,2,58,43,146,26,230,184,81,48,140,226,226,250,222,146,171,133,164,13,188,180,64,122,142,146,32,208,238,170,193,35,53,44,225],o=[18,0,50,107,48,0,133,125,248,65,26,195,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,204,24,122,65,56,165,18,52,206,218,4,187,51,97,9,29,191,90,253,106,185,31,197,155,52,205,245,185,203,131,20,226,25,124,95,113,220,113,141,15,15,104,211,144,152,237,150,157,127,51,143,24,231,218,171,255,176,241,128,229,149,150,148,66,245,228,91,27,182,228,136,61,182,237,133,45,220,24,103,214,152],s=[18,0,50,122,48,1,9,253,248,65,26,67,64,62,32,31,16,0,0,0,0,0,1,4,16,64,144,64,32,0,198,182,231,242,220,235,163,140,12,36,36,166,46,132,210,4,71,23,218,132,27,30,17,45,244,79,31,243,195,136,100,169,76,88,142,85,204,217,121,168,29,163,198,17,251,223,73,12,212,244,139,123,151,179,75,216,96,208,136,40,229,42,59,149,10,116,228,85,99,93,221,108,255,140,248,20,30,167,122,109,206,164,108,197,110,251,23,243,133,160,63,13,207,177,12,128],a=await new cp(((a,c)=>{let d;!async function(){e&&"closed"!==e.state||await async function(){e=new VideoDecoder({output:e=>{e.close(),clearTimeout(d),a(!0)},error:e=>{clearTimeout(d),a(!1)}}),await e.configure({codec:"av01.0.05M.08",width:160,height:90})}();const c=[t,n,i,r,o,s];for(let t=0;t<c.length;t++){const n=new EncodedVideoChunk({type:0==t?"key":"delta",timestamp:33333*t,duration:33333,data:new Uint8Array(c[t])});try{await e.decode(n)}catch(e){return void a(!1)}}}(),d=setTimeout((()=>{a(!1)}),5e3)}));return a}function ote(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function ste(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?ote(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ote(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}async function ate(e,t,n,i){const r=async function(e,t,n,i){let r=null;const o=[],s=async()=>{const r=xP("WEBCS_DOMAIN").slice(0,xP("AJAX_REQUEST_CONCURRENT")).map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:Dee()}))),s=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),a=await nte({fragementLength:xP("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:i=>(SL.debug("[".concat(e.clientId,"] Connect to choose_server:"),i.url),Yee(i,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:o});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},s),a},a=async()=>{if(await LD(1e3),null!==r)return r;const s=xP("WEBCS_DOMAIN_BACKUP_LIST").map((t=>({url:e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2"),areaCode:Dee()}))),a=i.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:s.map((e=>e.url))}),c=await nte({fragementLength:xP("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:i=>(SL.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),i.url),Yee(i,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},a),e[0]},promisesCollector:o});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},a),c};try{return r=await tte([s(),a()]),o.length&&o.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),r}catch(e){throw e[0]}}(e,t,n,i);return{gatewayInfo:await r}}async function cte(e,t,n,i,r){const o=e.cloudProxyServer;if("disabled"===o){if(!i)return;if(e.useLocalAccessPoint)return await ate(e,t,n,r);if(xP("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const i=await mte(e,t,n,r),o=i.gatewayInfo,a=i.proxyInfo;if(e.turnServer&&"auto"!==e.turnServer.mode)return{gatewayInfo:o};const c=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||DP.tcpport,udpport:e.udpport||DP.udpport,username:e.username||DP.username,password:e.password||DP.password,forceturn:!1,security:!0})));if(r.useP2P){var s;const t=null!==(s=e.uid)&&void 0!==s?s:o.uid,n="glb:".concat(t.toString()),i=await HN(n),r=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||DP.tcpport,udpport:e.udpport||DP.udpport,username:n,password:i,forceturn:!1,security:!0})));c.push(...r)}return e.turnServer={mode:"manual",servers:c},{gatewayInfo:o}}return await ate(e,t,n,r)}const a=await mte(e,t,n,r),c=a.proxyInfo,d=a.gatewayInfo,l={gatewayInfo:d},u=c.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport?e.tcpport:DP.tcpport,udpport:"proxy4"===o?void 0:e.udpport?e.udpport:DP.udpport,username:e.username||DP.username,password:e.password||DP.password,forceturn:"proxy4"!==o,security:"proxy5"===o})));if(r.useP2P){var h;const t=null!==(h=e.uid)&&void 0!==h?h:d.uid,n="glb:".concat(t.toString()),i=await HN(n),r=c.map((e=>({turnServerURL:e.address,tcpport:"proxy3"===o?void 0:e.tcpport||DP.tcpport,udpport:"proxy4"===o?void 0:e.udpport||DP.udpport,username:n,password:i,forceturn:"proxy4"!==o,security:"proxy5"===o})));u.push(...r)}return e.turnServer={mode:"manual",servers:u},SL.debug("[".concat(e.clientId,"] set proxy server: ").concat(e.proxyServer,", mode: ").concat(o)),l}async function dte(e,t,n,i,r){if(xP("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const o=await async function(e,t,n,i,r){const o=[YW.CHOOSE_SERVER,YW.CLOUD_PROXY_FALLBACK],s=await _te(e,i,(s=>"sdpEndpoint"===s.requestType?Hee(s,o,e,r,i,t,n):Xee(ste(ste({},s),{},{serviceIds:o}),e,t,n)));if(!s.gatewayInfo||!s.proxyInfo)throw new YL(wN.UNEXPECTED_ERROR,"missing gateway or proxy response").print();return e.apUrl=s.url,{gatewayInfo:s.gatewayInfo,proxyInfo:await C7(s.proxyInfo,s.gatewayInfo.uid)}}(e,t,n,i,r),s=o.gatewayInfo,a=o.proxyInfo;if("auto"!==e.turnServer.mode)return{gatewayInfo:s};const c=a.map((e=>({turnServerURL:e.address,tcpport:e.tcpport||DP.tcpport,udpport:e.udpport||DP.udpport,username:e.username||DP.username,password:e.password||DP.password,forceturn:!1,security:!0})));return e.turnServer={mode:"manual",servers:c},{gatewayInfo:s}}return{gatewayInfo:await pte(e,r,t,n,i)}}async function lte(e,t,n,i,r){const o=xP("ACCOUNT_REGISTER").slice(0,xP("AJAX_REQUEST_CONCURRENT"));let s=[];s=t.proxyServer?o.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):o.map((e=>"https://".concat(e,"/api/v1")));const a=null==r?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:s});try{const o=await async function(e,t,n,i,r){const o=Date.now(),s={sid:n.sid,opid:10,appid:n.appId,string_uid:t};let a=e[0];const c=await QD((()=>Nee(a+"".concat(-1===a.indexOf("?")?"?":"&","action=stringuid"),{data:s,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}})),((n,i)=>{if(0===n.code){if(n.uid<=0||n.uid>=Math.pow(2,32))throw SL.error("Invalid Uint Uid ".concat(t," => ").concat(n.uid),n),HL.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:wN.INVALID_UINT_UID_FROM_STRING_UID,extend:s}),new YL(wN.INVALID_UINT_UID_FROM_STRING_UID);return HL.reqUserAccount(s.sid,{lts:o,success:!0,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:null,extend:s}),!1}const r=iB(n.code);return r.retry&&(a=e[(i+1)%e.length]),HL.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:n.uid,errorCode:r.desc,extend:s}),r.retry}),((t,n)=>t.code!==wN.OPERATION_ABORTED&&(HL.reqUserAccount(s.sid,{lts:o,success:!1,serverAddr:a,stringUid:s.string_uid,uid:null,errorCode:t.code,extend:s}),a=e[(n+1)%e.length],!0)),r);if(0!==c.code){const e=iB(c.code);throw new YL(wN.UNEXPECTED_RESPONSE,e.desc)}return c}(s,e,t,n,i);return null==r||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),o.uid}catch(e){throw null==r||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[e]},a),e}}async function ute(e,t,n){const i=xP("ACCOUNT_REGISTER");let r=[];r=t.proxyServer?i.map((e=>"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1"))):i.map((e=>"https://".concat(e,"/api/v1")));try{const i=await ite({referenceList:r,asyncMapHandler:i=>async function(e,t,n,i){const r=Date.now(),o={sid:n.sid,opid:10,appid:n.appId,string_uid:t};try{const t=await Nee(e+"".concat(-1===e.indexOf("?")?"?":"&","action=stringuid"),{data:o,cancelToken:i,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(0!==t.code){const e=iB(t.code);throw new YL(wN.UNEXPECTED_RESPONSE,"preload sua error:".concat(e.desc),e)}if(t.uid<=0||t.uid>=Math.pow(2,32))throw new YL(wN.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:r,url:e,req:o,uid:t.uid,elapse:Date.now()-r}}catch(e){throw e}}(i,e,t,n),closeFn:e=>e.code===wN.OPERATION_ABORTED||e.code===wN.UNEXPECTED_RESPONSE&&!e.data.retry});return i}catch(e){throw e}}async function hte(e,t,n){const i=xP("CDS_AP").slice(0,xP("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1"):"https://".concat(t,"/api/v1?action=config"))),r=i.map((i=>function(e,t,n,i){const r=GO(),o={flag:64,cipher_method:0,features:jee(jee(jee(jee(jee({install_id:AP(),device:r.name,system:r.os,system_general:navigator.userAgent,vendor:t.appId,version:wP,cname:t.cname,session_id:t.sid,proxyServer:t.proxyServer,sdk_type:Aee.WEB_RTC,browser_name:r.name,browser_version:r.version,user_agent:navigator.userAgent,channel_name:t.cname},t.stringUid&&{string_uid:t.stringUid}),t.uid&&{uid:t.uid+""}),r.os&&{os_name:r.os}),r.osVersion&&{os_version:r.osVersion}),{},{detail:""})};return QD((()=>Nee(e,{data:o,timeout:1e3,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}})),void 0,(e=>e.code!==wN.OPERATION_ABORTED),i)}(i,e,t,n)));let o=null,s=null,a={};try{o=await tte(r)}catch(e){if(e.code===wN.OPERATION_ABORTED)throw e;s=e}r.forEach((e=>e.cancel()));if(HL.reportApiInvoke(e.sid,{name:zN.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,res:o}}).onSuccess(),o&&o.test_tags)try{a=function(e){if(!e.test_tags)return{};const t=e.test_tags,n=Object.keys(t),i={};return n.forEach((e=>{var n;const r=zS(n=e.slice(4)).call(n),o=JSON.parse(t[e]),s=o[1];i[r]={tag:o[0]||"",value:s}})),i}(o)}catch(e){}return a}async function pte(e,t,n,i,r){return _te(e,r,(o=>"sdpEndpoint"===o.requestType?Hee(o,YW.CHOOSE_SERVER,e,t,r,n,i):Yee(o,e,n,i)))}async function _te(e,t,n){let i=null;const r=[],o=async()=>{const i=[...xP("SDP_ENDPOINT_DOMAIN").slice(0,1).map((e=>({url:"https://".concat(e,"/api/v3/transpond/webrtc?v=3"),areaCode:Dee(),requestType:"sdpEndpoint"}))),...xP("WEBCS_DOMAIN").slice(0,1).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:Dee(),requestType:"ap"})))],o=t.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:i.map((e=>e.url))}),s=await nte({fragementLength:i.length,referenceList:i,asyncMapHandler:t=>(SL.debug("[".concat(e.clientId,"] Connect to primary choose_server:"),t.url),n(t)),allFailedhandler:e=>{throw t.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},o),e[0]},promisesCollector:r});return t.recordJoinChannelService({endTs:Date.now(),status:"success"},o),s},s=async()=>{if(await LD(1e3),null!==i)return i;const o=xP("WEBCS_DOMAIN_BACKUP_LIST").map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:Dee(),requestType:"ap"}))),s=t.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:o.map((e=>e.url))}),a=await nte({fragementLength:xP("FRAGEMENT_LENGTH"),referenceList:o,asyncMapHandler:t=>(SL.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),t.url),n(t)),allFailedhandler:e=>{throw t.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:r});return t.recordJoinChannelService({endTs:Date.now(),status:"success"},s),a};try{return i=await tte([o(),s()]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),i}catch(e){throw e[0]}}async function Ete(e,t){const n=xP("WEBCS_DOMAIN").concat(xP("WEBCS_DOMAIN_BACKUP_LIST")).map((e=>({url:"https://".concat(e,"/api/v2/transpond/webrtc?v=2"),areaCode:Dee(),serviceIds:[YW.CHOOSE_SERVER,YW.CLOUD_PROXY_FALLBACK]})));try{const i=await ite({referenceList:n,asyncMapHandler:n=>async function(e,t,n){let i,r=e.url,o=e.areaCode,s=e.serviceIds;const a=Date.now(),c=KC(qee(t,o,s),2),d=c[0],l=c[1];let u=pD.networkState;try{u&&pD.networkState===aD.OFFLINE&&pD.onlineWaiter&&await cp.race([pD.onlineWaiter,LD(ZD.maxRetryTimeout)]),u=pD.networkState;const e=await Nee(r,{data:d,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0,!0),t=e.data;i="1"===e.headers.http3?1:-1;const o=e=>{const t=[];if(e.response_body.forEach((n=>{const i=n.buffer.code;if(23===n.uri&&0===i&&!n.buffer.edges_services)if(4194310===n.buffer.flag)n.buffer.edges_services=[];else{const i={error:new YL(wN.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:xP("NO_EDGES_RETRY"),csIp:e.detail[502]}),flag:n.buffer.flag};t.push(i)}if(0!==i){const r=iB(i),o={error:new YL(wN.CAN_NOT_GET_GATEWAY_SERVER,r.desc,{desc:r.desc,retry:r.retry,csIp:e.detail[502]}),flag:n.buffer.flag};4194310===n.buffer.flag?SL.warning(o.error.toString()):t.push(o)}})),t.length)throw new YL(wN.CAN_NOT_GET_GATEWAY_SERVER,t.map((e=>"flag: ".concat(e.flag,", message: ").concat(e.error.message))).join(" | "),{retry:!!t.find((e=>e.error.data.retry)),csIp:e.detail[502],desc:[...new Set(t.map((e=>{var t;return null==e||null===(t=e.error)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.desc})).filter((e=>!!e)))]})};o(t);const s=y7(t,YW.CHOOSE_SERVER),c=y7(t,YW.CLOUD_PROXY_FALLBACK);return zee(s),{gatewayInfo:S7(s,r),proxyInfo:c,opid:l,requestTime:a,url:r,isHttp3:i,elapse:Date.now()-a}}catch(e){throw e}}(n,e,t),closeFn:e=>e.code===wN.OPERATION_ABORTED||e.code===wN.CAN_NOT_GET_GATEWAY_SERVER&&!e.data.retry});return i}catch(e){throw e}}async function mte(e,t,n,i){const r=xP("PROXY_SERVER_TYPE3"),o=(e,t,n)=>{let i=n||r;return Array.isArray(i)&&(i=t%2==0&&r[1]||r[0]),"https://".concat(i,"/ap/?url=").concat(e)};let s=null;const a=[],c=async()=>{const r=xP("WEBCS_DOMAIN").slice(0,xP("AJAX_REQUEST_CONCURRENT")).map(((t,n)=>{let i;return i="disabled"===e.cloudProxyServer&&e.proxyServer?o("".concat(t,"/api/v2/transpond/webrtc?v=2"),n,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):o("".concat(t,"/api/v2/transpond/webrtc?v=2"),n),{url:i,areaCode:Dee(),serviceIds:[YW.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?YW.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?YW.CLOUD_PROXY:YW.CLOUD_PROXY_FALLBACK]}})),s=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),c=await nte({fragementLength:xP("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:i=>(SL.debug("[".concat(e.clientId,"] Connect to choose_server:"),i.url),Xee(i,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},s),e[0]},promisesCollector:a});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},s),c},d=async()=>{if(await LD(1e3),null!==s)return s;const r=xP("WEBCS_DOMAIN_BACKUP_LIST").map(((t,n)=>{let i;return i="disabled"===e.cloudProxyServer&&e.proxyServer?o("".concat(t,"/api/v2/transpond/webrtc?v=2"),n,e.proxyServer):"disabled"===e.cloudProxyServer||"fallback"===e.cloudProxyServer?"https://".concat(t,"/api/v2/transpond/webrtc?v=2"):o("".concat(t,"/api/v2/transpond/webrtc?v=2"),n),{url:i,areaCode:Dee(),serviceIds:[YW.CHOOSE_SERVER,"proxy5"===e.cloudProxyServer?YW.CLOUD_PROXY_5:"proxy3"===e.cloudProxyServer||"proxy4"===e.cloudProxyServer?YW.CLOUD_PROXY:YW.CLOUD_PROXY_FALLBACK]}})),c=i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:r.map((e=>e.url))}),d=await nte({fragementLength:xP("FRAGEMENT_LENGTH"),referenceList:r,asyncMapHandler:i=>(SL.debug("[".concat(e.clientId,"] Connect to backup choose_server:"),i.url),Xee(i,e,t,n)),allFailedhandler:e=>{throw i.recordJoinChannelService({endTs:Date.now(),status:"error",errors:e},c),e[0]},promisesCollector:a});return i.recordJoinChannelService({endTs:Date.now(),status:"success"},c),d};let l,u,h;try{var p=await tte([c(),d()]);l=p.gatewayInfo,u=p.proxyInfo,h=p.url}catch(e){throw e[0]}if(a.length&&a.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),!l||!u)throw new YL(wN.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(e.apUrl=h,"disabled"!==e.cloudProxyServer&&Array.isArray(r)&&h){const t=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];Ui(r).call(r,t)&&(e.proxyServer=t,SL.setProxyServer(t),HL.setProxyServer(t))}return s={gatewayInfo:l,proxyInfo:await C7(u,l.uid)},s}async function fte(e,t,n){const i=xP("UAP_AP").slice(0,xP("AJAX_REQUEST_CONCURRENT")).map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v1?action=uap"):"https://".concat(t,"/api/v1?action=uap"))),r=i.map((i=>function(e,t,n,i){const r={command:"convergeAllocateEdge",sid:t.sid,appId:t.appId,token:t.token,ts:Date.now(),version:wP,cname:t.cname,uid:t.uid.toString(),requestId:Kee,seq:Kee};Kee+=1;const o={service_name:"tele_channel",json_body:JSON.stringify(r)};return QD((async()=>{const t=await Nee(e,{data:o,cancelToken:n,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(0!==t.code){const e=new YL(wN.UNEXPECTED_RESPONSE,"cross channel ap error, code"+t.code,{retry:!0});throw SL.error(e.toString()),e}const i=JSON.parse(t.json_body);if(200!==i.code){const e=new YL(wN.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(i.code,", reason: ").concat(i.reason));throw SL.error(e.toString()),e}if(!i.servers||0===i.servers.length){const e=new YL(wN.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw SL.error(e.toString()),e}return{vid:i.vid,workerToken:i.workerToken,addressList:(xP("CHANNEL_MEDIA_RELAY_SERVERS")||i.servers).map((e=>"wss://".concat(e.address.replace(/\./g,"-"),".").concat(xP("WORKER_DOMAIN"),":").concat(e.wss)))}}),void 0,(e=>!!(e.code!==wN.OPERATION_ABORTED&&e.code!==wN.UNEXPECTED_RESPONSE||e.data&&e.data.retry)),i)}(i,e,t,n)));try{const e=await tte(r);return r.forEach((e=>e.cancel())),e}catch(e){throw e[0]}}async function gte(e,t,n){let i=null;const r=[],o=async o=>{const s=xP(o?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map((t=>e.proxyServer?"https://".concat(e.proxyServer,"/ap/?url=").concat(t+"/api/v2/transpond/webrtc?v=2"):"https://".concat(t,"/api/v2/transpond/webrtc?v=2")));return o&&(await LD(1e3),null!==i)?i:await nte({fragementLength:xP("FRAGEMENT_LENGTH"),referenceList:s,asyncMapHandler:i=>(SL.debug("[".concat(e.clientId,"] update ticket, Connect to ").concat(o?"backup":""," choose_server:"),i),function(e,t,n,i){const r=KC($ee(t,[YW.CHOOSE_SERVER]),1)[0];let o=pD.networkState;return QD((async()=>{o&&pD.networkState===aD.OFFLINE&&pD.onlineWaiter&&await cp.race([pD.onlineWaiter,LD(i&&i.maxRetryTimeout||ZD.maxRetryTimeout)]),o=pD.networkState;const t=await Nee(e,{data:r,cancelToken:n,headers:{"Content-Type":"multipart/form-data;"}},!0);return Zee(t,e)}),(()=>!1),(e=>e.code!==wN.OPERATION_ABORTED&&(e.code===wN.UPDATE_TICKET_FAILED?e.data.retry:(SL.warning("[".concat(t.clientId,"] update ticket network error, retry"),e),!0))),i)}(i,e,t,n)),allFailedhandler:e=>{throw e[0]},promisesCollector:r})};try{return i=await tte([o(!1),o(!0)]),r.length&&r.forEach((e=>e.cancel&&"function"==typeof e.cancel&&e.cancel())),i}catch(e){throw e[0]}}const Ste="/ping",Tte="/api/v1?action=stringuid",Rte=JSON.stringify({sid:"",opid:10,appid:"",string_uid:""}),vte=["oceania","south-america","africa"],yte=55e3,Cte=1e4,bte=2147483647;function Ite(e){const t=Number(e);return!Number.isFinite(t)||t<Cte?yte:Math.min(t,bte)}function Ate(e,t){return"sua"===t?"".concat(e).concat(Tte):"".concat(e).concat(Ste)}let wte=new class{constructor(){zA(this,"hasClient",!1),zA(this,"activeJoinClientIds",new Set),zA(this,"timer",void 0),zA(this,"lastTickAt",void 0),zA(this,"pendingOrigins",new Set),zA(this,"visibilityListenerAttached",!1),zA(this,"onVisibilityChange",(()=>{Ote((()=>{"visible"===document.visibilityState?this.scheduleNext():this.clearTimer()}))}))}onCreateClient(){this.hasClient||(this.hasClient=!0,this.scheduleNext())}syncConfig(){this.scheduleNext()}onJoin(e){this.activeJoinClientIds.has(e)||(this.activeJoinClientIds.add(e),this.clearTimer())}onLeave(e){!this.activeJoinClientIds.delete(e)||this.activeJoinClientIds.size>0||this.scheduleNext()}dispose(){this.clearTimer(),this.pendingOrigins.clear(),this.lastTickAt=void 0,this.hasClient=!1,this.activeJoinClientIds.clear(),this.removeVisibilityListener()}scheduleNext(){this.clearTimer();const e=this.readConfig();if(!e.enabled)return void this.removeVisibilityListener();if(!this.hasClient||this.activeJoinClientIds.size>0)return;if(this.ensureVisibilityListener(),!this.isPageVisible())return;if(void 0!==this.lastTickAt&&!e.keepalive)return void this.removeVisibilityListener();const t=Date.now(),n=void 0===this.lastTickAt?0:Math.max(0,Math.min(this.lastTickAt+e.intervalMs-t,bte));this.timer=window.setTimeout((()=>{this.timer=void 0,Ote((()=>this.runTick()))}),n)}runTick(){const e=this.readConfig();if(!(this.activeJoinClientIds.size>0)&&this.hasClient&&e.enabled&&this.isPageVisible()){this.lastTickAt=Date.now();try{this.buildPlans(e).forEach((e=>this.executePlan(e)))}finally{this.scheduleNext()}}else this.scheduleNext()}executePlan(e){try{if("report"===e.mode)return void this.reportAttempt(e);if(this.pendingOrigins.has(e.origin))return;const t=fetch(e.url,function(e){var t;return Ui(t=e.targets).call(t,"sua")?{method:"POST",mode:"cors",credentials:"omit",headers:{"Content-Type":"application/json","X-Packet-Service-Type":"0","X-Packet-URI":"72"},body:Rte}:{method:"HEAD",mode:"no-cors",credentials:"omit",cache:"no-store"}}(e));this.pendingOrigins.add(e.origin),t.then((()=>this.pendingOrigins.delete(e.origin)),(()=>this.pendingOrigins.delete(e.origin))),this.reportAttempt(e)}catch(t){SL.debug("createClient preconnect failed",e.origin,t)}}reportAttempt(e){HL.reportCreateClientPreconnect({targets:e.targets,mode:e.mode,origin:e.origin})}buildPlans(e){const t=[{target:"sdpendpoint",domains:xP("SDP_ENDPOINT_DOMAIN")},{target:"sua",domains:xP("ACCOUNT_REGISTER")}],n=new Map;return t.forEach((t=>{let i=t.target;const r=function(e){if(!Array.isArray(e))return;return e.find((e=>"string"==typeof e&&e.length>0))||void 0}(t.domains);if(!r)return;const o=function(e){try{const t=new xg(Ui(e).call(e,"://")?e:"https://".concat(e));return"https:"===t.protocol?t.origin:void 0}catch(e){return}}(r);if(!o)return;if("sua"===i&&vte.some((e=>Ui(o).call(o,e))))return;const s=n.get(o);var a;if(s)return Ui(a=s.targets).call(a,i)||s.targets.push(i),void("request"===e.mode&&"sua"===i&&(s.url=Ate(o,i)));n.set(o,{origin:o,url:Ate(o,i),targets:[i],mode:e.mode})})),Array.from(fp(n).call(n))}readConfig(){return{enabled:!0===xP("ENABLE_CREATE_CLIENT_PRECONNECT"),mode:(e=xP("CREATE_CLIENT_PRECONNECT_MODE"),"request"===e?"request":"report"),keepalive:!0===xP("CREATE_CLIENT_PRECONNECT_KEEPALIVE"),intervalMs:Ite(xP("CREATE_CLIENT_PRECONNECT_INTERVAL_MS"))};var e}isPageVisible(){return"undefined"==typeof document||"visible"===document.visibilityState}ensureVisibilityListener(){this.visibilityListenerAttached||"undefined"==typeof document||(document.addEventListener("visibilitychange",this.onVisibilityChange),this.visibilityListenerAttached=!0)}removeVisibilityListener(){this.visibilityListenerAttached&&"undefined"!=typeof document&&document.removeEventListener("visibilitychange",this.onVisibilityChange),this.visibilityListenerAttached=!1}clearTimer(){void 0!==this.timer&&(window.clearTimeout(this.timer),this.timer=void 0)}};function Ote(e){try{e()}catch(e){SL.debug("createClient preconnect action failed",e)}}function Nte(e){Ote((()=>wte.onLeave(e)))}function Dte(e){let t=!0;return function(e){Ote((()=>wte.onJoin(e)))}(e),{markJoined:()=>{t=!1},releaseIfNotJoined:()=>{t&&(t=!1,Nte(e))}}}function Pte(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Lte(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Pte(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Pte(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class kte extends YN{get isSuccess(){return!!this.configs}constructor(e,t){super(),zA(this,"configs",void 0),zA(this,"store",void 0),zA(this,"joinInfo",void 0),zA(this,"cancelToken",void 0),zA(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),zA(this,"interval",void 0),zA(this,"mutex",void 0),zA(this,"mutableParamsRead",!1),zA(this,"configCache",{}),zA(this,"limit_bitrate",void 0),this.mutex=new JD("config-distribute",e),this.store=t}startGetConfigDistribute(e,t){this.joinInfo=e,this.cancelToken=t,this.interval&&this.stopGetConfigDistribute(),xP("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval((()=>{this.updateConfigDistribute()}),xP("CONFIG_DISTRIBUTE_INTERVAL")))}stopGetConfigDistribute(){this.interval&&clearInterval(this.interval),this.interval=void 0,this.joinInfo=void 0,this.cancelToken=void 0,this.configs=void 0,this.limit_bitrate=void 0}async awaitConfigDistributeComplete(){if(!this.mutex.isLocked)return;(await this.mutex.lock())()}async updateConfigDistribute(){if(!this.mutableParamsRead){this.mutableParamsRead=!0;HL.reportApiInvoke(null,{options:void 0,name:zN.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:ZN.TRACER}).onSuccess(JSON.stringify(BP))}if(!this.joinInfo||!this.cancelToken||!this.retryConfig)return void SL.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const t=await this.mutex.lock();try{e=await hte(this.joinInfo,this.cancelToken,this.retryConfig),SL.debug("[config-distribute] get config distribute",JSON.stringify(e));const n=function(e){var t;const n=t_(t=Object.keys(e).filter((e=>/^webrtc_ng_global_parameter/.test(e)))).call(t);for(let t=0;t<n.length;t++)for(let i=n.length-1;i>t;i--){const t=n[i],r=e[t].value;if("number"==typeof r.__priority){const o=r.__priority,s=n[i-1],a=e[s].value;if("number"==typeof a.__priority){if(!(o>a.__priority))continue;{const e=t;n[i]=n[i-1],n[i-1]=e}}else{const e=t;n[i]=n[i-1],n[i-1]=e}}}const i=Date.now(),r={};return n.forEach((t=>{const n=e[t].value.__expires;n&&n<=i||(r[t]=e[t])})),r}(e);this.cacheGlobalParameterConfig(n),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=n}catch(e){const t=new YL(wN.NETWORK_RESPONSE_ERROR,e);SL.warning("[config-distribute] ".concat(t.toString()))}finally{t()}}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){LF(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(PF.UPDATE_BITRATE_LIMIT,e):this.emit(PF.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&Lte({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{const t={},n=Object.keys(e),i=[];n.forEach((n=>{const r=e[n].value;t[n]=r;const o=r.__id;if(o&&this.configCache[n]&&this.configCache[n].__id===o)return;const s=r.__type,a=e[n].value,c=e[n].tag;let d=0;s?s===FP.REALTIME&&(d=1):Object.keys(a).some((e=>Object.prototype.hasOwnProperty.call(MP,e)||!Lx()&&Object.prototype.hasOwnProperty.call(PP,e)?(d=1,!0):void 0)),i.push({tag:c,isApplied:d,feature:n,params:JSON.stringify(r)})})),i.forEach((e=>{let t=e.tag,n=e.feature,i=e.params,r=e.isApplied;this.store.sessionId&&HL.abTest(this.store.sessionId,{intSucc:1,isApplied:r,tag:t,feature:n,params:i,cid:this.store.cid,uid:this.store.intUid})})),this.configCache=t}catch(e){SL.debug("handleABTestConfigDistribute error",e)}}cacheGlobalParameterConfig(e){const t=function(e){const t={};return Object.keys(e).forEach((n=>{const i=e[n].value,r=i.__expires,o=i.__type;Object.keys(i).forEach((e=>{"__id"===e||"__type"===e||"__priority"===e||"__expires"===e||Object.prototype.hasOwnProperty.call(t,e)||(t[e]=Lte(Lte({value:i[e]},r&&{expires:r}),o&&{type:o}))}))})),t}(e);try{var n;const i=null===(n=t.LIMIT_BITRATE)||void 0===n?void 0:n.value;if(delete t.LIMIT_BITRATE,i&&LF(i)&&this.handleBitrateLimit(i),this.limit_bitrate=i,this.handleGlobalParameterConfig(t),this.handleABTestConfigDistribute(e),function(e){try{const t=Date.now();Object.keys(e).forEach((n=>{const i=e[n],r=i.value,o=i.type,s=i.expires;s&&s<=t||((o===FP.REALTIME||Object.prototype.hasOwnProperty.call(MP,n))&&(BP[n]=r,UP[n]=r,SL.debug("Update realtime parameters from config distribute",n,r)),o||Lx()||!Object.prototype.hasOwnProperty.call(PP,n)||(BP[n]=r,UP[n]=r,SL.debug("Update gateway parameters from config distribute",n,r)))}))}catch(t){SL.error("Error update config immediately: ".concat(e),t.message)}}(t),function(e){try{var t;if(!xP("ENABLE_CONFIG_RESTORE"))return!1;const n=ML(e),i=window.localStorage.getItem(NL);if(!i)return!1;const r=JSON.parse(i),o=xP("BLOCKED_CONFIG_MAX_TIME");return Date.now()-r.timestamp>o?(WL(),!1):Ui(t=r.configHashes).call(t,n)}catch(e){return SL.debug("[error] ".concat(wL," error checking blocked config:"),e),!1}}(t))return SL.debug("[warning] [config-distribute] blocked config detected and skipped"),void HL.reportAlarm(this.store.sessionId||null,{type:yL.CONFIG_DISTRIBUTE,status:vL.RECOVER,message:"Blocked config detected and skipped"});!function(e){try{const t=ML(e),n=UL();if(n.currentConfigHash&&n.currentConfigHash===t)return VL({currentConfigHash:t,configVerified:!0}),BL(),WL(),void SL.debug("".concat(wL," config verified as safe, skip further checks"));VL({currentConfigHash:t,configVerified:!1}),BL(),WL()}catch(e){SL.debug("[error] ".concat(wL," error on config applied:"),e)}}(t),Ote((()=>wte.syncConfig()));const r=JSON.stringify(t),o=window.btoa(r);window.localStorage.setItem("websdk_ng_global_parameter",o),SL.debug("Caching global parameters ".concat(r))}catch(e){SL.error("Error caching global parameters:",e.message)}}handleGlobalParameterConfig(e){try{const t=Date.now();Object.keys(e).forEach((n=>{switch(n){case"CLIENT_ROLE_OPTIONS":if(Object.prototype.hasOwnProperty.call(UP,n)){const i=e[n],r=i.value,o=i.expires;if(o&&o<=t)return;WD(UP[n],r)||(BP[n]=r,UP[n]=r,this.emit(PF.UPDATE_CLIENT_ROLE_OPTIONS,r),SL.debug("Updating client role options: ".concat(JSON.stringify(r))))}break;case"REMOTE_VIDEO_STREAM_TYPE":if(Object.prototype.hasOwnProperty.call(UP,n)){var i;const r=e[n],o=r.value,s=r.expires;if(s&&s<=t)return;"number"==typeof o&&Ui(i=[0,1,4,5,6,7,8,9]).call(i,o)&&(BP[n]={value:o},UP[n]=o,this.emit(PF.UPDATE_REMOTE_VIDEO_STREAM_TYPE,o),SL.debug("Updating client remote stream type: ".concat(JSON.stringify(o))))}break;case"ENABLE_FORCE_HLS":if(Object.prototype.hasOwnProperty.call(UP,n)){const i=e[n],r=i.value,o=i.expires;if(o&&o<=t)return;WD(UP[n],r)||(BP[n]=r,UP[n]=r,this.emit(PF.FALLBACK_TO_HLS,r),SL.debug("Updating enable force hls: ".concat(JSON.stringify(r))))}break;case"VOS_CONFIGURE":if(Object.prototype.hasOwnProperty.call(UP,n)){const i=e[n],r=i.value,o=i.expires;if(o&&o<=t)return;WD(UP[n],r)||(BP[n]=r,UP[n]=r,this.emit(PF.UPDATE_VOS_CONFIGURE,r),SL.debug("Updating vos configure: ".concat(JSON.stringify(r))))}}}))}catch(e){SL.error("Error handling global parameter config:",e.message)}}}class Mte extends YN{constructor(){super(...arguments),zA(this,"resultStorage",new Map)}setLocalAudioStats(e,t,n){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(n,t)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(n,t))}setLocalVideoStats(e,t,n){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(n,t)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(n,t)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(n)),!t.muted&&this.record("VIDEO_ENCODE_FAILED",e,this.checResolutionSent(n))}setRemoteAudioStats(e,t){const n=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",n,this.checkAudioOutputLevel(t))}setRemoteVideoStats(e,t){const n=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",n,this.checkVideoDecode(t))}record(e,t,n){if(xP("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const i=this.resultStorage.get(e);if(!i)return;i.result.push(n);const r="VIDEO_ENCODE_FAILED"===e?xP("ENCODE_EXCEPTION_TIMES"):5;if(i.result.length>=r){var o;const n=Ui(o=i.result).call(o,!0);i.isPrevNormal&&!n&&this.emit("exception",Ute[e],e,t),!i.isPrevNormal&&n&&this.emit("exception",Ute[e]+2e3,e+"_RECOVER",t),i.isPrevNormal=n,i.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&0===e.receiveLevel)}checkAudioInputLevel(e,t){return t instanceof OU&&!t.isActive||(!!t.muted||0!==e.sendVolumeLevel)}checkFramerateInput(e,t){let n=null;t._encoderConfig&&t._encoderConfig.frameRate&&(n=T7(t._encoderConfig.frameRate));const i=e.captureFrameRate;return!n||!i||!(n>10&&i<5||n<10&&n>=5&&i<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checResolutionSent(e){var t;return!(!e.codecType||Ui(t=xP("ENCODE_EXCEPTION_VALIDATE_CODEC")).call(t,e.codecType.toLocaleLowerCase()))||(!e.captureFrameRate||0!==e.sendFrameRate||0!==e.sendResolutionWidth||0!==e.sendResolutionHeight)}checkSendVideoBitrate(e,t){return!!t.muted||0!==e.sendBitrate}checkSendAudioBitrate(e,t){return t instanceof OU&&!t.isActive||(!!t.muted||0!==e.sendBitrate)}checkVideoDecode(e){return 0===e.receiveBitrate||0!==e.decodeFrameRate}}const Ute={FRAMERATE_INPUT_TOO_LOW:1001,FRAMERATE_SENT_TOO_LOW:1002,SEND_VIDEO_BITRATE_TOO_LOW:1003,RECV_VIDEO_DECODE_FAILED:1005,AUDIO_INPUT_LEVEL_TOO_LOW:2001,AUDIO_OUTPUT_LEVEL_TOO_LOW:2002,SEND_AUDIO_BITRATE_TOO_LOW:2003,VIDEO_ENCODE_FAILED:2004};const Vte=new class{markSubscribeStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/subscribe-").concat(t))}markPublishStart(e,t){performance.mark("agora-web-sdk/".concat(e,"/publish-").concat(t))}measureFromSubscribeStart(e,t){const n=performance.getEntriesByName("agora-web-sdk/".concat(e,"/subscribe-").concat(t));if(n.length>0){const e=n[n.length-1];return Math.round(performance.now()-e.startTime)}return 0}measureFromPublishStart(e,t){const n=performance.getEntriesByName("agora-web-sdk/".concat(e,"/publish-").concat(t));if(n.length>0){const e=n[n.length-1];return Math.round(performance.now()-e.startTime)}return 0}};function xte(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Fte(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?xte(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xte(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class Bte{constructor(e){zA(this,"store",void 0),zA(this,"onStatsException",void 0),zA(this,"onUploadPublishDuration",void 0),zA(this,"onStatsChanged",void 0),zA(this,"onVideoCodecChanged",void 0),zA(this,"localStats",new Map),zA(this,"remoteStats",new Map),zA(this,"updateStatsInterval",void 0),zA(this,"trafficStats",void 0),zA(this,"trafficStatsPeerList",[]),zA(this,"uplinkStats",void 0),zA(this,"exceptionMonitor",void 0),zA(this,"p2pChannel",void 0),zA(this,"scalabilityMode",gP.L1T1),zA(this,"updateStats",(()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))})),this.store=e,this.exceptionMonitor=new Mte,this.exceptionMonitor.on("exception",((e,t,n)=>{this.onStatsException&&this.onStatsException(e,t,n)}))}startUpdateStats(){this.updateStatsInterval||(this.updateStatsInterval=window.setInterval(this.updateStats,1e3))}stopUpdateStats(){this.updateStatsInterval&&(window.clearInterval(this.updateStatsInterval),this.updateStatsInterval=void 0)}reset(){this.localStats=new Map,this.remoteStats=new Map,this.trafficStats=void 0,this.trafficStatsPeerList=[],this.uplinkStats=void 0}getLocalAudioTrackStats(){return this.localStats.get(BF.LocalAudioTrack)||Fte({},Nk)}getLocalVideoTrackStats(){return this.localStats.get(BF.LocalVideoTrack)||Fte({},Dk)}getRemoteAudioTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const n=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return n&&(t.publishDuration=n.B_ppad+(Date.now()-this.trafficStats.timestamp)),t},n={};if(e){var i;const r=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.audioStats;r&&(n[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let i=KC(e,2),r=i[0],o=i[1].audioStats;o&&(n[r]=t(r,o))}));return n}getRemoteNetworkQualityStats(e){const t={};if(e){var n;const i=null===(n=this.remoteStats.get(e))||void 0===n?void 0:n.networkStats;i&&(t[e]=i)}else Array.from(this.remoteStats.entries()).forEach((e=>{let n=KC(e,2),i=n[0],r=n[1].networkStats;r&&(t[i]=r)}));return t}getNetworkQuality(){let e=0,t=0;return this.trafficStats&&(e=v7(this.trafficStats.B_unq),t=v7(this.trafficStats.B_dnq)),{uplinkNetworkQuality:e,downlinkNetworkQuality:t}}getRemoteVideoTrackStats(e){const t=(e,t)=>{if(!this.trafficStats)return t;const n=this.trafficStats.peer_delay.find((t=>t.peer_uid===e));return n&&(t.publishDuration=n.B_ppvd+(Date.now()-this.trafficStats.timestamp)),t},n={};if(e){var i;const r=null===(i=this.remoteStats.get(e))||void 0===i?void 0:i.videoStats;r&&(n[e]=t(e,r))}else Array.from(this.remoteStats.entries()).forEach((e=>{let i=KC(e,2),r=i[0],o=i[1].videoStats;o&&(n[r]=t(r,o))}));return n}getRTCStats(){let e=0,t=0,n=0,i=0;const r=this.localStats.get(BF.LocalAudioTrack);r&&(e+=r.sendBytes,t+=r.sendBitrate);const o=this.localStats.get(BF.LocalVideoTrack);o&&(e+=o.sendBytes,t+=o.sendBitrate);const s=this.localStats.get(BF.LocalVideoLowTrack);s&&(e+=s.sendBytes,t+=s.sendBitrate),this.remoteStats.forEach((e=>{let t=e.audioStats,r=e.videoStats;t&&(n+=t.receiveBytes,i+=t.receiveBitrate),r&&(n+=r.receiveBytes,i+=r.receiveBitrate)}));let a=1;return this.trafficStats&&(a+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:a,SendBitrate:t,SendBytes:e,RecvBytes:n,RecvBitrate:i,OutgoingAvailableBandwidth:this.uplinkStats?this.uplinkStats.B_uab/1e3:0,RTT:this.trafficStats?2*this.trafficStats.B_acd:0}}addLocalStats(e){this.localStats.set(e,void 0)}removeLocalStats(e){e?this.localStats.delete(e):this.localStats.clear()}addRemoteStats(e){this.remoteStats.set(e,{})}removeRemoteStats(e){e?this.remoteStats.delete(e):this.remoteStats.clear()}addP2PChannel(e){this.p2pChannel=e}updateTrafficStats(e){e.peer_delay=e.peer_delay.filter((e=>void 0!==e.B_ppad||void 0!==e.B_ppvd));e.peer_delay.filter((e=>-1===this.trafficStatsPeerList.indexOf(e.peer_uid))).forEach((e=>{var t;const n=null===(t=this.p2pChannel)||void 0===t?void 0:t.getRemoteMedia(e.peer_uid),i=null!=n&&n.videoSSRC?Vte.measureFromSubscribeStart(this.store.clientId,n.videoSSRC):0,r=null!=n&&n.audioSSRC?Vte.measureFromSubscribeStart(this.store.clientId,n.audioSSRC):0;void 0!==e.B_ppad&&void 0!==e.B_ppvd&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(e.peer_uid,e.B_ppad,e.B_ppvd,i>r?i:r),this.trafficStatsPeerList.push(e.peer_uid))})),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&SL.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,t,n){if(!e)return!1;const i=!!n&&t.framesDecodeFreezeTime>n.framesDecodeFreezeTime,r=!n||t.framesDecodeCount>n.framesDecodeCount;return i||!r}static isRemoteAudioFreeze(e){return!!e&&e._isFreeze()}isLocalVideoFreeze(e){return!(!e.inputFrame||!e.sentFrame)&&(e.inputFrame.frameRate>5&&e.sentFrame.frameRate<3)}updateLocalStats(e){Array.from(this.localStats.entries()).forEach((t=>{let n=KC(t,2),i=n[0],r=n[1];switch(i){case BF.LocalVideoTrack:case BF.LocalVideoLowTrack:{const t=r,n=Fte({},Dk),a=e.getStats(),c=e.getLocalMedia(i);if(a){const i=a.videoSend.find((e=>e.ssrc===(null==c?void 0:c.ssrcs[0].ssrcId)));if(i){const r=e.getLocalVideoSize(),s=e.getEncoderConfig(BF.LocalVideoTrack);var o;if("H264"===i.codec||"H265"===i.codec||"VP8"===i.codec||"VP9"===i.codec||"AV1X"===i.codec||"AV1"===i.codec)if(n.codecType=i.codec,(null==t?void 0:t.codecType)!==i.codec)null===(o=this.onVideoCodecChanged)||void 0===o||o.call(this,i.codec.toLocaleLowerCase());n.sendBytes=i.bytes,n.sendBitrate=t?8*Math.max(0,n.sendBytes-t.sendBytes):0,i.inputFrame?(n.captureFrameRate=i.inputFrame.frameRate,n.captureResolutionHeight=i.inputFrame.height,n.captureResolutionWidth=i.inputFrame.width):r&&(n.captureResolutionWidth=r.width,n.captureResolutionHeight=r.height),i.sentFrame?(n.sendFrameRate=i.sentFrame.frameRate,n.sendResolutionHeight=i.sentFrame.height,n.sendResolutionWidth=i.sentFrame.width):r&&(n.sendResolutionWidth=r.width,n.sendResolutionHeight=r.height),i.avgEncodeMs&&(n.encodeDelay=i.avgEncodeMs),s&&s.bitrateMax?n.targetSendBitrate=1e3*s.bitrateMax:i.targetBitrate&&(n.targetSendBitrate=i.targetBitrate),n.sendPackets=i.packets,n.sendPacketsLost=i.packetsLost,n.sendJitterMs=i.jitterMs,n.sendRttMs=i.rttMs,n.totalDuration=t?t.totalDuration+1:1,n.totalFreezeTime=t?t.totalFreezeTime:0,this.isLocalVideoFreeze(i)&&(n.totalFreezeTime+=1),i.scalabilityMode&&this.scalabilityMode!==i.scalabilityMode&&(SL.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(i.scalabilityMode)),this.scalabilityMode=i.scalabilityMode)}this.trafficStats&&(n.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var s;if(this.localStats.set(i,n),(null==t?void 0:t.sendResolutionWidth)!==n.sendResolutionWidth||(null==t?void 0:t.sendResolutionHeight)!==n.sendResolutionHeight)null===(s=this.onStatsChanged)||void 0===s||s.call(this,"resolution",{width:n.sendResolutionWidth,height:n.sendResolutionHeight});n&&c&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,c.track,n);break}case BF.LocalAudioTrack:{const t=r,n=Fte({},Nk),o=e.getStats(),s=e.getLocalMedia(i);if(o){const i=o.audioSend.find((e=>e.ssrc===(null==s?void 0:s.ssrcs[0].ssrcId)));if(i){if("opus"!==i.codec&&"aac"!==i.codec&&"PCMU"!==i.codec&&"PCMA"!==i.codec&&"G722"!==i.codec||(n.codecType=i.codec),i.inputLevel)n.sendVolumeLevel=Math.round(32767*i.inputLevel);else{const t=e.getLocalAudioVolume();t&&(n.sendVolumeLevel=Math.round(32767*t))}n.sendBytes=i.bytes,n.sendPackets=i.packets,n.sendPacketsLost=i.packetsLost,n.sendJitterMs=i.jitterMs,n.sendRttMs=i.rttMs,n.sendBitrate=t?8*Math.max(0,n.sendBytes-t.sendBytes):0}}this.trafficStats&&(n.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(BF.LocalAudioTrack,n),n&&s&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,s.track,n);break}}}))}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach((t=>{var n,i;let r=KC(t,2),o=r[0],s=r[1],a=s.videoStats;const c=s.audioStats,d=a,l=s.videoPcStats,u=Fte({},Pk),h=Fte({},kk),p=Fte({},Lk),_=e.getRemoteMedia(o),E=_.audioTrack,m=_.videoTrack,f=_.audioSSRC,g=_.videoSSRC;let S;S=this.store.useP2P?e.getStats(!0):e.getStats();const T=null===(n=S)||void 0===n?void 0:n.audioRecv.find((e=>e.ssrc===f)),R=null===(i=S)||void 0===i?void 0:i.videoRecv.find((e=>e.ssrc===g)),v=this.trafficStats&&this.trafficStats.peer_delay.find((e=>e.peer_uid===o));if(T&&("opus"!==T.codec&&"aac"!==T.codec&&"PCMU"!==T.codec&&"PCMA"!==T.codec&&"G722"!==T.codec||(u.codecType=T.codec),T.outputLevel?u.receiveLevel=Math.round(32767*T.outputLevel):E&&(u.receiveLevel=Math.round(32767*E.getVolumeLevel())),u.receiveBytes=T.bytes,u.receivePackets=T.packets,u.receivePacketsLost=T.packetsLost,u.receivePacketsDiscarded=T.packetsDiscarded,u.packetLossRate=u.receivePacketsLost/(u.receivePackets+u.receivePacketsLost),u.receiveBitrate=c?8*Math.max(0,u.receiveBytes-c.receiveBytes):0,u.totalDuration=c?c.totalDuration+1:1,u.totalFreezeTime=c?c.totalFreezeTime:0,u.freezeRate=u.totalFreezeTime/u.totalDuration,u.receiveDelay=T.jitterBufferMs,u.totalDuration>10&&Bte.isRemoteAudioFreeze(E)&&(u.totalFreezeTime+=1)),R){"H264"!==R.codec&&"H265"!==R.codec&&"VP8"!==R.codec&&"VP9"!==R.codec&&"AV1X"!==R.codec&&"AV1"!==R.codec||(h.codecType=R.codec),h.receiveBytes=R.bytes,h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.decodeFrameRate=R.decodeFrameRate<0?0:R.decodeFrameRate,h.renderFrameRate=R.decodeFrameRate<0?0:R.decodeFrameRate,R.outputFrame&&(h.renderFrameRate=R.outputFrame.frameRate),R.receivedFrame?(h.receiveFrameRate=R.receivedFrame.frameRate,h.receiveResolutionHeight=R.receivedFrame.height,h.receiveResolutionWidth=R.receivedFrame.width):m&&(h.receiveResolutionHeight=m._videoHeight||0,h.receiveResolutionWidth=m._videoWidth||0),void 0!==R.framesRateFirefox&&(h.receiveFrameRate=Math.round(R.framesRateFirefox)),h.receivePackets=R.packets,h.receivePacketsLost=R.packetsLost,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.receiveDelay=R.jitterBufferMs||0;const t=!!g&&e.getRemoteVideoIsReady(g),n=d?d.totalFreezeTime:0,i=d?d.totalDuration:0;var y;if(h.totalDuration=d?d.totalDuration+1:1,1===xP("REMOTE_VIDEO_FREEZE_TIME_VERSION"))m&&t&&m._player&&(h.totalFreezeTime=m._player.totalFreezeTime/1e3);else h.totalFreezeTime=null!==(y=R.totalFreezesDuration)&&void 0!==y?y:n||0,void 0===R.totalFreezesDuration&&m&&t&&Bte.isRemoteVideoFreeze(m,R,l)&&(h.totalFreezeTime+=1);h.freezeRate=Math.max(0,Math.min((h.totalFreezeTime-n)/(h.totalDuration-i),1))}v&&(u.end2EndDelay=v.B_ad,h.end2EndDelay=v.B_vd,u.transportDelay=v.B_ed,h.transportDelay=v.B_ed,u.currentPacketLossRate=v.B_ealr4/100,h.currentPacketLossRate=v.B_evlr4/100,p.uplinkNetworkQuality=v.B_punq?v.B_punq:0,p.downlinkNetworkQuality=v.B_pdnq?v.B_pdnq:0),this.remoteStats.set(o,{audioStats:u,videoStats:h,videoPcStats:R,networkStats:p}),E&&this.exceptionMonitor.setRemoteAudioStats(E,u),m&&this.exceptionMonitor.setRemoteVideoStats(m,h)}))}}class jte{constructor(){zA(this,"destChannelMediaInfos",new Map),zA(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){SF(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){SF(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){dF(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function Gte(e){if(!(e instanceof jte)){return new YL(wN.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw()}const t=e.getSrcChannelMediaInfo(),n=e.getDestChannelMediaInfo();if(!t){return new YL(wN.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw()}if(0===n.size){return new YL(wN.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}}class Wte{get hasVideo(){return this._video_enabled_&&!this._video_muted_&&this._video_added_}get hasAudio(){return this._audio_enabled_&&!this._audio_muted_&&this._audio_added_}get audioTrack(){if(this.hasAudio||this._audio_pre_subscribed)return this._audioTrack}get videoTrack(){if(this.hasVideo||this._video_pre_subscribed)return this._videoTrack}get dataChannels(){return this._dataChannels}constructor(e,t){zA(this,"uid",void 0),zA(this,"_uintid",void 0),zA(this,"_trust_in_room_",!0),zA(this,"_trust_audio_enabled_state_",!0),zA(this,"_trust_video_enabled_state_",!0),zA(this,"_trust_audio_mute_state_",!0),zA(this,"_trust_video_mute_state_",!0),zA(this,"_audio_muted_",!1),zA(this,"_video_muted_",!1),zA(this,"_audio_enabled_",!0),zA(this,"_video_enabled_",!0),zA(this,"_audio_added_",!1),zA(this,"_video_added_",!1),zA(this,"_is_pre_created",!1),zA(this,"_video_pre_subscribed",!1),zA(this,"_audio_pre_subscribed",!1),zA(this,"_trust_video_stream_added_state_",!0),zA(this,"_trust_audio_stream_added_state_",!0),zA(this,"_audioTrack",void 0),zA(this,"_videoTrack",void 0),zA(this,"_dataChannels",[]),zA(this,"_audioSSRC",void 0),zA(this,"_videoSSRC",void 0),zA(this,"_audioOrtc",void 0),zA(this,"_videoOrtc",void 0),zA(this,"_cname",void 0),zA(this,"_rtxSsrcId",void 0),zA(this,"_videoMid",void 0),zA(this,"_audioMid",void 0),this.uid=e,this._uintid=t}}function Kte(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Hte(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Kte(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Kte(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const Yte=e=>"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1 2\na=msid-semantic: WMS\na=ice-lite".concat(e?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP4 127.0.0.1\na=mid:2\n"),Xte="9",Jte=2e4,zte=4e4;let Zte=class{get localCapabilities(){return vD(this._localCapabilities)}get rtpCapabilities(){return vD(this._rtpCapabilities)}get candidates(){return vD(this._candidates)}get iceParameters(){return vD(this._iceParameters)}get remoteIceUfrag(){var e;return null===(e=this._iceParameters)||void 0===e?void 0:e.iceUfrag}get dtlsParameters(){return vD(this._dtlsParameters)}constructor(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]&&arguments[3];zA(this,"sessionDesc",void 0),zA(this,"_localCapabilities",void 0),zA(this,"_rtpCapabilities",void 0),zA(this,"_candidates",void 0),zA(this,"_originCandidates",void 0),zA(this,"_iceParameters",void 0),zA(this,"_isUseExtmapAllowMixed",void 0),zA(this,"_isUseLocalCodecs",void 0),zA(this,"_isUseDataChannel",void 0),zA(this,"_dtlsParameters",void 0),zA(this,"setup",void 0),zA(this,"currentMidIndex",void 0),zA(this,"cname",void 0),zA(this,"useLocalCodecsMids",[]),zA(this,"preloadSsrcs",[]),zA(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=t,this._isUseLocalCodecs=n,this._isUseDataChannel=i;const r=e=vD(e),o=r.iceParameters,s=r.dtlsParameters,a=r.candidates,c=r.rtpCapabilities,d=r.setup,l=r.localCapabilities,u=r.cname;this._rtpCapabilities=c,this._candidates=a,this._originCandidates=vD(a),this._iceParameters=o,this._dtlsParameters=s,this._localCapabilities=l,this.setup=d,this.cname=u;var h=KC(this.updateRemoteRTPCapabilities(c),1);this.sessionDesc=h[0],this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}checkPreloadSsrcs(e){return e.length===this.preloadSsrcs.length&&e.every((e=>{var t;return Ui(t=this.preloadSsrcs).call(t,e)}))}preloadRemoteMedia(e){let t=0;const n=[],i=[];for(;e>0;){const r=[Hte({ssrcId:zte+t},xP("USE_SUB_RTX")?{rtx:zte+t+1}:{})],o="".concat(zte+t,"_").concat(Jte+t),s=H7(r,this.cname,xP("SYNC_GROUP")?o:void 0),a=s.ssrcs,c=s.ssrcGroups,d=this.preCreateOrRecycleSendMedia("video",a,c,void 0),l=[{ssrcId:Jte+t}],u="".concat(zte+t,"_").concat(Jte+t),h=H7(l,this.cname,xP("SYNC_GROUP")?u:void 0),p=h.ssrcs,_=h.ssrcGroups,E=this.preCreateOrRecycleSendMedia("audio",p,_,void 0);e--,t+=2,n.push(d,E),i.push(a[0].ssrcId,p[0].ssrcId)}return this.useLocalCodecsMids.push(...n),this.preloadSsrcs=i,{mids:n,preSSRCs:i,isAvailable:!0}}preCreateOrRecycleSendMedia(e,t,n,i){const r=this.rtpCapabilities.send.videoCodecs,o=this._isUseLocalCodecs||0===r.length?this.localCapabilities.recv:this.rtpCapabilities.send;SL.debug("create or recycle send media without remote rtp capabilities, ssrcs ",t[0].ssrcId);const s=e===UF.VIDEO?o.videoCodecs:o.audioCodecs,a=e===UF.VIDEO?o.videoExtensions:o.audioExtensions;this.currentMidIndex+=1;const c="".concat(this.currentMidIndex);let d={media:{mediaType:e,port:Xte,protos:["UDP","TLS","RTP","SAVPF"],fmts:s.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:a,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:s,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(c)}};return d=this.mungSendMediaDesc(d,i),this.sessionDesc.mediaDescriptions.push(d),this.updateBundleMids(),c}toString(){return ZP(this.sessionDesc)}send(e,t,n,i){const r=H7(t,this.cname,xP("SYNC_GROUP")?n:void 0),o=r.ssrcs,s=r.ssrcGroups,a=this.findPreloadMediaDesc(o);if(a){if($O()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),i&&(i.twcc||i.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(a,i),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,o);let n;return-1===t||1===t&&(zO()||function(){const e=GO();return!(e.name!==xO.CHROME||!e.osVersion)&&Number(e.version)<=90}()||tN(143)||rN(143)||XO()||xP("RESERVE_MID_1_MLINE")||xP("ENABLE_ENCODED_TRANSFORM")&&JO())||0===t&&!function(e){const t=GO();return!(t.name!==xO.FIREFOX||!t.osVersion)&&Number(t.version)===e}(138)&&xP("USE_SUB_RTX")||uN()?(n=this.createOrRecycleSendMedia(e,o,s,"sendonly",i),this.updateBundleMids()):(n=vD(this.sessionDesc.mediaDescriptions[t]),n.attributes.direction="sendonly",n.attributes.ssrcs=o,n.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(n,i)),$O()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,n.attributes.mid),{mid:n.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const e=this.createOrRecycleDataChannel(),t=e.mediaDesc,n=e.needExchangeSDP;return this.updateBundleMids(),{mid:t.attributes.mid,needExchangeSDP:n}}batchSend(e){const t=e.map((e=>{let t=e.kind,n=e.ssrcMsg,i=e.mslabel;return this.send(t,n,i)})),n=[];let i=!1;return t.forEach((e=>{let t=e.mid;e.needExchangeSDP&&(i=!0),n.push(t)})),{mids:n,needExchangeSDP:i}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{"0"===e.attributes.mid||$O()||uN()?e.attributes.ssrcs=[]:(e.attributes.ssrcs=[],e.attributes.direction="inactive",e.media.port="0")})),this.updateBundleMids()}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Ui(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Ui(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}receive(e,t,n,i){e.forEach(((e,r)=>{this.createOrRecycleRecvMedia(e,[],"recvonly",t,n,i[r])})),this.updateBundleMids()}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}updateRemoteRTPCapabilities(e){const t=this.sessionDesc||zP((n=this._isUseExtmapAllowMixed,this._isUseDataChannel?Yte(n):"v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=ice-lite".concat(n?"\na=extmap-allow-mixed":"","\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n")));var n;this._rtpCapabilities=e;let i=!1;const r=this.rtpCapabilities.send,o=this.localCapabilities.send,s=this.localCapabilities.recv,a=s.videoCodecs,c=s.audioCodecs,d=s.videoExtensions,l=s.audioExtensions;for(const e of t.mediaDescriptions){var u;if("sendonly"!==e.attributes.direction||"string"!=typeof e.attributes.mid||!Ui(u=this.useLocalCodecsMids).call(u,e.attributes.mid)){if(i=!0,e.attributes.iceUfrag=this._iceParameters.iceUfrag,e.attributes.icePwd=this._iceParameters.icePwd,e.attributes.fingerprints=this._dtlsParameters.fingerprints,e.attributes.candidates=this._candidates,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){var h;e.media.fmts=a.map((e=>e.payloadType.toString(10))),e.attributes.payloads=a,e.attributes.extmaps=d;const t=e.attributes.mid;"string"!=typeof t||Ui(h=this.useLocalCodecsMids).call(h,t)||this.useLocalCodecsMids.push(t)}else if(0===r.videoCodecs.length){const t=o.videoCodecs.filter((e=>{var t,n;return null===(t=e.rtpMap)||void 0===t?void 0:Ui(n=t.encodingName.toLowerCase()).call(n,"vp8")}));0===t.length&&t.push(o.videoCodecs[0]),e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=r.videoCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r.videoCodecs,e.attributes.extmaps=r.videoExtensions;if("audio"===e.media.mediaType)if(this._isUseLocalCodecs&&"sendonly"===e.attributes.direction){var p;e.media.fmts=c.map((e=>e.payloadType.toString(10))),e.attributes.payloads=c,e.attributes.extmaps=l;const t=e.attributes.mid;"string"!=typeof t||Ui(p=this.useLocalCodecsMids).call(p,t)||this.useLocalCodecsMids.push(t)}else if(0===r.audioCodecs.length){const t=o.audioCodecs.filter((e=>{var t,n;return null===(t=e.rtpMap)||void 0===t?void 0:Ui(n=t.encodingName.toLowerCase()).call(n,"opus")}))||[o.audioCodecs[0]];e.media.fmts=t.map((e=>e.payloadType.toString(10))),e.attributes.payloads=t,e.attributes.extmaps=[]}else e.media.fmts=r.audioCodecs.map((e=>e.payloadType.toString(10))),e.attributes.payloads=r.audioCodecs,e.attributes.extmaps=r.audioExtensions,iee(e)}}return this.sessionDesc=t,this.currentMidIndex=t.mediaDescriptions.length-1,[this.sessionDesc,i]}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),n=[];if(t.forEach((e=>{n.push(Hte(Hte({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case VF.TCP_RELAY:this._candidates=n;break;case VF.UDP_TCP_RELAY:case VF.RELAY:this._candidates=[...t,...n];break;default:this._candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){let t=!1;return e=vD(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((n=>{n.attributes.iceUfrag===e.iceUfrag&&n.attributes.icePwd===e.icePwd||(t=!0),n.attributes.iceUfrag=e.iceUfrag,n.attributes.icePwd=e.icePwd})),t}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}findAvailableMediaIndex(e,t){return this.sessionDesc.mediaDescriptions.findIndex((n=>{const i=n.media.mediaType===e&&"0"!==n.media.port&&("sendonly"===n.attributes.direction||"sendrecv"===n.attributes.direction)&&0===n.attributes.ssrcs.length;if($O()){if(i){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==n.attributes.mid&&"1"!==n.attributes.mid)||!(!e||e!==n.attributes.mid)}return!1}return i}))}createOrRecycleDataChannel(){for(const e of this.sessionDesc.mediaDescriptions)if("application"===e.media.mediaType)return{mediaDesc:e,needExchangeSDP:!1};this.currentMidIndex+=1;const e="".concat(this.currentMidIndex),t={media:{mediaType:"application",port:Xte,protos:["UDP","DTLS","SCTP"],fmts:["webrtc-datachannel"]},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:[],fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:[],ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:[],rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,mid:"".concat(e),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(t),{mediaDesc:t,needExchangeSDP:!0}}createOrRecycleRecvMedia(e,t,n,i,r,o){const s=e._mediaStreamTrack.kind,a=this.rtpCapabilities.recv,c=ree(s,a,this.localCapabilities.send,s===UF.VIDEO?i:r),d=s===UF.VIDEO?a.videoExtensions:a.audioExtensions;this.currentMidIndex+=1;const l="".concat(this.currentMidIndex);let u={media:{mediaType:s,port:Xte,protos:["UDP","TLS","RTP","SAVPF"],fmts:c.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:d,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:c,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(l)}};u=this.mungRecvMediaDsec(u,e,o);const h=this.findFirstClosedMedia(s);if(h){const e=this.sessionDesc.mediaDescriptions.indexOf(h);this.sessionDesc.mediaDescriptions[e]=u}else this.sessionDesc.mediaDescriptions.push(u);return u}updateRemoteDtlsParameters(e){const t=new Set(this._dtlsParameters.fingerprints.map((e=>e.fingerprint))),n=new Set(e.map((e=>e.fingerprint)));let i=!1;t.size!==n.size&&(i=!0);for(const e of t)n.has(e)||(i=!0);return i}updateRemoteCodec(e,t,n){const i=[...new Set(this._rtpCapabilities.recv.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Ui(t=Object.keys(GP)).call(t,e)})))],r=new Set(t);if(i.every((e=>r.has(e))))return SL.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(t)),!1;const o=this._rtpCapabilities.recv.videoCodecs.filter((e=>t.some((t=>{var n;return Ui(n=e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").call(n,t)}))));if(0===o.length)return SL.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(i," codecs: ").concat(t)),!1;const s=[...new Set(o.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")))];let a;if(SL.debug("updateRemoteCodec, from ".concat(i," to ").concat(s)),0===e.length)a=this.sessionDesc.mediaDescriptions.filter((e=>"video"===e.media.mediaType&&"recvonly"===e.attributes.direction));else if(a=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&"video"===t.media.mediaType&&Ui(e).call(e,t.attributes.mid)&&"recvonly"===t.attributes.direction)),a.length!==e.length)return SL.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(e,", codecs: ").concat(t)),!1;if(xP("USE_PUB_RTX")||xP("USE_SUB_RTX")){const e=oee(o,this.rtpCapabilities.recv.videoCodecs);o.push(...e)}this._rtpCapabilities.recv.videoCodecs=o;const c=this.localCapabilities.send,d=this.rtpCapabilities.recv,l=ree(UF.VIDEO,d,c,n);return a.forEach((e=>{const t=l.map((e=>e.payloadType.toString(10)));SL.debug("updateRemoteCodec mid: ".concat(e.attributes.mid,", from"),e.attributes.payloads,"to",l),e.attributes.payloads=l,e.media.fmts=t})),SL.debug("updateRemoteCodec success, mids: ".concat(e,", codecs: ").concat(t,", remote recv: ").concat(this._rtpCapabilities.recv.videoCodecs.length,", remote send: ").concat(this._rtpCapabilities.send.videoCodecs.length)),!0}createOrRecycleSendMedia(e,t,n,i,r){const o=this.rtpCapabilities.send.videoCodecs,s=this._isUseLocalCodecs||0===o.length?this.localCapabilities.recv:this.rtpCapabilities.send,a=e===UF.VIDEO?s.videoCodecs:s.audioCodecs,c=e===UF.VIDEO?s.videoExtensions:s.audioExtensions;this.currentMidIndex+=1;const d="".concat(this.currentMidIndex);let l={media:{mediaType:e,port:Xte,protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:this.candidates,extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungSendMediaDesc(l,r);const u=this.findFirstClosedMedia(e);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}mungRecvMediaDsec(e,t,n){const i=vD(e);return X7(i),Y7(i,t),J7(i,t),z7(i),Z7(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=vD(e);return n.attributes&&n.attributes.payloads&&Array.isArray(n.attributes.payloads)&&n.attributes.payloads.length>0&&n.attributes.payloads.forEach((e=>{e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&xP("ENABLE_DOWN_SPS_PPS")&&(e.fmtp&&e.fmtp.parameters||(e.fmtp={parameters:{}}),e.fmtp.parameters["sps-pps-idr-in-keyframe"]="1")})),Z7(n,t,this.localCapabilities.recv),iee(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}bumpMid(e){this.currentMidIndex+=e}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>$O()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var n;return(null===(n=t.attributes)||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId)===e[0].ssrcId}))}getSSRC(e){var t;return null===(t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===t?void 0:t.attributes.ssrcs}};function qte(e){return!!e&&Boolean("number"==typeof e.minDownscaleWidth&&e.minDownscaleWidth>=1||"number"==typeof e.minDownscaleHeight&&e.minDownscaleHeight>=1)}function Qte(e){return"vp8"===e||"vp9"===e}function $te(e,t,n,i){if("number"!=typeof i)return Array.from({length:n+1},((n,i)=>e/Math.pow(t,i)));const r=Math.max(e,i),o=r/e;if(o<=1)return Array.from({length:n+1},(()=>e));const s=1/t,a=Math.min(n,Math.max(1,Math.ceil(Math.log(o)/Math.log(s)))),c=Math.pow(o,1/a);return Array.from({length:n+1},((t,n)=>{if(0===n)return e;const i=Math.min(n,a);return Math.min(e*Math.pow(c,i),r)}))}function ene(e,t,n,i){if("number"!=typeof i)return n;const r=Math.max(e,i)/e;if(r<=1)return 0;const o=1/t;return Math.min(n,Math.max(1,Math.ceil(Math.log(r)/Math.log(o))))}function tne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function nne(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?tne(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):tne(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}var ine=function(e){return e[e.DOWN=0]="DOWN",e[e.UP=1]="UP",e}(ine||{});const rne=new Map;function one(e,t,n,i){let r=e.scale;if(0===r&&i===ine.UP||r>=t.length-1&&i===ine.DOWN)return e;let o=nne(nne({},e),{},{scale:i===ine.DOWN?++r:--r});switch(n){case"maintain-framerate":o=nne(nne({},o),t[r].motion);break;case"maintain-resolution":o=nne(nne({},o),t[r].detail);break;case"balanced":o=nne(nne({},o),t[r].balanced)}return o}function sne(e,t,n){if(t){const i={overUse:0,underUse:0,adaptationList:ane(t,n)};rne.set(e,i)}else rne.delete(e)}function ane(e,t){const n=nne({},e),i=n.bitrateMax,r=n.frameRate,o=n.scaleResolutionDownBy,s=n.bitrateMin,a=function(e){const t=[];if("number"==typeof e.minDownscaleHeight&&e.minDownscaleHeight>=1&&e.height>0&&t.push(e.height/e.minDownscaleHeight),"number"==typeof e.minDownscaleWidth&&e.minDownscaleWidth>=1&&e.width>0&&t.push(e.width/e.minDownscaleWidth),t.length)return Math.max(e.scaleResolutionDownBy,Math.min(...t))}(n),c=LP.MIN_FRAME_RATE,d=LP.MAX_THRESHOLD_FRAMERATE,l=LP.MAX_SCALE,u=LP.BITRATE_MIN_THRESHOLD,h=LP.BITRATE_MAX_THRESHOLD,p=LP.BWE_SCALE_UP_THRESHOLD,_=LP.BWE_SCALE_DOWN_THRESHOLD,E=LP.PERF_SCALE_DOWN_THRESHOLD,m=LP.PERF_SCALE_UP_THRESHOLD,f=LP.BALANCE_BITRATE_FACTOR,g=LP.BALANCE_FRAMERATE_FACTOR,S=LP.BALANCE_RESOLUTION_FACTOR,T=LP.MOTION_RESOLUTION_FACTOR,R=LP.MOTION_BITRATE_FACTOR,v=LP.DETAIL_FRAMERATE_FACTOR,y=LP.DETAIL_BITRATE_FACTOR,C=Math.min(n.frameRate,d);let b=l;"maintain-framerate"===t?b=ene(o,T,l,a):"balanced"===t&&(b=ene(o,S,l,a));const I=$te(o,S,b,a),A=$te(o,T,b,a),w=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(_,1)*i),bwe_up:i,fps_down:Math.round(Math.pow(E,1)*C),fps_up:r},balanced:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:i,bitrateMin:s},motion:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:i,bitrateMin:s},detail:{scaleResolutionDownBy:1,frameRate:r,bitrateMax:i,bitrateMin:s}}];for(let e=1;e<=b;e++){const t={bwe_up:Math.round(Math.pow(p,e)*i),bwe_down:Math.round(Math.pow(_,e+1)*i),fps_up:Math.round(Math.pow(m,e)*C),fps_down:Math.round(Math.pow(E,e+1)*C)},n={scaleResolutionDownBy:I[e],frameRate:Math.max(Math.round(Math.pow(g,e)*r),c),bitrateMax:Math.max(Math.round(Math.pow(f,e)*i),h),bitrateMin:Math.max(Math.round(Math.pow(f,e)*s),u)},o={scaleResolutionDownBy:A[e],frameRate:r,bitrateMax:Math.max(Math.round(Math.pow(R,e)*i),h),bitrateMin:Math.max(Math.round(Math.pow(R,e)*s),u)},a={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(v,e)*r),c),bitrateMax:Math.max(Math.round(Math.pow(y,e)*i),h),bitrateMin:Math.max(Math.round(Math.pow(y,e)*s),u)};w.push({scale:e,threshold:t,balanced:n,motion:o,detail:a})}return w}function cne(e,t,n,i,r,o){const s=rne.get(e)||{overUse:0,underUse:0,adaptationList:ane(r,o)},a=s.adaptationList;rne.set(e,s);const c=LP.OVERUSE_TIMES_THRESHOLD,d=LP.UNDERUSE_TIMES_THRESHOLD,l=i.scale;let u,h;return"number"==typeof t&&t>0&&function(e,t,n,i){if(t>=n.length)return!1;let r=n[t].threshold.fps_down;return xP("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===i&&(r=n[0].threshold.fps_down),e<r}(t,l,a,o)&&(s.overUse++,h=fP.CPU,s.overUse>c)||"number"==typeof n&&n>0&&function(e,t,n){return!(t>=n.length)&&e<n[t].threshold.bwe_down}(n,l,a)&&(s.overUse++,h=fP.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,u=one(i,a,o,ine.DOWN),[u,h]):("number"==typeof t&&t>0&&"number"==typeof n&&n>0&&function(e,t,n,i){if(0===t)return;let r=n[t].threshold.fps_up;return xP("FORCE_AG_HIGH_FRAMERATE")&&"maintain-framerate"===i&&(r=n[1].threshold.fps_up),e>r}(t,l,a,o)&&function(e,t,n){if(0===t)return;return e>n[t].threshold.bwe_up}(n,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,u=one(i,a,o,ine.UP),0===u.scale&&(h=fP.NONE))),[u,h])}function dne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function lne(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?dne(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dne(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function une(e,t){var n;return!!xP("ENABLE_AG_ADAPTATION")&&(!!qte(t)||!!(e instanceof RV||Ui(n=e._hints).call(n,Rk.CUSTOM_TRACK))&&(!!xP("FORCE_SUPPORT_AG_ADAPTATION")||!!(aN(14,0,!1)&&cN(17,4,!0)||sN(14)&&dN(17,4,!0))))}const hne=new Map;function pne(e,t,n,i,r,o){if(_ne(e,n),r(t),"balanced"!==i&&"maintain-framerate"!==i&&"maintain-resolution"!==i)return;let s=-1;sne(e,t,i);const a=window.setInterval((()=>{const a=hne.get(e);if(!xP("ENABLE_AG_ADAPTATION")||!a)return _ne(e,n),void r(t);const c=o();if(c.sendPackets>0&&c.OutgoingAvailableBandwidth>0){if(-1===s)return void(s=Date.now());if(Date.now()-s<1e3)return;const o=c.sendFrameRate,d=c.OutgoingAvailableBandwidth,l=KC(cne(e,o,d,a.adaptationConfig,t,i),2),u=l[0],h=l[1];h&&(n.qualityLimitationReason=h),u&&a.adaptationConfig.scale!==u.scale&&(SL.debug("[".concat(e,"] applyAdaptation: ").concat(n.qualityLimitationReason,"\n           sendFps ").concat(o,", bwe ").concat(d,", switch from ").concat(a.adaptationConfig.scale," to ").concat(u.scale," ")),a.adaptationConfig=lne(lne({},a.adaptationConfig),u),r(u))}}),xP("CHECK_LOCAL_STATS_INTERVAL")),c=lne({},t);hne.set(e,{timer:a,adaptationConfig:c,originConfig:t,adaptationFunc:r}),SL.debug("[".concat(e,"] start adaptation, originConfig: ").concat(JSON.stringify(t),", degradationPreference: ").concat(i))}function _ne(e,t){const n=hne.get(e);if(n){const t=n.timer;window.clearTimeout(t),hne.delete(e)}t.qualityLimitationReason=fP.NONE,sne(e)}const Ene=["balanced","maintain-framerate","maintain-resolution"];function mne(e){switch(e){case"motion":return"maintain-framerate";case"detail":return"maintain-resolution";case"balanced":return"balanced";default:return}}function fne(e){var t;let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=mne(e._optimizationMode);if(i)return i;const r=xP("CUSTOM_ADAPTATION_DEFAULT_MODE");return Ui(t=e._hints).call(t,Rk.CUSTOM_TRACK)?function(e){return"string"==typeof e&&Ui(Ene).call(Ene,e)}(r)?r:n?"maintain-framerate":"":"maintain-framerate"}function gne(e,t){if(t)return"maintain-resolution";const n=mne(e._optimizationMode);return n||void 0}function Sne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Tne(e,t,n){var i;const r=e.getParameters(),o=null===(i=r.encodings)||void 0===i?void 0:i[0];return o&&Object.assign(o,n),Object.assign(r,t),r}async function Rne(e,t,n){try{return await e.setParameters(Tne(e,t,n)),{classification:"transient"}}catch(i){const r=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Sne(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Sne(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},n);delete r.scaleResolutionDownBy;try{return await e.setParameters(Tne(e,t,r)),{classification:"unsupported",retryWithScaleError:i}}catch(e){return{classification:"unknown",retryWithScaleError:i,retryWithoutScaleError:e}}}}function vne(e,t){var n;let i;switch(t){case BF.LocalAudioTrack:i=CF.Audio;break;case BF.LocalVideoTrack:i=Ui(n=e._hints).call(n,Rk.SCREEN_TRACK)?CF.Screen:CF.High;break;case BF.LocalVideoLowTrack:i=CF.Low}return i}function yne(e){const t=JL();if(e.some((e=>e._bypassWebAudio)))throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!t.webAudioMediaStreamDest)throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function Cne(e,t){yne(e);const n=t||new OU;return e.forEach((e=>n.addAudioTrack(e))),n}const bne=!JL().supportUnifiedPlan||xP("CHROME_FORCE_PLAN_B")&&SN();function Ine(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e.useDcSignal)return n={spec:t,store:e},mee("DataChannelConnection").create(n);var n;const i=bne?function(e){return mee("PlanBConnection").create(e)}({spec:t,store:e}):new Pne(t,e);return i}function Ane(e){return e&&("disconnected"===e.iceConnectionState||"checking"===e.iceConnectionState||"failed"===e.iceConnectionState)}function wne(e){try{if(e.iceServers)return!1;if(e.turnServer&&"off"!==e.turnServer.mode){if(eD(e.turnServer.servers))return!1;if(xP("FORCE_TURN_TCP")||e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).some((e=>e.forceturn)))return!0}return!1}catch(e){return!1}}var One;function Nne(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Dne(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Nne(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Nne(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let Pne=(One=class e extends MF{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get remoteIceUfrag(){var e;return null===(e=this.remoteSDP)||void 0===e?void 0:e.remoteIceUfrag}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Ui(t=Object.keys(GP)).call(t,e)})))]}constructor(t,n){if(super(t,n),zA(this,"id",kD(5,"connection-")),zA(this,"store",void 0),zA(this,"peerConnection",void 0),zA(this,"forceTurn",!1),zA(this,"remoteSDP",void 0),zA(this,"initialOffer",void 0),zA(this,"transportEventReceiver",void 0),zA(this,"statsFilter",void 0),zA(this,"extension",{useXR:xP("USE_XR")}),zA(this,"localCapabilities",void 0),zA(this,"remoteCodecs",void 0),zA(this,"localCandidateCount",0),zA(this,"allCandidatesReceived",!1),zA(this,"isPreallocation",!1),zA(this,"isPreRender",!1),zA(this,"preMediaMap",new Map),zA(this,"dataStreamChannelMap",new Map),zA(this,"establishPromise",void 0),zA(this,"recoveredDataChannelIds",[]),zA(this,"currentDataChannelId",1),zA(this,"supportAV1RtpSpec",!1),zA(this,"_nvMedia",void 0),zA(this,"mutex",void 0),zA(this,"qualityLimitationReason",fP.NONE),zA(this,"unsupportedResolutionFloorTrackIds",new Set),zA(this,"isFirstConnected",!1),this.store=n,this.forceTurn=wne(t),this.mutex=new JD("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=bP(this.peerConnection,xP("STATS_UPDATE_INTERVAL"),void 0,$O()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,t.isPreallocation&&(this.isPreallocation=!0),this.store.aiClientMode){const e=this.peerConnection.createDataChannel("agora-media",{id:this.store.mediaDcId,ordered:!1,negotiated:!0});e.binaryType="arraybuffer";try{this._nvMedia=function(e){return mee("AiAudioModeExtension").create(e)}(e),this._nvMedia.setAudioMetadataHandler((e=>{var t;null===(t=this.onAudioMetadata)||void 0===t||t.call(this,e)})),this._nvMedia.setAudioPtsHandler((e=>{var t;null===(t=this.onAudioPts)||void 0===t||t.call(this,e)})),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] AI Audio Mode initialized"))}catch(e){this._nvMedia=void 0,SL.warning("[".concat(this.store.clientId,"] [P2PConnection] AI Audio Mode not available"),e)}}this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void SL.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const n=this.remoteSDP.toString();null==t||t(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}else SL.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=B7(t.sdp),i=await $7({filterRTX:!xP("USE_PUB_RTX")&&!xP("USE_SUB_RTX"),filterVideoFec:xP("FILTER_VIDEO_FEC"),filterAudioFec:xP("FILTER_AUDIO_FEC"),filterVideoCodec:xP("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:xP("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:xP("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=nee(i),this.initialOffer=t,xP("ENABLE_SVC")&&"av1"==this.store.codec){const t=await Q7();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=i.send)||void 0===e||e.videoExtensions.push(t)}let r;return t.sdp&&lee(t.sdp)&&(r=vD(i),D7(r)),Dne(Dne({},n),{},{rtpCapabilities:r||i,offerSDP:t.sdp})}catch(e){throw new ON(wN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");if(this.initialOffer.sdp&&lee(this.initialOffer.sdp)&&P7(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new Zte(Dne(Dne({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!xP("ENABLE_PRE_SUB_WITH_PRE_PC")||!xP("PRE_USE_LOCAL_CODECS"))&&QL(this.store),this.store.aiClientMode),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),qL()&&QL(this.store)){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,n=xP("PRE_SUB_NUM")||1,i=e>n?e:n,r=this.remoteSDP.preloadRemoteMedia(i),o=r.mids,s=r.preSSRCs,a=aee(this.initialOffer.sdp,this.extension),c=this.logSDPExchange(a||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:a}),null==c||c(a),new Array(i).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const d=await this.peerConnection.createOffer(),l=this.logSDPExchange(d.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(d);const u=this.remoteSDP.toString();null==l||l(u),await this.peerConnection.setRemoteDescription({type:"answer",sdp:u}),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(s)),await this.presetMedia(o,s);const h=this.peerConnection.getTransceivers()[0];null!=h&&h.receiver&&this.tryBindTransportEvents(h.receiver)}else{const t=this.remoteSDP.toString(),i=aee(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const o=this.peerConnection.getTransceivers()[0];if(null!=o&&o.receiver&&this.tryBindTransportEvents(o.receiver),QL(this.store))if(e.preallocation&&xP("ENABLE_PRE_SUB_WITH_PRE_PC")){var n;const e=(null===(n=this.store.preSubOptions)||void 0===n?void 0:n.length)||0,t=xP("PRE_SUB_NUM")||1,i=e>t?e:t,r=this.remoteSDP.preloadRemoteMedia(i),o=r.mids,s=r.preSSRCs;await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(s)),await this.presetMedia(o,s)}else{const t=e.preSSRCs,n=void 0===t?[]:t,i=n.map((e=>e.ssrcMsg[0].ssrcId));if(0===n.length)return;const r=this.remoteSDP.batchSend(n.map((e=>Object.assign({},e)))).mids;await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(i)),await this.presetMedia(r,i)}}}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}shouldUseAiAudioPreload(){return this.store.aiClientMode&&this.store.autoSubscribe&&!!this._nvMedia}async presetAiAudioMedia(e,t){if(!this._nvMedia)return;const n=await this._nvMedia.receiveByRTCMedia(UF.AUDIO,[{ssrcId:t}],void 0);this.store.autoReceiveAndPlayAudio&&this._nvMedia.play(),this.preMediaMap.set(t,{mid:e,track:n.track,player:void 0,transceiver:void 0,aiAudioMode:!0})}async presetMedia(e,t){for(const o of e.entries()){var n=KC(o,2);const e=n[0],s=n[1];for(const n of this.peerConnection.getTransceivers())if(null!=n.mid&&s===n.mid&&n.receiver.track){const o=n.receiver.track;if("audio"===o.kind&&this.shouldUseAiAudioPreload()){await this.presetAiAudioMedia(s,t[e]);break}if(xP("PRE_PLAYOUT_DELAY_HINT")){const e=n.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=xP("PRE_PLAYOUT_DELAY_HINT"),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia set playoutDelayHint to ").concat(xP("PRE_PLAYOUT_DELAY_HINT"))))}let a,c;if("video"===o.kind&&xP("ENABLE_PRE_RENDER")){var i,r;let n=null===(i=this.store.preSubOptions)||void 0===i||null===(i=i[e])||void 0===i?void 0:i.element;const s=(null===(r=this.store.preSubOptions)||void 0===r||null===(r=r[e])||void 0===r?void 0:r.config)||{};SL.debug("try to play pre sub video","string"==typeof n?n:"element","config: ".concat(JSON.stringify(s))),"string"==typeof n&&(n=document.getElementById(n)||void 0),a=n instanceof HTMLVideoElement?new LU(Dne({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(kD(5,"")),element:n},s)):new MU(Dne({trackId:"track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(kD(5,"")),element:n},s),!n),a.updateVideoTrack(o),a.onFirstVideoFrameRender=()=>{var n;a&&(a.onFirstVideoFrameRender=void 0);const i=this.preMediaMap.get(t[e]);i&&(i.firstVideoRender=Date.now()),null===(n=this.onFirstVideoRender)||void 0===n||n.call(this,t[e])},a.onVideoBufferReady=()=>{var n;null===(n=this.onFirstVideoBufferReady)||void 0===n||n.call(this,t[e])},a.play(this.store.sessionId||void 0),this.isPreRender=!0}if("audio"===o.kind&&this.store.autoReceiveAndPlayAudio){c="track-".concat(o.kind,"-unknown-").concat(this.store.clientId,"_").concat(kD(5,""));const e=100;CM.play(o,c,e,this.store.sessionId||void 0),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] presetMedia start audio playback, trackId: ").concat(c))}this.preMediaMap.set(t[e],{mid:s,track:o,player:a,transceiver:n,audioTrackId:c});break}this.store.peerReceiver()}}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}checkIceParameters(e){if(!this.remoteSDP)return!1;return this.remoteSDP.restartICE(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");let n=!1;const i=e.rtpCapabilities;if(n=KC(this.remoteSDP.updateRemoteRTPCapabilities(i),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);n=n||e}const r=e.preSSRCs,o=void 0===r?[]:r,s=o.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(s)){const e=[],n=[];let i=!1;var t;if(Array.from(this.preMediaMap.entries()).every((t=>{let r=KC(t,2),o=r[0],s=r[1],a=s.mid,c=s.player,d=(s.track,s.audioTrackId),l=s.aiAudioMode;return e.push(a),n.push(o),this.preMediaMap.delete(o),c&&c.destroy(),d&&CM.stop(d),i=i||!!l,!0})),i)null===(t=this._nvMedia)||void 0===t||t.stopReceiving();if(e.length>0&&(this.remoteSDP.stopSending(e),await see(this.peerConnection,this.remoteSDP,this.extension),SL.warn("[P2PConnection.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(n)),HL.reportApiInvoke(this.store.sessionId,{name:zN.PRELOAD_MEDIA_FAILED,options:[o,n],tag:ZN.TRACER}).onSuccess()),o.length>0){const e=this.remoteSDP.batchSend(o.map((e=>Object.assign({},e)))).mids;await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[P2PConnection.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(s)),await this.presetMedia(e,s)}}n?(await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[P2PConnection] updateRemoteConnect by exchanging SDP.")):SL.debug("[P2PConnection] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return Ww((function*(){const r=yield Kw(i.mutex.lock("From P2PConnection.send"));try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=O7();e.forEach((e=>{const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,Dne({direction:"sendonly"},"video"===e.trackMediaType&&i.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),$O()&&!0===xP("SIMULCAST")&&(yield Kw(i.applySimulcastForFirefox(o,e)));const a=yield Kw(i.peerConnection.createOffer()),c=i.remoteSDP.predictReceivingMids(e.length),d=i.mungSendOfferSDP(a.sdp,e,c),l=zP(d),u=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return j7(t,xP("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],i.remoteSDP.receive(e,t,n,h);const o=i.remoteSDP.toString();throw yield Kw(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Kw(i.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield Kw(i.stopSending(c,!0)),r}i.remoteSDP.receive(e,t,n,h);const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return yield Kw(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Kw(i.applySimulcastEncodings(o,e)),yield Kw(i.applySendEncodings(o,e)),null==_||_(p),yield Kw(i.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=c[t];return{localSSRC:u[t],id:n,transceiver:e}}))}catch(e){throw e instanceof ON?e:new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let n=this.dataStreamChannelMap.get(e);if(n&&"open"===n.readyState)SL.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");n=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:xP("DATASTREAM_MAX_RETRANSMITS")}),n.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,n)}t.forEach((e=>{e._updateOriginDataChannel(n)}));const i=this.remoteSDP.sendDataChannel();if(i.needExchangeSDP){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),SL.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else SL.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof ON?e:new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof ON?e:new ON(wN.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const n=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{var t;_ne(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){if(this._nvMedia&&e===UF.AUDIO)return SL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by DataChannel.")),await this._nvMedia.receiveByRTCMedia(e,t,void 0);try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,n,i),o=r.mid;r.needExchangeSDP&&(await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const s=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");if(xP("PRE_PLAYOUT_DELAY_HINT")){const t=s.receiver;"playoutDelayHint"in t&&(t.playoutDelayHint=xP("PRE_PLAYOUT_DELAY_HINT"),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," set playoutDelayHint to ").concat(xP("PRE_PLAYOUT_DELAY_HINT"))))}return{track:s.receiver.track,id:o,transceiver:s}}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e),n=t.mids;return t.needExchangeSDP&&(await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),n.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");if(xP("PRE_PLAYOUT_DELAY_HINT")){const e=t.receiver;"playoutDelayHint"in e&&(e.playoutDelayHint=xP("PRE_PLAYOUT_DELAY_HINT"),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e.track.kind," set playoutDelayHint to ").concat(xP("PRE_PLAYOUT_DELAY_HINT"))))}return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");let t=!1;e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((n=>{let i=KC(n,2),r=i[0],o=i[1],s=o.mid,a=o.player,c=o.audioTrackId,d=o.aiAudioMode;if(s===e)return this.preMediaMap.delete(r),a&&a.destroy(),c&&CM.stop(c),t=t||!!d,!0}))})),t&&this._nvMedia&&(this._nvMedia.setAudioMetadataHandler(null),this._nvMedia.setAudioPtsHandler(null),this._nvMedia.stopReceiving()),this.remoteSDP.stopSending(e);const n=this.remoteSDP.toString(),i=this.logSDPExchange(n,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const r=await this.peerConnection.createAnswer();null==i||i(r.sdp||""),await this.peerConnection.setLocalDescription(r)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return Ww((function*(){const n=yield Kw(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=JL().supportPCSetConfiguration,r=xP("FORCE_TURN_TCP")||t.forceTurn;if(e===VF.RELAY&&!i)return;if(i&&!r){const n=e===VF.RELAY?"relay":"all",i=t.peerConnection.getConfiguration();i.iceTransportPolicy!==n&&(SL.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}t.remoteSDP.updateCandidates(e);const o=yield Kw(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=B7(o.sdp),a=(yield s.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString(),d=t.logSDPExchange(o.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield Kw(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield Kw(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){SL.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(VF.TCP_RELAY),await see(this.peerConnection,this.remoteSDP,this.extension)}catch(e){SL.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e,t,n,i;null===(e=this._nvMedia)||void 0===e||e.setAudioMetadataHandler(null),null===(t=this._nvMedia)||void 0===t||t.setAudioPtsHandler(null),null===(n=this._nvMedia)||void 0===n||n.close(),this._nvMedia=void 0,this.peerConnection.getTransceivers().forEach((e=>{_ne(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player,n=e.audioTrackId;t&&t.destroy(),n&&CM.stop(n)})),this.preMediaMap.clear(),this.peerConnection.close(),null===(i=this.onConnectionStateChange)||void 0===i||i.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){const e=Dne(Dne({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason});if(this._nvMedia){const t=this._nvMedia.getStats();e.audioRecv.push(t)}return e}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?$O()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),n=t.local,i=t.remote;return{local:Dne(Dne({},dP),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:Dne(Dne({},dP),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const n="code: ".concat(e.errorCode,", message: ").concat(e.errorText),i=e.port?"local: ".concat(e.port):"",r=A7(e.url||"");SL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(n,"), url: ").concat(r||"",", host_candidate:").concat(i)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,n)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),xP("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[]},i=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(eD(t.turnServer.servers)?n.iceServers=t.turnServer.servers:xP("NEW_TURN_MODE")&&n.iceServers&&"disabled"===i?(xP("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),xP("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),xP("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),xP("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),xP("ENABLE_ENCODED_TRANSFORM")&&JL().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(f7(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!xP("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const n=xP("NEW_TURN_MODE");1===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(f7(e.turnServerURL),":443?transport=tcp")}):4===n&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(f7(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const n=t.iceTransport;n&&(n.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var n;e&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,e))},n.getSelectedCandidatePair&&(n.onselectedcandidatepairchange=()=>{if(n.getSelectedCandidatePair()){const e=n.getSelectedCandidatePair()||{},t=e.local,i=e.remote;if(t&&i){const e=t.address+":"+t.port,n=i.address+":"+i.port;SL.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(A7(e)),", remote ").concat(JSON.stringify(A7(n))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var n,i;if(!t){const n=this.peerConnection.getSenders();t=n.find((t=>t.track===e._mediaStreamTrack))}if(!t)return SL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return SL.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!JL().supportSetRtpSenderParameters)return SL.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r=UM(e),o=!!r&&Qte(this.store.codec)&&qte(r),s=o&&!this.unsupportedResolutionFloorTrackIds.has(e.getTrackId()),a=!!r&&!(o&&!s)&&une(e,s?r:void 0),c=s&&a,d=s||Ui(n=["vp8","vp9"]).call(n,this.store.codec),l={},u={},h=gne(e,c);h&&(l.degradationPreference=h);const p=w7(this.peerConnection,e._mediaStreamTrack);if(a&&p&&t&&r&&this.getLocalVideoStats&&d){const n=this.id+p.mid,i=fne(e,s);pne(n,r,this,i,(i=>{t&&this.updateAdaptation(e,t,i,n,s)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var _;const t=e._encoderConfig,n=t.bitrateMax,i=t.frameRate,r=t.scaleResolutionDownBy;n&&(u.maxBitrate=1e3*n),(Ui(_=e._hints).call(_,Rk.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(u.maxFramerate=T7(i)),r&&r>=1&&(u.scaleResolutionDownBy=r))}const E=xP("ENCODER_CONFIG_LIMIT").maxFramerate;if(E&&"number"==typeof E&&(u.maxFramerate=u.maxFramerate?Math.min(u.maxFramerate,E):E),xP("DSCP_TYPE")&&SN()){var m;const e=xP("DSCP_TYPE");Ui(m=["very-low","low","medium","high"]).call(m,e)&&(u.networkPriority=e)}const f=t.getParameters(),g=null===(i=f.encodings)||void 0===i?void 0:i[0];$O()&&!g&&(l.encodings=[u]),g&&Object.assign(g,u),Object.assign(f,l),SL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(f.encodings))),await t.setParameters(f),await dee(this.store.codec,t,xP("SVC_MODE"))}async updateAdaptation(e,t,n,i,r){var o,s;if(!t)return SL.debug("[updateAdaptation] no rtpSender found");if(!JL().supportSetRtpSenderParameters)return SL.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const a={},c={},d=n.bitrateMax,l=n.frameRate,u=n.scaleResolutionDownBy;d&&(c.maxBitrate=1e3*d),l&&(c.maxFramerate=T7(l));let h=!1;"number"==typeof u&&u>=1&&(r||Ui(o=["vp8","vp9"]).call(o,this.store.codec))&&(c.scaleResolutionDownBy=u,h=u>1);const p=t.getParameters(),_=null===(s=p.encodings)||void 0===s?void 0:s[0];_&&Object.assign(_,c),Object.assign(p,a);try{await t.setParameters(p),SL.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(p.encodings)))}catch(n){if(!("transport"in t)||t.transport&&"connected"===t.transport.state)if("connected"!==this.peerConnectionState)SL.debug("[updateAdaptation] peerConnection not connected}");else if(r&&h){const r=await Rne(t,a,c);"unsupported"===r.classification?(this.unsupportedResolutionFloorTrackIds.add(e.getTrackId()),_ne(i,this),SL.warn("[".concat(e.getTrackId(),"] fallback to browser adaptation because scaleResolutionDownBy adaptation is unsupported"),n,r.retryWithScaleError),this.updateRtpSenderEncodings(e,t).catch((t=>{SL.warn("[".concat(e.getTrackId(),"] failed to re-apply browser adaptation after disabling resolution floor"),t)}))):"transient"===r.classification?SL.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled after transient setParameters failure"),n):SL.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled because setParameters failure is not classified as unsupported"),n,r.retryWithScaleError,r.retryWithoutScaleError)}else SL.debug("[updateAdaptation] updateRtpSenderEncodings failed",n);else SL.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!JL().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof TV&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){SL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){if(xP("FORBID_MODIFY_LOCAL_OFFER_SDP"))return e;const i=zP(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(Y7(o,e),q7(o,e,this.store.codec))})),ZP(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof TV&&!Ui(n=d._hints).call(n,Rk.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!$O()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof TV&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,n,i,r,o;return!!(e instanceof TV&&xP("SIMULCAST")&&"vp8"===this.store.codec&&!Ui(t=e._hints).call(t,Rk.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,n,i){if(xP("SDP_LOGGING"))return SL.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(JL().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},Zx(One.prototype,"updateRemoteRTPCapabilities",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"updateRemoteRTPCapabilities"),One.prototype),Zx(One.prototype,"connect",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"connect"),One.prototype),Zx(One.prototype,"updateRemoteConnect",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"updateRemoteConnect"),One.prototype),Zx(One.prototype,"createDataChannels",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"createDataChannels"),One.prototype),Zx(One.prototype,"receive",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"receive"),One.prototype),Zx(One.prototype,"batchReceive",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"batchReceive"),One.prototype),Zx(One.prototype,"stopReceiving",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"stopReceiving"),One.prototype),Zx(One.prototype,"muteRemote",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"muteRemote"),One.prototype),Zx(One.prototype,"unmuteRemote",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"unmuteRemote"),One.prototype),Zx(One.prototype,"muteLocal",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"muteLocal"),One.prototype),Zx(One.prototype,"unmuteLocal",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"unmuteLocal"),One.prototype),Zx(One.prototype,"close",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"close"),One.prototype),Zx(One.prototype,"updateEncoderConfig",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"updateEncoderConfig"),One.prototype),Zx(One.prototype,"updateSendParameters",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"updateSendParameters"),One.prototype),Zx(One.prototype,"replaceTrack",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"replaceTrack"),One.prototype),Zx(One.prototype,"updateAdaptation",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"updateAdaptation"),One.prototype),Zx(One.prototype,"getRemoteSSRC",[Lne],Object.getOwnPropertyDescriptor(One.prototype,"getRemoteSSRC"),One.prototype),One);function Lne(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}function kne(e,t){let n=document.createElement("video"),i=document.createElement("canvas");n.setAttribute("style","display:none"),i.setAttribute("style","display:none"),n.setAttribute("muted",""),n.muted=!0,n.setAttribute("autoplay",""),n.autoplay=!0,n.setAttribute("playsinline",""),i.width=T7(t.width),i.height=T7(t.height);const r=T7(t.framerate||15);document.body.append(n),document.body.append(i);let o=e._mediaStreamTrack;n.srcObject=new MediaStream([o]),n.play().catch(UD);const s=i.getContext("2d");if(!s)throw new YL(wN.UNEXPECTED_ERROR,"can not get canvas context");const a=JL(),c=i.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=i),i.startCapture=()=>{if(!n)return i.stopCapture&&i.stopCapture();if(n.paused&&n.play(),n.videoHeight>2&&n.videoWidth>2){const e=n.videoWidth,t=n.videoHeight/e,r=i.width*t;Math.abs(r-i.height)>=2&&(SL.debug("adjust low stream resolution","".concat(i.width,"x").concat(i.height," -> ").concat(i.width,"x").concat(r)),i.height=r)}s.drawImage(n,0,0,i.width,i.height),c.requestFrame&&c.requestFrame(),o!==e._mediaStreamTrack&&(o=e._mediaStreamTrack,n.srcObject=new MediaStream([o]))},i.stopCapture=rM((()=>i.startCapture&&i.startCapture()),r);const d=c.stop;return c.stop=()=>{d.call(c),n&&(n.remove(),n.srcObject=null,n=null),i&&(i.width=0,i.remove(),i.stopCapture&&i.stopCapture(),i.startCapture=void 0,i.stopCapture=void 0,i=null),SL.debug("clean low stream renderer")},c}var Mne=function(e){return e[e.Video_Send_Type=190]="Video_Send_Type",e}(Mne||{}),Une=function(e){return e[e.Video_Send_Qp_Sum=2143]="Video_Send_Qp_Sum",e[e.Video_Send_Freeze=2082]="Video_Send_Freeze",e[e.Video_Send_Codec=2240]="Video_Send_Codec",e[e.Video_Send_Power_Efficient_Encoder=2241]="Video_Send_Power_Efficient_Encoder",e[e.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",e[e.Video_Recv_Freeze=2084]="Video_Recv_Freeze",e[e.Video_Recv_Codec=2242]="Video_Recv_Codec",e[e.Video_Recv_Power_Efficient_Decoder=2243]="Video_Recv_Power_Efficient_Decoder",e[e.Video_Render_Freeze_Time=2109]="Video_Render_Freeze_Time",e[e.Video_Render_Freeze_Time_Render=2147]="Video_Render_Freeze_Time_Render",e[e.Video_Render_Freeze_Time_Render2=2223]="Video_Render_Freeze_Time_Render2",e[e.Audio_Recv_Freeze=2083]="Audio_Recv_Freeze",e}(Une||{}),Vne=function(e){return e[e.Video_Send_Retransmit=2062]="Video_Send_Retransmit",e[e.Video_Send_Target_Encoded=2064]="Video_Send_Target_Encoded",e[e.Video_Send_Actual_Encoded=2060]="Video_Send_Actual_Encoded",e[e.Video_Send_Transmit=2066]="Video_Send_Transmit",e[e.Video_Send_Bandwidth=2061]="Video_Send_Bandwidth",e[e.Video_Capture_Height=2033]="Video_Capture_Height",e[e.Video_Capture_Width=2035]="Video_Capture_Width",e[e.Video_Capture_Frame_Rate=2034]="Video_Capture_Frame_Rate",e[e.Video_Send_Low_Height=2073]="Video_Send_Low_Height",e[e.Video_Send_Low_Frame_Rate=2075]="Video_Send_Low_Frame_Rate",e[e.Video_Send_Low_Width=2077]="Video_Send_Low_Width",e[e.Video_Send_Low_Bitrate=2069]="Video_Send_Low_Bitrate",e[e.Video_Send_Low_Package_Lost=2070]="Video_Send_Low_Package_Lost",e[e.Video_Send_Low_Package_Rate=2071]="Video_Send_Low_Package_Rate",e[e.Video_Send_Frame_Rate=2002]="Video_Send_Frame_Rate",e[e.Video_Send_Width=2003]="Video_Send_Width",e[e.Video_Send_Height=2004]="Video_Send_Height",e[e.Video_Send_Disabled=2095]="Video_Send_Disabled",e[e.Video_Send_Adaptation=2032]="Video_Send_Adaptation",e[e.Video_Send_Player_Status=2128]="Video_Send_Player_Status",e[e.Video_Send_Nacks=2009]="Video_Send_Nacks",e[e.Video_Send_Plis=2010]="Video_Send_Plis",e[e.Video_Send_Firs=2011]="Video_Send_Firs",e[e.Video_Send_Avg_Encode=2007]="Video_Send_Avg_Encode",e[e.Video_Send_Huge_Frame_Sent=2174]="Video_Send_Huge_Frame_Sent",e[e.Video_Send_Bytes_Retransmit=2173]="Video_Send_Bytes_Retransmit",e[e.Video_Send_Packages_Retransmit=2172]="Video_Send_Packages_Retransmit",e[e.Video_Send_Key_Frames_Encoded=2207]="Video_Send_Key_Frames_Encoded",e[e.Video_Send_Bitrate=2012]="Video_Send_Bitrate",e[e.Video_Send_Package_Rate=2031]="Video_Send_Package_Rate",e[e.Video_Send_Package_Lost=2005]="Video_Send_Package_Lost",e[e.Audio_Capture_PCM_Level=2104]="Audio_Capture_PCM_Level",e[e.Audio_Send_Level=2038]="Audio_Send_Level",e[e.Audio_Send_Bitrate=2039]="Audio_Send_Bitrate",e[e.Audio_Send_Package_Rate=2040]="Audio_Send_Package_Rate",e[e.Audio_Send_AEC_Return_Loss=2041]="Audio_Send_AEC_Return_Loss",e[e.Audio_Send_AEC_Return_Loss_Enhancement=2042]="Audio_Send_AEC_Return_Loss_Enhancement",e[e.Audio_Send_Freeze=2081]="Audio_Send_Freeze",e[e.Audio_Send_Disabled=2096]="Audio_Send_Disabled",e[e.Audio_Send_Bytes_Retransmit=2179]="Audio_Send_Bytes_Retransmit",e[e.Audio_Send_Packages_Retransmit=2180]="Audio_Send_Packages_Retransmit",e[e.Video_Recv_Height=2019]="Video_Recv_Height",e[e.Video_Recv_Width=2018]="Video_Recv_Width",e[e.Video_Recv_Frame_Rate_Output=2155]="Video_Recv_Frame_Rate_Output",e[e.Video_Recv_Jitter_Buffer=2023]="Video_Recv_Jitter_Buffer",e[e.Video_Recv_Current_Delay=2024]="Video_Recv_Current_Delay",e[e.Video_Recv_Nacks=2026]="Video_Recv_Nacks",e[e.Video_Recv_Plis=2027]="Video_Recv_Plis",e[e.Video_Recv_Firs=2028]="Video_Recv_Firs",e[e.Video_Recv_Disabled=2101]="Video_Recv_Disabled",e[e.Video_Recv_Player_Status=2129]="Video_Recv_Player_Status",e[e.Video_Recv_I_Frame_Delay=2149]="Video_Recv_I_Frame_Delay",e[e.Video_Render_Frame_Rate_Render=2022]="Video_Render_Frame_Rate_Render",e[e.Video_Render_Freeze_Duration=2156]="Video_Render_Freeze_Duration",e[e.Audio_Render_Level=2043]="Audio_Render_Level",e[e.Audio_Render_Freeze_Time_80ms=2226]="Audio_Render_Freeze_Time_80ms",e[e.Audio_Render_Freeze_Time_200ms=2227]="Audio_Render_Freeze_Time_200ms",e[e.Audio_Render_Freeze_Samples_80ms=2228]="Audio_Render_Freeze_Samples_80ms",e[e.Audio_Render_Freeze_Samples_200ms=2229]="Audio_Render_Freeze_Samples_200ms",e[e.Audio_Recv_PCM_Level=2105]="Audio_Recv_PCM_Level",e[e.Audio_Recv_Disabled=2102]="Audio_Recv_Disabled",e[e.Audio_Recv_Jitter_Buffer=2054]="Audio_Recv_Jitter_Buffer",e[e.Audio_Recv_Current_Delay=2047]="Audio_Recv_Current_Delay",e[e.Audio_Recv_Player_Status=2130]="Audio_Recv_Player_Status",e[e.Audio_Recv_Bitrate=2044]="Audio_Recv_Bitrate",e[e.Audio_Recv_Concealed_Samples=2148]="Audio_Recv_Concealed_Samples",e[e.Audio_Recv_Total_Samples_Received=2224]="Audio_Recv_Total_Samples_Received",e}(Vne||{}),xne=function(e){return e[e.Video_Render_Frame_Rate_Decode=2021]="Video_Render_Frame_Rate_Decode",e[e.Video_Recv_Frame_Rate=2020]="Video_Recv_Frame_Rate",e[e.Video_Recv_Frame_Dropped=2181]="Video_Recv_Frame_Dropped",e[e.Video_Recv_Bytes_Retransmit=2175]="Video_Recv_Bytes_Retransmit",e[e.Video_Recv_Packages_Retransmit=2176]="Video_Recv_Packages_Retransmit",e[e.Video_Recv_Packages_Discarded=2198]="Video_Recv_Packages_Discarded",e[e.Video_Recv_Avg_Decode=2200]="Video_Recv_Avg_Decode",e[e.Video_Recv_Avg_Processing_Delay=2202]="Video_Recv_Avg_Processing_Delay",e[e.Video_Recv_Avg_Assembly_Time=2203]="Video_Recv_Avg_Assembly_Time",e[e.Video_Recv_Avg_Inter_Frame_Delay=2204]="Video_Recv_Avg_Inter_Frame_Delay",e[e.Video_Recv_Key_Frames_Decoded=2206]="Video_Recv_Key_Frames_Decoded",e[e.Video_Recv_Package_Lost=2014]="Video_Recv_Package_Lost",e[e.Video_Recv_Bitrate=2029]="Video_Recv_Bitrate",e[e.Video_Recv_Package_Rate=2078]="Video_Recv_Package_Rate",e[e.Audio_Recv_Jitter=2055]="Audio_Recv_Jitter",e[e.Audio_Recv_Bytes_Retransmit=2178]="Audio_Recv_Bytes_Retransmit",e[e.Audio_Recv_Packages_Retransmit=2177]="Audio_Recv_Packages_Retransmit",e[e.Audio_Recv_Packages_Discarded=2199]="Audio_Recv_Packages_Discarded",e[e.Audio_Recv_Avg_Processing_Delay=2201]="Audio_Recv_Avg_Processing_Delay",e[e.Audio_Recv_Package_Rate=2046]="Audio_Recv_Package_Rate",e[e.Audio_Recv_Package_Lost=2045]="Audio_Recv_Package_Lost",e[e.Audio_Recv_AV_Sync_TIME=2237]="Audio_Recv_AV_Sync_TIME",e}(xne||{}),Fne=function(e){return e[e.RTT=2006]="RTT",e[e.CONN_TYPE=801]="CONN_TYPE",e[e.STATS_UPDATE_INTERVAL=2205]="STATS_UPDATE_INTERVAL",e}(Fne||{}),Bne=function(e){return e[e.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",e[e.PAGE_VISIBILITY=2233]="PAGE_VISIBILITY",e}(Bne||{}),jne=function(e){return e[e.Transport_Send_Bitrate=2234]="Transport_Send_Bitrate",e[e.Transport_Recv_Bitrate=2235]="Transport_Recv_Bitrate",e}(jne||{});const Gne=1e3,Wne=6,Kne=3,Hne=Math.max(Wne,Kne,60);function Yne(e){return e=e.toLowerCase(),Ui(e).call(e,"vp8")?1:Ui(e).call(e,"h264")?2:Ui(e).call(e,"vp9")?3:Ui(e).call(e,"av1")?4:Ui(e).call(e,"h265")?5:0}function Xne(e,t,n){null!=n&&Number.isFinite(n)&&(e[t]=Math.round(Math.max(0,n)))}function Jne(e){const t={[Fne.CONN_TYPE]:0,[Fne.RTT]:e.rtt,[Fne.STATS_UPDATE_INTERVAL]:e.updateInterval?Math.round(Math.max(0,e.updateInterval)):void 0};switch(e.selectedCandidatePair.localCandidate.candidateType){case"relay":{const n=e.selectedCandidatePair.localCandidate.relayProtocol;"udp"===n&&(t[Fne.CONN_TYPE]=1),"tcp"===n&&(t[Fne.CONN_TYPE]=3),"tls"===n&&(t[Fne.CONN_TYPE]=4);break}case"srflx":t[Fne.CONN_TYPE]=2;break;case"unknown":t[Fne.CONN_TYPE]=5;break;default:t[Fne.CONN_TYPE]=0}return t}function zne(e){let t=0;switch(e){case"none":t=0;break;case"cpu":t=1;break;case"bandwidth":t=2;break;case"other":t=3}return t}class Zne extends YN{constructor(e){super(),zA(this,"store",void 0),zA(this,"uploadWRTCStatsTimer",void 0),zA(this,"uploadOutboundDenoiserStatsTimer",void 0),zA(this,"uploadExtStatsTimer",void 0),zA(this,"uploadExtUsageStatsTimer",void 0),zA(this,"uploadInboundExtStatsTimer",void 0),zA(this,"requestStats",void 0),zA(this,"requestTransportStats",void 0),zA(this,"requestLocalMedia",void 0),zA(this,"requestRemoteMedia",void 0),zA(this,"requestAllTracks",void 0),zA(this,"requestVideoIsReady",void 0),zA(this,"requestUploadStats",void 0),zA(this,"requestUpload",void 0),zA(this,"uploadOutboundStarted",!1),zA(this,"uploadInboundStarted",!1),zA(this,"uploadTransportStarted",!1),zA(this,"uploadBaseStatsStarted",!1),zA(this,"uploadExtensionUsageStarted",!1),zA(this,"lastRecvStats",void 0),zA(this,"lastSendStats",void 0),zA(this,"lastRefRecvStats",void 0),zA(this,"lastRefSendStats",void 0),zA(this,"lastNormalRecvStats",void 0),zA(this,"lastNormalSendStats",void 0),zA(this,"lastExtendStats",{}),zA(this,"needUploadStats",{}),zA(this,"needUploadRenderFreezeTime",!0),zA(this,"lastUploadCompensateTime",-1),zA(this,"uploadCompensateDeltaTime",0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const t=e%Kne==0,n=e%Wne==0,i=e%60==0;let r,o;if(this.uploadTransportStarted&&(r=this.requestStats(),this.store.useP2P&&(o=this.requestStats(!0))),!r&&this.uploadOutboundStarted&&(r=this.requestStats()),!o&&this.uploadInboundStarted&&(o=this.requestStats(!0)),r||o){var s;const a={};if(this.uploadTransportStarted&&r){const e=this.getTransportStats(r,t?this.lastRefSendStats:void 0,o,t);e&&(a.misc=[e])}if(this.uploadOutboundStarted&&r){const e=this.getOutboundStats(r,n?this.lastNormalSendStats:void 0,t?this.lastRefSendStats:void 0,this.lastSendStats,i);e&&(a.outbound=[e])}if(this.uploadInboundStarted&&o){this.uploadCompensateStats(e);const i=this.getInboundStats(o,n?this.lastNormalRecvStats:void 0,t?this.lastRefRecvStats:void 0,this.lastRecvStats);i&&(a.inbound=i)}const c=null===(s=this.requestTransportStats)||void 0===s?void 0:s.call(this).connectState;if(c&&(Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[Bne.RTC_PEER_CONNECTION_STATE]=SP[c]):a.misc=[{addition:{[Bne.RTC_PEER_CONNECTION_STATE]:SP[c]}}]),BV.needUploadStats.length>0||n){const e=BV.needUploadStats.shift()||("visible"===BV.visibility?1:0);Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[Bne.PAGE_VISIBILITY]=e):a.misc=[{addition:{[Bne.PAGE_VISIBILITY]:e}}]}this.needUploadStats.sendType&&(Array.isArray(a.outbound)&&a.outbound[0]&&a.outbound[0].high&&(a.outbound[0].high[Mne.Video_Send_Type]=this.needUploadStats.sendType),this.needUploadStats.sendType=void 0),this.requestUploadStats(a)}this.lastRecvStats=o,this.lastSendStats=r,n&&(this.lastNormalRecvStats=o,this.lastNormalSendStats=r),t&&(this.lastRefRecvStats=o,this.lastRefSendStats=r)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0,BV.startCollectStats();let e=1;this.uploadWRTCStatsTimer=window.setInterval((()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var t,n;const e=null===(t=this.requestTransportStats)||void 0===t?void 0:t.call(this);return void(e&&(null===(n=this.requestUploadStats)||void 0===n||n.call(this,{misc:[{addition:{[Bne.RTC_PEER_CONNECTION_STATE]:SP[e.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===Hne+1&&(e=1)}),Gne)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const t=e%Kne==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!t)return;if(-1===this.lastUploadCompensateTime)return void(this.lastUploadCompensateTime=Date.now());const n=Math.max(-6e3,Date.now()-this.lastUploadCompensateTime-6e3);if(this.uploadCompensateDeltaTime+=n,this.lastUploadCompensateTime=Date.now(),this.uploadCompensateDeltaTime<6e3)return;const i=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*i;const r=this.requestStats(!0);new Array(i).fill(0).forEach((()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const e={};if(this.uploadInboundStarted&&r){const t=this.requestRemoteMedia()||[],n=[];t.forEach((e=>{let t=KC(e,2),i=t[0],o=t[1];const s={peer:i.uid};if((i._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(i._videoSSRC)||!1)&&o.has(UF.VIDEO)&&i.videoTrack){const e=function(e,t,n){if(!t.videoRecv.find((t=>t.ssrc===e)))return;const i={};if(n&&n._player){const e=n._player,t=e.renderFreezeAccTime2,r=e.videoElementStatus;if("visible"===BV.visibility&&r===Fk.PLAYING&&JL().supportRequestVideoFrameCallback){const n=Math.min(6e3,t);e.renderFreezeAccTime2=Math.max(0,t-n),Xne(i,Une.Video_Render_Freeze_Time_Render2,n),xP("USE_NEW_RENDER_FREEZE_TIME")&&Xne(i,Une.Video_Render_Freeze_Time_Render,n)}}return i}(i._videoSSRC,r,i.videoTrack);e&&(s.video=e)}s.video&&n.push(s)})),n.length>0&&(e.inbound=n,this.requestUploadStats(e))}}))}stopUploadWRTCStats(){window.clearInterval(this.uploadWRTCStatsTimer),this.uploadWRTCStatsTimer=void 0,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(e,t,n,i){if(!this.requestStats)return;if(!i)return null==e.rtt?void 0:{addition:{[Fne.RTT]:e.rtt,[Fne.CONN_TYPE]:void 0,[Fne.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const r=Jne(e);if(this.store.useP2P){if(n){const e=Jne(n);r[Fne.CONN_TYPE]&&e[Fne.CONN_TYPE]&&(r[Fne.CONN_TYPE]+=e[Fne.CONN_TYPE]<<3)}r[Fne.CONN_TYPE]?r[Fne.CONN_TYPE]+=110:r[Fne.CONN_TYPE]=110}else{r[Fne.CONN_TYPE]?r[Fne.CONN_TYPE]+=100:r[Fne.CONN_TYPE]=100;const n=function(e,t){if(t)return[Math.ceil(8*(e.transport.bytesSent-t.transport.bytesSent)/(e.timestamp-t.timestamp)),Math.ceil(8*(e.transport.bytesReceived-t.transport.bytesReceived)/(e.timestamp-t.timestamp))];return[0,0]}(e,t);r[jne.Transport_Send_Bitrate]=n[0],r[jne.Transport_Recv_Bitrate]=n[1]}return{addition:r}}getOutboundStats(e,t,n,i,r){if(!this.requestUploadStats||!this.requestLocalMedia)return;const o=this.requestLocalMedia();if(!o||0===o.length)return;let s,a,c;return o.forEach((i=>{let o=KC(i,2),d=o[0],l=o[1],u=l.track,h=l.ssrcs;switch(d){case BF.LocalVideoLowTrack:case BF.LocalVideoTrack:if(d===BF.LocalVideoTrack){var p;const i=function(e,t,n,i,r,o){const s=t.videoSend.find((t=>t.ssrc===e));if(!s)return;const a={},c=s.sentFrame,d=s.inputFrame;if(i&&(Xne(a,Une.Video_Send_Qp_Sum,s.qpSumPerFrame),s.codec&&Xne(a,Une.Video_Send_Codec,Yne(s.codec)),"number"==typeof s.powerEfficientEncoder&&Xne(a,Une.Video_Send_Power_Efficient_Encoder,s.powerEfficientEncoder),d&&c)){const e=d.frameRate,t=c.frameRate;a[Une.Video_Send_Freeze]=function(e,t){let n=!0;return n=!(e<=5)&&(e<=10?t<3:e<=20?t<4:t<5),n}(e,t)?1:0}if(r){switch(c&&(Xne(a,Vne.Video_Send_Height,c.height),Xne(a,Vne.Video_Send_Width,c.width),Xne(a,Vne.Video_Send_Frame_Rate,c.frameRate)),a[Vne.Video_Send_Disabled]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0,s.adaptionChangeReason){case"none":a[Vne.Video_Send_Adaptation]=0;break;case"cpu":a[Vne.Video_Send_Adaptation]=1;break;case"bandwidth":a[Vne.Video_Send_Adaptation]=2;break;case"other":a[Vne.Video_Send_Adaptation]=3}let i=0;s.adaptionChangeReason&&(i+=zne(s.adaptionChangeReason)),t.qualityLimitationReason&&(i+=zne(t.qualityLimitationReason)<<3),a[Vne.Video_Send_Adaptation]=i,a[Vne.Video_Send_Player_Status]=jk[n._player?n._player.videoElementStatus:"uninit"],Xne(a,Vne.Video_Send_Nacks,s.nacksCount),Xne(a,Vne.Video_Send_Plis,s.plisCount),Xne(a,Vne.Video_Send_Firs,s.firsCount),Xne(a,Vne.Video_Send_Avg_Encode,s.avgEncodeMs),Xne(a,Vne.Video_Send_Huge_Frame_Sent,s.hugeFramesSent),Xne(a,Vne.Video_Send_Bytes_Retransmit,s.retransmittedBytesSent),Xne(a,Vne.Video_Send_Packages_Retransmit,s.retransmittedPacketsSent),Xne(a,Vne.Video_Send_Key_Frames_Encoded,s.keyFramesEncoded);const o=r.videoSend.find((t=>t.ssrc===e));if(o){let e=Gne*Kne;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.packets&&null!=s.packets&&Xne(a,Vne.Video_Send_Package_Rate,1e3*(s.packets-o.packets)/e),null!=s.packetsLost&&null!=o.packetsLost&&Xne(a,Vne.Video_Send_Package_Lost,s.packetsLost-o.packetsLost),null!=o.bytes&&null!=s.bytes&&Xne(a,Vne.Video_Send_Bitrate,8*(s.bytes-o.bytes)/e)}}return a}(h[0].ssrcId,e,u,t,n),o="CameraVideoTrack"===u.__className__?3:Ui(p=u._hints).call(p,Rk.SCREEN_TRACK)?7:10;(this.lastExtendStats.sendType!==o||r)&&(this.needUploadStats={sendType:o},this.lastExtendStats.sendType=o);const s=u&&function(e,t,n,i){const r=t.videoSend.find((t=>t.ssrc===e));if(!r)return null;const o={};if(i){const e=r.inputFrame,t=e&&e.height||n.videoHeight||0,i=e&&e.width||n.videoWidth||0,s=e&&e.frameRate||0;Xne(o,Vne.Video_Capture_Height,t),Xne(o,Vne.Video_Capture_Width,i),Xne(o,Vne.Video_Capture_Frame_Rate,s)}return o}(h[0].ssrcId,e,u,!!n),c=function(e,t){const n={};return t&&(Xne(n,Vne.Video_Send_Retransmit,e.bitrate.retransmit),Xne(n,Vne.Video_Send_Target_Encoded,e.bitrate.targetEncoded),Xne(n,Vne.Video_Send_Actual_Encoded,e.bitrate.actualEncoded),Xne(n,Vne.Video_Send_Transmit,e.bitrate.transmit),Xne(n,Vne.Video_Send_Bandwidth,e.sendBandwidth)),n}(e,!!n);a=Object.assign({},i,s,c)}else c=function(e,t,n,i,r){const o=t.videoSend.find((t=>t.ssrc===e));if(!o)return;const s={};if(i){const t=o.sentFrame;t&&(Xne(s,Vne.Video_Send_Low_Height,t.height),Xne(s,Vne.Video_Send_Low_Width,t.width),Xne(s,Vne.Video_Send_Low_Frame_Rate,t.frameRate));const n=i.videoSend.find((t=>t.ssrc===e));if(n){let e=Gne*Wne;n.timestamp&&o.timestamp&&(e=o.timestamp-n.timestamp),null!=n.packets&&null!=o.packets&&Xne(s,Vne.Video_Send_Low_Package_Rate,1e3*(o.packets-n.packets)/e),null!=o.packetsLost&&null!=n.packetsLost&&Xne(s,Vne.Video_Send_Low_Package_Lost,o.packetsLost-n.packetsLost),null!=n.bytes&&null!=o.bytes&&Xne(s,Vne.Video_Send_Low_Bitrate,8*(o.bytes-n.bytes)/e)}}return s}(h[0].ssrcId,e,0,n);break;case BF.LocalAudioTrack:s=u&&function(e,t,n,i,r,o){const s=t.audioSend.find((t=>t.ssrc===e));if(!s)return;const a={};if(r){a[Vne.Audio_Send_Disabled]=n._originMediaStreamTrack&&!n._originMediaStreamTrack.enabled||n._mediaStreamTrack&&!n._mediaStreamTrack.enabled?1:0;const t=100*n._source.getAccurateVolumeLevel(),i=s.inputLevel;if(null!=i){const e=Math.ceil(50*Math.log10(100*i+1));Xne(a,Vne.Audio_Send_Level,e)}Xne(a,Vne.Audio_Capture_PCM_Level,t),Xne(a,Vne.Audio_Send_AEC_Return_Loss,s.aecReturnLoss),Xne(a,Vne.Audio_Send_AEC_Return_Loss_Enhancement,s.aecReturnLossEnhancement),Xne(a,Vne.Audio_Send_Bytes_Retransmit,s.retransmittedBytesSent),Xne(a,Vne.Audio_Send_Packages_Retransmit,s.retransmittedPacketsSent),a[Vne.Audio_Send_Freeze]=0;const o=r.audioSend.find((t=>t.ssrc===e));if(o){let e=Gne*Wne;o.timestamp&&s.timestamp&&(e=s.timestamp-o.timestamp),null!=o.bytes&&null!=s.bytes&&Xne(a,Vne.Audio_Send_Bitrate,8*(s.bytes-o.bytes)/e),null!=o.packets&&null!=s.packets&&Xne(a,Vne.Audio_Send_Package_Rate,1e3*(s.packets-o.packets)/e)}}return a}(h[0].ssrcId,e,u,0,n)}})),{high:a,low:c,audio:s}}getInboundStats(e,t,n,i){if(!this.requestRemoteMedia)return;const r=this.requestRemoteMedia()||[],o=[];return r.forEach((r=>{let s=KC(r,2),a=s[0],c=s[1];const d={peer:a.uid};let l;if(c.has(UF.VIDEO)&&a.videoTrack){const r=a._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(a._videoSSRC)||!1,o=a.videoTrack?function(e,t,n,i,r,o,s,a){const c=t.videoRecv.find((t=>t.ssrc===e));if(!c)return;const d={},l=c.receivedFrame,u=c.outputFrame,h=c.decodeFrameRate;Xne(d,xne.Video_Render_Frame_Rate_Decode,h),c.framesRateFirefox&&Xne(d,xne.Video_Recv_Frame_Rate,c.framesRateFirefox),l&&Xne(d,xne.Video_Recv_Frame_Rate,l.frameRate),Xne(d,xne.Video_Recv_Frame_Dropped,c.framesDroppedCount),Xne(d,xne.Video_Recv_Bytes_Retransmit,c.retransmittedBytesReceived),Xne(d,xne.Video_Recv_Packages_Retransmit,c.retransmittedPacketsReceived),Xne(d,xne.Video_Recv_Packages_Discarded,c.packetsDiscarded),Xne(d,xne.Video_Recv_Avg_Decode,c.avgDecodeMs),Xne(d,xne.Video_Recv_Avg_Processing_Delay,c.avgProcessingDelayMs),Xne(d,xne.Video_Recv_Avg_Assembly_Time,c.avgFramesAssembledFromMultiplePacketsMs),Xne(d,xne.Video_Recv_Avg_Inter_Frame_Delay,c.avgInterFrameDelayMs),Xne(d,xne.Video_Recv_Key_Frames_Decoded,c.keyFramesDecoded);const p=a&&a.videoRecv.find((t=>t.ssrc===e));if(p){const e=t.timestamp-a.timestamp||Gne;null!=c.packetsLost&&null!=p.packetsLost&&Xne(d,xne.Video_Recv_Package_Lost,c.packetsLost-p.packetsLost),null!=p.bytes&&null!=c.bytes&&Xne(d,xne.Video_Recv_Bitrate,8*(c.bytes-p.bytes)/e),null!=p.packets&&null!=c.packets&&Xne(d,xne.Video_Recv_Package_Rate,1e3*(c.packets-p.packets)/e)}const _=o&&o.videoRecv.find((t=>t.ssrc===e));if(_&&(Xne(d,Une.Video_Recv_Qp_Sum,c.qpSumPerFrame),c.codec&&Xne(d,Une.Video_Recv_Codec,Yne(c.codec)),"number"==typeof c.powerEfficientDecoder&&Xne(d,Une.Video_Recv_Power_Efficient_Decoder,c.powerEfficientDecoder),d[Une.Video_Recv_Freeze]=i&&Bte.isRemoteVideoFreeze(n,c,_)?1:0),s){var E;const t=s.videoRecv.find((t=>t.ssrc===e));l?(Xne(d,Vne.Video_Recv_Height,l.height),Xne(d,Vne.Video_Recv_Width,l.width)):n&&(Xne(d,Vne.Video_Recv_Height,n._videoHeight||0),Xne(d,Vne.Video_Recv_Width,n._videoWidth||0)),u&&Xne(d,Vne.Video_Recv_Frame_Rate_Output,u.frameRate);const i=null===(E=n._player)||void 0===E?void 0:E.rendFrameRate.toFixed(0);if(i&&Xne(d,Vne.Video_Render_Frame_Rate_Render,+i),Xne(d,Vne.Video_Recv_Jitter_Buffer,c.jitterBufferMs),Xne(d,Vne.Video_Recv_Current_Delay,c.currentDelayMs),Xne(d,Vne.Video_Recv_Firs,c.firsCount),Xne(d,Vne.Video_Recv_Nacks,c.nacksCount),Xne(d,Vne.Video_Recv_Plis,c.plisCount),n){d[Vne.Video_Recv_Disabled]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1;const e=n._player;if(e){const n=e.freezeTimeCounterList,i=e.renderFreezeAccTime,o=e.renderFreezeAccTime2,s=e.videoElementStatus;if(n&&n.length>0&&Xne(d,Une.Video_Render_Freeze_Time,n.splice(0,1)[0]),r&&"visible"===BV.visibility&&s===Fk.PLAYING&&JL().supportRequestVideoFrameCallback){const t=Math.min(6e3,o);e.renderFreezeAccTime2=Math.max(0,o-t),Xne(d,Une.Video_Render_Freeze_Time_Render2,t);const n=Math.min(6e3,i);e.renderFreezeAccTime=Math.max(0,i-n),Xne(d,Une.Video_Render_Freeze_Time_Render,xP("USE_NEW_RENDER_FREEZE_TIME")?t:n)}if("number"==typeof c.totalFreezesDuration){const e=t&&t.totalFreezesDuration?c.totalFreezesDuration-t.totalFreezesDuration:c.totalFreezesDuration;Xne(d,Vne.Video_Render_Freeze_Duration,1e3*e)}}}if(d[Vne.Video_Recv_Player_Status]=jk[n._player?n._player.videoElementStatus:"uninit"],t&&void 0!==c.totalInterFrameDelay&&void 0!==c.totalSquaredInterFrameDelay&&void 0!==t.totalInterFrameDelay&&void 0!==t.totalSquaredInterFrameDelay){const e=c.totalInterFrameDelay-t.totalInterFrameDelay,n=c.totalSquaredInterFrameDelay-t.totalSquaredInterFrameDelay,i=c.framesDecodeCount-t.framesDecodeCount,r=e/i*1e3,o=Math.round(1e3*Math.sqrt((n-Math.pow(e,2)/i)/i));!isNaN(o)&&r+o>Math.max(3*r,r+150)&&(d[Vne.Video_Recv_I_Frame_Delay]=o)}}return d}(a._videoSSRC,e,a.videoTrack,!0===r,this.needUploadRenderFreezeTime,t,n,i):void 0;if(o&&(d.video=o),a.videoTrack){const t=e.videoRecv.find((e=>e.ssrc===a._videoSSRC));t&&t.estimatedPlayoutTimestamp&&(l=t.estimatedPlayoutTimestamp)}}if(c.has(UF.AUDIO)&&a.audioTrack){const r=!a.hasAudio,o=a.audioTrack?function(e,t,n,i,r,o){let s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];const a=t.audioRecv.find((t=>t.ssrc===e));if(!a)return;const c={};Xne(c,xne.Audio_Recv_Jitter,a.jitterMs),Xne(c,xne.Audio_Recv_Bytes_Retransmit,a.retransmittedBytesReceived),Xne(c,xne.Audio_Recv_Packages_Retransmit,a.retransmittedPacketsReceived),Xne(c,xne.Audio_Recv_Packages_Discarded,a.packetsDiscarded),Xne(c,xne.Audio_Recv_Avg_Processing_Delay,a.avgProcessingDelayMs);const d=o&&o.audioRecv.find((t=>t.ssrc===e));if(d){const e=Gne;null!=a.packets&&null!=d.packets&&Xne(c,xne.Audio_Recv_Package_Rate,1e3*(a.packets-d.packets)/e),null!=a.packetsLost&&null!=d.packetsLost&&Xne(c,xne.Audio_Recv_Package_Lost,a.packetsLost-d.packetsLost)}if(i){const e=a.receivedFrames,t=a.droppedFrames;null!=e&&null!=t&&(c[Une.Audio_Recv_Freeze]=0===(l=e)||100*t/l>20?1:0)}var l;if(r){const t=100*n._source.getAccurateVolumeLevel(),i=a.outputLevel;if(null!=i){const e=Math.ceil(50*Math.log10(100*i+1));Xne(c,Vne.Audio_Render_Level,e)}Xne(c,Vne.Audio_Recv_PCM_Level,t),n&&(c[Vne.Audio_Recv_Disabled]=n._originMediaStreamTrack.enabled&&n._mediaStreamTrack.enabled?0:1),Xne(c,Vne.Audio_Recv_Jitter_Buffer,a.jitterBufferMs),Xne(c,Vne.Audio_Recv_Current_Delay,a.jitterBufferMs),c[Vne.Audio_Recv_Player_Status]=jk[CM.getPlayerState(n.getTrackId())];const o=r.audioRecv.find((t=>t.ssrc===e));if(o&&(null!=o.bytes&&null!=a.bytes&&Xne(c,Vne.Audio_Recv_Bitrate,8*(a.bytes-o.bytes)/(Gne*Kne)),!s)){const e=a.concealedSamples-o.concealedSamples;e>0&&Xne(c,Vne.Audio_Recv_Concealed_Samples,e);const t=a.totalSamplesReceived-o.totalSamplesReceived;t>0&&Xne(c,Vne.Audio_Recv_Total_Samples_Received,t);const n=a.freezeSamples80-o.freezeSamples80;n>0&&Xne(c,Vne.Audio_Render_Freeze_Samples_80ms,n);const i=a.freezeSamples200-o.freezeSamples200;i>0&&Xne(c,Vne.Audio_Render_Freeze_Samples_200ms,i);const r=a.freezeMs80-o.freezeMs80;Xne(c,Vne.Audio_Render_Freeze_Time_80ms,r<0?0:r);const s=a.freezeMs200-o.freezeMs200;Xne(c,Vne.Audio_Render_Freeze_Time_200ms,s<0?0:s)}}return c}(a._audioSSRC,e,a.audioTrack,t,n,i,r):void 0;if(o&&(d.audio=o),a.audioTrack&&l){const t=e.audioRecv.find((e=>e.ssrc===a._audioSSRC));if(t&&t.estimatedPlayoutTimestamp){const e=t.estimatedPlayoutTimestamp-l;d.audio?d.audio[xne.Audio_Recv_AV_Sync_TIME]=e:d.audio={[xne.Audio_Recv_AV_Sync_TIME]:e}}}}(d.video||d.audio)&&o.push(d)})),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,o}startUploadTransportStats(){this.uploadTransportStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats()}stopUploadTransportStats(){this.uploadTransportStarted=!1}startUploadOutboundStats(){this.uploadOutboundStarted||(this.uploadOutboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;const e=(this.requestAllTracks()||[]).find((e=>e instanceof AU));if(e&&e._external.getDenoiserStats){const t=e._external.getDenoiserStats();t&&this.requestUpload(oF.DENOISER_STATS,t)}}),2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval((()=>{if(!this.requestAllTracks||!this.requestUpload)return;this.requestAllTracks().forEach((e=>{e.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}))}),2e3))}stopUploadOutboundStats(){this.uploadOutboundStarted&&(this.uploadOutboundStarted=!1,this.lastSendStats&&(this.lastSendStats.videoSend=[],this.lastSendStats.audioSend=[],this.lastSendStats=void 0),this.lastRefSendStats&&(this.lastRefSendStats.videoSend=[],this.lastRefSendStats.audioSend=[],this.lastRefSendStats=void 0),this.lastNormalSendStats&&(this.lastNormalSendStats.videoSend=[],this.lastNormalSendStats.audioSend=[],this.lastNormalSendStats=void 0),this.lastExtendStats={},this.needUploadStats={},this.uploadOutboundDenoiserStatsTimer&&window.clearInterval(this.uploadOutboundDenoiserStatsTimer),this.uploadOutboundDenoiserStatsTimer=void 0,this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=void 0)}startUploadInboundStats(){this.uploadInboundStarted||(this.uploadInboundStarted=!0,this.uploadWRTCStatsTimer||this.startUploadWRTCStats(),this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=window.setInterval((()=>{if(!this.requestUpload||!this.requestRemoteMedia)return;(this.requestRemoteMedia()||[]).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1];if(i.has(UF.VIDEO)&&n.videoTrack){n.videoTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}if(i.has(UF.AUDIO)&&n.audioTrack){n.audioTrack.getProcessorStats().forEach((e=>{this.requestUpload&&this.requestUpload(e.type,e.stats)}))}}))}),2e3))}stopUploadInboundStats(){this.uploadInboundStarted&&(this.uploadInboundStarted=!1,this.lastRecvStats&&(this.lastRecvStats.videoRecv=[],this.lastRecvStats.audioRecv=[],this.lastRecvStats=void 0),this.lastRefRecvStats&&(this.lastRefRecvStats.videoRecv=[],this.lastRefRecvStats.audioRecv=[],this.lastRefRecvStats=void 0),this.lastNormalRecvStats&&(this.lastNormalRecvStats.videoRecv=[],this.lastNormalRecvStats.audioRecv=[],this.lastNormalRecvStats=void 0),this.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0,this.uploadInboundExtStatsTimer&&window.clearInterval(this.uploadInboundExtStatsTimer),this.uploadInboundExtStatsTimer=void 0)}startUploadExtensionUsageStats(){if(this.uploadExtensionUsageStarted)return;this.uploadExtensionUsageStarted=!0,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer);const e=new Map;this.uploadExtUsageStatsTimer=window.setInterval((async()=>{const t=Date.now(),n={connectionInterval:xP("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:t};let i=[];const r=this.requestAllTracks&&this.requestAllTracks()||[];for(const e of r)!e.muted&&e.enabled&&(i=i.concat(await e.getProcessorUsage()));const o=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const e of o){var s=KC(e,2);const t=s[0],n=s[1];n.has(UF.VIDEO)&&t.videoTrack&&(i=i.concat(await t.videoTrack.getProcessorUsage())),n.has(UF.AUDIO)&&t.audioTrack&&(i=i.concat(await t.audioTrack.getProcessorUsage()))}if(0===i.length)return;n.details=function(e,t){const n={};for(const s of e){var i;const e=s.id,a=s.value,c=s.level,d=s.direction,l=null!==(i=t.get(e))&&void 0!==i?i:0,u=2===a?l+xP("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:l;var r,o;t.set(e,u),n[e]?(2===a&&(n[e].value=a),c>n[e].level&&(n[e].level=c),"remote"===d&&(n[e].remoteUidCount+=1),n[e].totalTs=null!==(r=t.get(e))&&void 0!==r?r:0):n[e]={value:a,level:c,remoteUidCount:"local"===d?0:1,totalTs:null!==(o=t.get(e))&&void 0!==o?o:0}}return Object.keys(n).map((e=>{const t=n[e];return{id:e,level:t.level,value:t.value,totalTs:t.totalTs}}))}(i,e);const a=Date.now(),c=a>t?a:t+1;this.requestUpload&&this.requestUpload(oF.EXTENSION_USAGE_STATS,{usageStats:n,sendTs:c})}),xP("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1,BV.stopCollectStats()}}const qne=xP("ICE_RESTART_INTERVAL");let Qne=new Map,$ne=new Map,eie=[VF.UDP_TCP_RELAY,VF.TCP_RELAY,VF.RELAY],tie=xP("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&JL().supportPCSetConfiguration;function nie(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const n=Qne.get(e.id);n&&(window.clearTimeout(n),Qne.delete(e.id));const i=$ne.get(e.id);t&&i&&i.index===eie.length-1&&(SL.debug("[".concat(e.id,"] reset ICE restart policy")),$ne.delete(e.id))}function iie(e,t,n){if(0===Qne.size&&0===$ne.size&&(Array.isArray(xP("RESTART_SEQUENCE"))&&xP("RESTART_SEQUENCE").length>0&&!function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){const i=e[n];if(e.filter((e=>e===i)).length!==t.filter((e=>e===i)).length)return!1}return!0}(eie,xP("RESTART_SEQUENCE"))&&(eie=xP("RESTART_SEQUENCE").filter((e=>{var t;if(Ui(t=Object.values(VF)).call(t,e))return!0})),SL.debug("use reconnection policy from config distribution, queues: ".concat(eie.join(" => ")))),tie=xP("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&JL().supportPCSetConfiguration),0===eie.length)return void n();let i,r=$ne.get(e.id)||{},o=r.index,s=void 0===o?0:o,a=r.type;if(tie&&a===VF.RELAY)return void n();let c=a&&s>=eie.length-1;if(tie)a=VF.RELAY;else{if(c)return void n();a?(s++,a=eie[s]):(a=eie[0],s=0)}SL.debug("[".concat(e.id,"] choose ICE restart policy: ").concat(a,", index: ").concat(s)),t(a),$ne.set(e.id,{index:s,type:a}),i=window.setTimeout((()=>iie(e,t,n)),qne),Qne.set(e.id,i)}var rie;function oie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function sie(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?oie(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oie(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function aie(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=Yw,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new cie(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function cie(e){function t(e){if(Object(e)!==e)return cp.reject(new TypeError(e+" is not an object."));var t=e.done;return cp.resolve(e.value).then((function(e){return{value:e,done:t}}))}return cie=function(e){this.s=e,this.n=e.next},cie.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?cp.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?cp.reject(e):t(n.apply(this.s,arguments))}},new cie(e)}let die=(rie=class extends YN{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(GF.StateChange,t,this._state)}constructor(e,t){super(),zA(this,"isPlanB",void 0),zA(this,"store",void 0),zA(this,"statsUploader",void 0),zA(this,"connection",void 0),zA(this,"localTrackMap",new Map),zA(this,"remoteUserMap",new Map),zA(this,"localDataChannels",[]),zA(this,"remoteDataChannelMap",new Map),zA(this,"pendingLocalTracks",[]),zA(this,"pendingRemoteTracks",[]),zA(this,"pendingLocalDataChannels",[]),zA(this,"pendingRemoteDataChannels",[]),zA(this,"statsCollector",void 0),zA(this,"shouldForwardP2PCreation",void 0),zA(this,"iceFailedCount",0),zA(this,"dtlsFailedCount",0),zA(this,"mutex",void 0),zA(this,"_state",jF.Disconnected),zA(this,"_p2pBySDPEndPoint",!1),zA(this,"_pcStatsUploadType",xP("NEW_ICE_RESTART")?xF.FIRST_CONNECTION:xF.OLD_FIRST_CONNECTION),zA(this,"_isStartRestartIce",!1),zA(this,"_restartTimer",void 0),zA(this,"_isTryConnecting",!1),zA(this,"_iceError",null),zA(this,"_forceTurn",!1),zA(this,"_isWaitPcToRePub",!1),zA(this,"handleMuteLocalTrack",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==jF.Connected)return void n(new ON(wN.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const r=this.filterTobeMutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>"videoLowTrack"===e[0]));if(o){const e=o[1];this.store.enableInstantMuteRestore?(e.track._originMediaStreamTrack.enabled=!1,SL.info("[".concat(this.store.clientId,"] P2PChannel muteLocalLowTrack without close sender because enableInstantMuteRestore is true"))):e.track._originMediaStreamTrack.stop()}this.store.enableInstantMuteRestore?SL.info("[".concat(this.store.clientId,"] P2PChannel muteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.muteLocal(r.map((e=>KC(e,2)[1].id)));const s=this.createMuteMessage(r);await lD(this,GF.RequestMuteLocal,s),t()}catch(e){n(e)}finally{i()}})),zA(this,"handleUnmuteLocalTrack",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==jF.Connected)return void n(new ON(wN.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();const o=r.find((e=>"videoLowTrack"===e[0]));if(o){const t=o[1];if(this.store.enableInstantMuteRestore)t.track._originMediaStreamTrack.enabled=!0,SL.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalLowTrack without close sender because enableInstantMuteRestore is true"));else{if(t.track._originMediaStreamTrack.stop(),!xP("DISABLE_DUAL_STREAM_USE_ENCODING")&&JL().supportDualStreamEncoding){const n=e._mediaStreamTrack.clone();t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n}else{const n=kne(e,hD(this,GF.RequestLowStreamParameter));t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n}await new cp(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}this.store.enableInstantMuteRestore?SL.info("[".concat(this.store.clientId,"] P2PChannel unmuteLocalTrack without close sender because enableInstantMuteRestore is true")):await this.connection.unmuteLocal(r.map((e=>KC(e,2)[1].id)));const s=this.createUnmuteMessage(r);await lD(this,GF.RequestUnmuteLocal,s),t()}catch(e){n(e)}finally{i()}})),zA(this,"handleUpdateVideoEncoder",(async(e,t,n,i)=>{let r;i||(r=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const n=this.localTrackMap.get(BF.LocalVideoTrack);if(!this.connection||!n||n.track!==e||this.state!==jF.Connected)return void t();const i=n.id,s=n.track;await this.connection.updateSendParameters(i,s),await this.connection.updateEncoderConfig(i,s),this.emit(GF.UpdateVideoEncoder,s),t()}catch(e){n(e)}finally{var o;null===(o=r)||void 0===o||o()}})),zA(this,"handleUpdateVideoSendParameters",(async(e,t,n)=>{const i=await this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const n=this.localTrackMap.get(BF.LocalVideoTrack);if(!this.connection||!n||n.track!==e||this.state!==jF.Connected)return void t();const r=n.id,o=n.track;await this.connection.updateSendParameters(r,o),t()}catch(e){n(e)}finally{i()}})),zA(this,"handleReplaceMixingTrack",(async(e,t,n,i)=>{if(!this.connection||this.state!==jF.Connected)return void t();const r=Cne([e]);let o;SL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(r.getTrackId(),"]")),"boolean"==typeof i&&i||(o=await this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{await this.replaceTrack(e,r),t()}catch(e){n(e)}finally{var s;null===(s=o)||void 0===s||s()}})),zA(this,"handleReplaceTrack",(async(e,t,n,i)=>{let r;SL.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof i&&i||(r=await this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var o;const n=Array.from(this.localTrackMap.entries()).find((t=>{let n=KC(t,2)[1].track;return e===n}));if(!this.connection||!n||this.state!==jF.Connected)return void t();if(await(null===(o=this.connection)||void 0===o?void 0:o.replaceTrack(e,n[1].id)),this.isPlanB){const t=n[1];t.id=e._mediaStreamTrack.id,this.localTrackMap.set(n[0],t)}if(n[0]===BF.LocalVideoTrack&&!xP("DISABLE_DUAL_STREAM_USE_ENCODING")&&JL().supportDualStreamEncoding){const t=this.localTrackMap.get(BF.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new cp(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}t()}catch(e){n(e)}finally{var s;null===(s=r)||void 0===s||s()}})),zA(this,"handleGetRTCStats",(e=>{e(this.statsCollector.getRTCStats())})),zA(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),zA(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),zA(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),zA(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Zne(this.store),this.bindStatsUploaderEvents(),this.mutex=new JD("P2PChannel-mutex",this.store.clientId),this.isPlanB=!JL().supportUnifiedPlan||xP("CHROME_FORCE_PLAN_B")&&SN(),this.shouldForwardP2PCreation=xP("FORWARD_P2P_CREATION")&&JL().supportPCSetConfiguration&&(gN()||xP("ENABLE_JOIN_V4")),this.shouldForwardP2PCreation&&this.recreateConnection()}async startP2PConnection(e,t){var n;this.state=jF.New,this._forceTurn=wne(e),SL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const i=this.shouldForwardP2PCreation&&"closed"===(null===(n=this.connection)||void 0===n?void 0:n.peerConnectionState);if((!this.shouldForwardP2PCreation||i||t)&&((i||t)&&this.connection&&(SL.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.recreateConnection(e)),!this.connection)throw new ON(wN.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=xP("NEW_ICE_RESTART")?xF.FIRST_CONNECTION:xF.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(e),this.connection.establishPromise}updateConnectionConfiguration(e){var t;null===(t=this.connection)||void 0===t||t.setConfiguration(e)}markSDPEndpointConnection(){this._p2pBySDPEndPoint=!0}async connect(e){if(!this.connection)throw new ON(wN.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");if(!this.isPreallocation()||this.state!==jF.Connected){this.store.peerConnectionStart();const t=await this.connection.connect(e);return this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=jF.Connected,t}if(this.connection instanceof Pne||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name)if(this.store.flexiblePC);else{const t=this.connection.checkDtlsParameters(e.dtlsParameters.fingerprints),n=vee(e.iceParameters.iceUfrag,e.iceParameters.icePwd);n||SL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] ice parameters mismatch, length: ").concat(e.iceParameters.iceUfrag.length," / ").concat(e.iceParameters.icePwd.length));const i=this.connection.checkIceParameters(e.iceParameters),r=t||!n||i&&!(this.connection instanceof Pne);if(r||i){SL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] dtls parameters mismatch, ").concat(r?"try next":"restart ICE"));return HL.reportApiInvoke(this.store.sessionId,{name:t?zN.MISMATCH_DTLS_PARAMETERS:zN.MISMATCH_ICE_PARAMETERS,options:t?[e.dtlsParameters.fingerprints]:[e.iceParameters],tag:ZN.TRACER}).onSuccess(),void this.emit(GF.RequestReconnect)}}await this.connection.updateRemoteConnect(e)}updateRemoteRTPCapabilities(e){const t=Array.from(this.localTrackMap.entries()).filter((e=>{var t;let n=KC(e,1)[0];return Ui(t=[BF.LocalVideoLowTrack,BF.LocalVideoTrack]).call(t,n)})),n=t.map((e=>KC(e,2)[1].id)),i=t.map((e=>KC(e,1)[0]));if(this.connection instanceof Pne||this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name){if(HL.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(i),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(e)}),!Ui(e).call(e,this.store.codec)){const t=["vp9","vp8","h264"].find((t=>Ui(e).call(e,t)));t&&(this.store.codec=t,SL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(t,".")))}this.connection.updateRemoteRTPCapabilities(n,e)}}async getEstablishParams(){var e;return this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof Pne&&"closed"!==this.connection.peerConnectionState&&Ui(e=[jF.New,jF.Connected]).call(e,this.state)?this.connection.establishPromise:void 0}async publishDataChannel(e){if(!this.connection||this.state!==jF.Connected){if(this.state===jF.Disconnected)throw new ON(wN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return e.forEach((e=>{var t;Ui(t=this.pendingLocalDataChannels).call(t,e)||this.pendingLocalDataChannels.push(e)})),[]}const t=this.filterTobePublishedDataChannels(e);return 0===t.length?[]:(t.forEach((e=>{const t=Date.now();this.store.publish(e.id.toString(),"datachannel",t)})),await this.connection.createDataChannels(this.store.uid,t),t.forEach((e=>{this.localDataChannels.push(e);const t=Date.now();this.store.publish(e.id+"","datachannel",void 0,t)})),e.map((e=>({streamId:e.id,ordered:e.ordered,maxRetransmits:e.maxRetransmits,metadata:e.metadata,channelId:e._originDataChannelId}))))}publish(e,t,n){var i=this;return Ww((function*(){const r=yield Kw(i.mutex.lock("From P2PChannel.publish"));try{var o;const s=i.connection&&Ui(o=["disconnected","failed"]).call(o,i.connection.peerConnectionState);if(!i.connection||i.state!==jF.Connected||s){if(i.state===jF.Disconnected)throw new ON(wN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");i.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===i.pendingLocalTracks.indexOf(e)));return i.pendingLocalTracks=i.pendingLocalTracks.concat(t),void(s&&(i._isWaitPcToRePub=!0))}i.store.pubId=i.store.pubId+1,Vte.markPublishStart(i.store.clientId,i.store.pubId);const a=i.filterTobePublishedTracks(e,t,n);if(0===a.length)return void(yield Kw(i.tryToUnmuteAudio(e)));yield*Hw(aie(i.doPublish(i.connection,a)))}finally{r()}}))()}doPublish(e,t){var n=this;return Ww((function*(){t.forEach((e=>{let t=e.track,i=e.type;const r=Date.now();n.store.publish(t.getTrackId(),i===BF.LocalAudioTrack?"audio":"video",r)})),n.bindLocalTrackEvents(t);const i=t.map((e=>e.track)),r=yield Kw(e.send(i,n.store.codec,n.store.audioCodec)),o=(yield Kw(r.next())).value,s=n.createGatewayPublishMessage(t,o);let a;try{a=yield s}catch(e){throw r.throw(e),(null==e?void 0:e.code)===wN.WS_ABORT&&t.forEach((e=>{let t=e.track;-1===n.pendingLocalTracks.indexOf(t)&&n.pendingLocalTracks.push(t)})),n.unbindLocalTrackEvents(t),e}const c=n.mapPubResToRemoteConfig(s,a,i),d=(yield Kw(r.next(c))).value;if(n.state===jF.Disconnected)throw new ON(wN.UNEXPECTED_ERROR,"PeerConnection already disconnected.");xP("ENABLE_VIDEO_SEI");const l=xP("ENABLE_ENCODED_TRANSFORM"),u=xP("ENABLE_AUDIO_METADATA");i.forEach((async e=>{const t=e.getRTCRtpTransceiver();if(!t||!l)return;const n=See(),i=n.interceptLocalVideoFrame,r=n.interceptLocalAudioFrame;e.trackMediaType===UF.VIDEO?await i(t.sender,e):e.trackMediaType===UF.AUDIO&&await r(t.sender,{metadata:u?()=>{const t=e.metadata.shift();return t&&t.value}:void 0})})),t.forEach((e=>{let t=e.type;n.statsCollector.addLocalStats(t)})),n.assignLocalTracks(t,d),n.statsUploader.startUploadOutboundStats(),t.forEach((e=>{let t=e.track,i=e.type;const r=Date.now();n.store.publish(t.getTrackId(),i===BF.LocalAudioTrack?"audio":"video",void 0,r)}))}))()}async updateVideoStreamParameter(e,t){const n=this.localTrackMap.get(t);if(!n||!this.connection)return;if(!(n.track instanceof TV))return SL.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const i=n.track,r=function(e,t){const n={};return e.height&&e.width&&(n.scaleResolutionDownBy=b7(e,t)),n.maxFramerate=e.framerate?T7(e.framerate):void 0,n.maxBitrate=e.bitrate?1e3*e.bitrate:void 0,n}(e,i);if(i._encoderConfig||(i._encoderConfig={}),t!==BF.LocalVideoLowTrack||!xP("DISABLE_DUAL_STREAM_USE_ENCODING")&&JL().supportDualStreamEncoding)null!=r.scaleResolutionDownBy&&(i._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const t=i._originMediaStreamTrack;if(!t.canvas)return SL.warn("[".concat(i.getTrackId(),"] no canvas on track"));!function(e,t){const n=e.canvas;t.width&&(n.width=T7(t.width)),t.height&&(n.height=T7(t.height)),t.framerate&&(n.stopCapture&&n.stopCapture(),n.stopCapture=rM((()=>{!n.startCapture&&n.stopCapture&&n.stopCapture(),n.startCapture&&n.startCapture()}),T7(t.framerate)))}(t,e)}null!=r.maxBitrate&&(i._encoderConfig.bitrateMax=r.maxBitrate/1e3),null!=r.maxFramerate&&(i._encoderConfig.frameRate&&"object"==typeof i._encoderConfig.frameRate?i._encoderConfig.frameRate.max=r.maxFramerate:i._encoderConfig.frameRate={max:r.maxFramerate}),SL.debug("[".concat(i.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(i._encoderConfig))),await this.connection.updateRtpSenderEncodings(i)}publishLowStream(e){var t=this;return Ww((function*(){if(!t.connection||t.state!==jF.Connected)return;const n=yield Kw(t.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=t.localTrackMap.get(BF.LocalVideoTrack);if(!r)throw new ON(wN.UNEXPECTED_ERROR,"Could not find high stream");if(t.localTrackMap.has(BF.LocalVideoLowTrack))throw new ON(wN.UNEXPECTED_ERROR,"[".concat(t.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:t.getLowVideoTrack(r.track,e),type:BF.LocalVideoLowTrack}];if(yield*Hw(aie(t.doPublish(t.connection,o))),r.track.muted||!r.track.enabled){var i;const e=null===(i=t.localTrackMap.get(BF.LocalVideoLowTrack))||void 0===i?void 0:i.id;void 0!==e&&(yield Kw(t.connection.muteLocal([e])))}}finally{n()}}))()}async republish(){this.pendingLocalTracks.length>0&&(SL.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await dD(this,GF.RequestRePublish,this.pendingLocalTracks),this.emit(GF.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(SL.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),await dD(this,GF.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1}async reSubscribe(e){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const t=this.pendingRemoteTracks[e],n=t.user,i=t.kind;(i!==UF.AUDIO||n._audio_added_&&n._audioSSRC)&&(i!==UF.VIDEO||n._video_added_&&n._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(e)await dD(this,GF.RequestReSubscribe,this.pendingRemoteTracks);else for(const e of this.pendingRemoteTracks){const t=e.user,n=e.kind;await this.subscribe(t,n,n===UF.VIDEO?t._videoSSRC:t._audioSSRC)}this.pendingRemoteTracks.forEach((e=>{let t=e.user;this.emit(GF.MediaReconnectEnd,t.uid)})),this.pendingRemoteTracks=[]}async unpublish(e){if(!this.connection||this.state!==jF.Connected)return void e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const n=t.find((e=>"videoLowTrack"===e[0]));if(n){n[1].track.close()}return this.doUnpublish(this.connection,t)}async unpublishDataChannel(e){if(!this.connection||this.state!==jF.Connected)return void e.forEach((e=>{const t=this.pendingLocalDataChannels.indexOf(e);-1!==t&&this.pendingLocalDataChannels.splice(t,1)}));const t=this.filterTobeUnpublishedDataChannels(e);return 0!==t.length?(t.forEach((e=>{const t=this.localDataChannels.indexOf(e);-1!==t&&this.localDataChannels.splice(t,1)})),0===this.localDataChannels.length&&await this.connection.stopDataChannels(this.store.uid),t.map((e=>e.id))):void 0}async unpublishLowStream(){if(!this.connection||this.state!==jF.Connected)return;const e=this.localTrackMap.get(BF.LocalVideoLowTrack);if(!e)return;e.track.close();const t=[[BF.LocalVideoLowTrack,e]];return this.doUnpublish(this.connection,t)}async doUnpublish(e,t){const n=this.createGatewayUnpublishMessage(t);return await e.stopSending(t.map((e=>KC(e,2)[1].id))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let t=KC(e,2);return{type:t[0],track:t[1].track}}))),t.forEach((e=>{let t=KC(e,1)[0];this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&this.statsUploader.stopUploadOutboundStats(),n}async subscribeDataChannel(e,t){if(!this.connection||this.state!==jF.Connected)throw new ON(wN.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const n=t.filter((t=>{var n;return!(null!==(n=this.remoteDataChannelMap.get(e))&&void 0!==n&&n.get(t.id))}));if(0!==n.length)return await this.connection.createDataChannels(e.uid,n),n.forEach((t=>{var n;this.remoteDataChannelMap.has(e)?null===(n=this.remoteDataChannelMap.get(e))||void 0===n||n.set(t.id,t):this.remoteDataChannelMap.set(e,new Map([[t.id,t]]));const i=this.pendingRemoteDataChannels.findIndex((n=>{let i=n.user,r=n.id;return i.uid===e.uid&&r===t.id}));-1!==i&&this.pendingRemoteDataChannels.splice(i,1)})),n.map((e=>e.id))}async subscribe(e,t,n,i,r){var o;if(!this.connection||this.state!==jF.Connected)throw new ON(wN.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if(null!==(o=this.remoteUserMap.get(e))&&void 0!==o&&o.has(t))return;let s,a,c,d,l;const u=this.connection.getPreMedia(n);if(u)SL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(n,", no need to send sub to gateway.")),c=u.transceiver,s=u.track,a=u.mid,d=u.player,l=u.audioTrackId,u.firstVideoRender&&this.store.firstVideoFrameDecoded(e.uid,{firstPreRender:u.firstVideoRender});else if(r){const n=r.find((e=>e.stream_type===t));if(!n)throw new ON(wN.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(t," for user: ").concat(e.uid," because subscribe answer from gateway does not contain stream_type: ").concat(t,"."));const i=await this.connection.receive(t,n.ssrcs,String(e._uintid),n.attributes);(this.connection instanceof Pne||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=i.transceiver),s=i.track,a=i.id}else{const r=await this.connection.receive(t,[{ssrcId:n,rtx:i}],String(e._uintid),void 0);(this.connection instanceof Pne||"name"in this.connection&&"DataChannelConnection"===this.connection.name)&&(c=r.transceiver),s=r.track,a=r.id}if(t===UF.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new FV(s,e.uid,e._uintid,this.store),SL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),l&&(e._audioTrack._reusePreAudioElement(l,!0),u&&(u.audioTrackId=void 0)),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new xV(s,e.uid,e._uintid,this.store,d),SL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId())),e._videoTrack.once(Ak.PLAY_START,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playStart:Date.now()})})),e._videoTrack.once(Ak.PLAY_END,(()=>{this.store.firstVideoFrameDecoded(e.uid,{playEnd:Date.now()}),this.reportVideoFirstFrameRender(e)})),d?e._videoTrack.once(Ak.FIRST_FRAME_RENDER,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)})):e._videoTrack.once(Ak.FIRST_FRAME_DECODED,(()=>{this.store.firstVideoFrameDecoded(e.uid,{firstRender:Date.now()}),this.reportVideoFirstFrameRender(e)}))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack)),c&&xP("ENABLE_ENCODED_TRANSFORM")){const n=See(),i=n.interceptRemoteVideoFrame,r=n.interceptRemoteAudioFrame;t==UF.VIDEO?await i(c.receiver,{onSei:xP("ENABLE_VIDEO_SEI")&&((t,n)=>{var i;return null===(i=e._videoTrack)||void 0===i?void 0:i._onSei(t,n)}),onFirstFrame:e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):t==UF.AUDIO&&await r(c.receiver,{enableTopn:!!xP("ENABLE_AUDIO_TOPN"),enableMetadata:!!xP("ENABLE_AUDIO_METADATA"),enablePts:!!xP("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(GF.AudioMetadata,e)},onPts:e=>{this.safeEmit(GF.AudioPts,e)}})}const h=this.remoteUserMap.get(e);h?h.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const p=this.pendingRemoteTracks.findIndex((n=>{let i=n.user,r=n.kind;return i.uid===e.uid&&t===r}));-1!==p&&(this.pendingRemoteTracks.splice(p,1),this.emit(GF.MediaReconnectEnd,e.uid))}async massSubscribe(e){return this.massSubscribeNoLock(e)}async massSubscribeNoLock(e){if(!this.connection||this.state!==jF.Connected)throw new ON(wN.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");e=e.filter((e=>{var t;let n=e.user,i=e.mediaType;return!(null!==(t=this.remoteUserMap.get(n))&&void 0!==t&&t.has(i))}));const t=[],n=new Map;e.forEach((e=>{if(!this.connection)return;const i=this.connection.getPreMedia(e.ssrcId);if(i){const t=i.track,r=i.mid,o=i.transceiver,s=i.player,a=i.audioTrackId;n.set(e.ssrcId,{track:t,id:r,transceiver:o,player:s,audioTrackId:a})}else t.push(e)}));const i=await this.connection.batchReceive(t.map((e=>{let t=e.user;return{kind:e.mediaType,ssrcMsg:[{ssrcId:e.ssrcId,rtx:e.rtxSsrcId}],mslabel:String(t._uintid)}})));t.forEach(((e,t)=>{n.set(e.ssrcId,i[t])}));for(const t of e){const e=t.user,i=t.mediaType,r=t.ssrcId,o=n.get(r);if(!o)return void SL.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(e.uid," subscribe data,").concat(i,", ").concat(r));const s=o.track,a=o.id,c=o.transceiver,d=o.player,l=o.audioTrackId;if(c&&xP("ENABLE_ENCODED_TRANSFORM")){const t=See(),n=t.interceptRemoteVideoFrame,r=t.interceptRemoteAudioFrame;i==UF.VIDEO?await n(c.receiver,{onSei:xP("ENABLE_VIDEO_SEI")&&((t,n)=>{var i;return null===(i=e._videoTrack)||void 0===i?void 0:i._onSei(t,n)}),onFirstFrame:e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):i==UF.AUDIO&&await r(c.receiver,{enableTopn:!!xP("ENABLE_AUDIO_TOPN"),enableMetadata:!!xP("ENABLE_AUDIO_METADATA"),enablePts:!!xP("ENABLE_AUDIO_PTS"),onMetadata:e=>{this.safeEmit(GF.AudioMetadata,e)},onPts:e=>{this.safeEmit(GF.AudioPts,e)}})}if(i===UF.AUDIO){if(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new FV(s,e.uid,e._uintid,this.store),SL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),l){e._audioTrack._reusePreAudioElement(l,!0);const t=this.connection.getPreMedia(r);t&&(t.audioTrackId=void 0)}c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)}else e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new xV(s,e.uid,e._uintid,this.store,d),SL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack);if(xP("ENABLE_VIDEO_SEI")&&c){const t=See(),n=t.interceptRemoteVideoFrame,r=t.interceptRemoteAudioFrame;i==UF.VIDEO?await n(c.receiver,{onSei:(t,n)=>{var i;null===(i=e._videoTrack)||void 0===i||i._onSei(t,n)},onFirstFrame:e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e.ssrc));n&&this.store.firstVideoFrameDecoded(n.uid,{firstReceivedEncodedFrame:Date.now(),frameType:e.type,rtpTimestamp:e.rtpTimestamp,framePayloadType:e.payloadType,frameDataLength:e.length,mimeType:e.mimeType})}}):i==UF.AUDIO&&await r(c.receiver)}const u=this.remoteUserMap.get(e);u?u.set(i,a):this.remoteUserMap.set(e,new Map([[i,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats();const h=this.pendingRemoteTracks.findIndex((t=>{let n=t.user,r=t.kind;return n.uid===e.uid&&i===r}));-1!==h&&(this.pendingRemoteTracks.splice(h,1),this.emit(GF.MediaReconnectEnd,e.uid))}}async unsubscribe(e,t,n){const i=this.pendingRemoteTracks.filter((n=>{let i=n.user,r=n.kind;return void 0!==t?i.uid===e.uid&&t===r:i.uid===e.uid}));if(i.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.connection&&this.state===jF.Connected||n||i.forEach((t=>{let n=t.kind;var i;if(n===UF.AUDIO)null===(i=e._audioTrack)||void 0===i||i._destroy(),e._audioTrack=void 0;else if(n===UF.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.connection||this.state!==jF.Connected)return;const r=this.filterTobeUnSubscribedTracks(e,t);if(0===r.length)return;await this.connection.stopReceiving(r.map((e=>KC(e,2)[1].id)));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),r.forEach((e=>{let t=KC(e,2),i=t[0],r=t[1].kind;var o,s;r===UF.VIDEO&&i._videoSSRC&&(null===(o=this.connection)||void 0===o||o.setStatsRemoteVideoIsReady(i._videoSSRC,!1));if(r===UF.VIDEO)this.unbindRemoteTrackEvents(i._videoTrack),n||(null===(s=i._videoTrack)||void 0===s||s._destroy(),i._videoTrack=void 0);else if(r===UF.AUDIO){var a;if(this.unbindRemoteTrackEvents(i._audioTrack),!n)null===(a=i._audioTrack)||void 0===a||a._destroy(),i._audioTrack=void 0}})),o}async unsubscribeDataChannel(e,t){if(t.forEach((e=>{const t=this.pendingRemoteDataChannels.findIndex((t=>t.id===e.id));-1!==t&&this.pendingRemoteDataChannels.splice(t,1)})),!this.connection)return;const n=this.filterTobeUnSubscribedDataChannels(e,t);if(0===n.length)return;t.forEach((e=>{e._close()}));const i=this.remoteDataChannelMap.get(e);return n.forEach((e=>{i&&i.delete(e.id)})),i&&0===i.size&&(this.remoteDataChannelMap.delete(e),await this.connection.stopDataChannels(e.uid)),n.map((e=>e.id))}async massUnsubscribe(e){return this.massUnsubscribeNoLock(e)}async massUnsubscribeNoLock(e){let t=[];for(const n of e){const e=n.user,i=n.mediaType,r=this.pendingRemoteTracks.filter((t=>{let n=t.user,r=t.kind;return void 0!==i?n.uid===e.uid&&i===r:n.uid===e.uid}));r.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),t=t.concat(r)}if(!this.connection||this.state!==jF.Connected)return void t.forEach((e=>{let t=e.user,n=e.kind;var i;if(n===UF.AUDIO)null===(i=t._audioTrack)||void 0===i||i._destroy(),t._audioTrack=void 0;else if(n===UF.VIDEO){var r;null===(r=t._videoTrack)||void 0===r||r._destroy(),t._videoTrack=void 0}}));const n=sr(e).call(e,((e,t)=>{let n=t.user,i=t.mediaType;const r=this.filterTobeUnSubscribedTracks(n,i);return e.concat(r)}),[]);if(0===n.length)return;await this.connection.stopReceiving(n.map((e=>KC(e,2)[1].id)));const i=this.createUnsubscribeAllMessage(n);return this.withdrawRemoteTracks(n),0===this.remoteUserMap.size&&this.statsUploader.stopUploadInboundStats(),n.forEach((e=>{let t=KC(e,2),n=t[0],i=t[1].kind;var r,o;i===UF.VIDEO&&n._videoSSRC&&(null===(r=this.connection)||void 0===r||r.setStatsRemoteVideoIsReady(n._videoSSRC,!1));if(i===UF.VIDEO)this.unbindRemoteTrackEvents(n._videoTrack),null===(o=n._videoTrack)||void 0===o||o._destroy(),n._videoTrack=void 0;else if(i===UF.AUDIO){var s;this.unbindRemoteTrackEvents(n._audioTrack),null===(s=n._audioTrack)||void 0===s||s._destroy(),n._audioTrack=void 0}})),i}isPreSubScribe(e){if(!this.connection||this.state!==jF.Connected)return!1;return!!this.connection.getPreMedia(e)}async muteRemote(e,t){if(!this.connection)return;const n=this.remoteUserMap.get(e);if(!n)return void SL.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid,"."));if(!n.get(t))return void SL.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const i=t===UF.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==i&&this.connection.setStatsRemoteVideoIsReady(i,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.connection)return;const n=this.remoteUserMap.get(e);if(!n)return void SL.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid,"."));n.get(t)||SL.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}addAudioMetadata(e){const t=this.localTrackMap.get(BF.LocalAudioTrack),n=t&&t.track;n&&n.metadata.push(e)}getAllTracks(e){const t=this.localTrackMap.get(BF.LocalAudioTrack);if((null==t?void 0:t.track)instanceof OU){const n=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>KC(e,1)[0]!==BF.LocalAudioTrack)).filter((t=>{let n=KC(t,1)[0];return!(e&&n===BF.LocalVideoLowTrack)})).map((e=>KC(e,2)[1].track)).concat(n.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let n=KC(t,1)[0];return!(e&&n===BF.LocalVideoLowTrack)})).map((e=>KC(e,2)[1].track))}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(e,t,n,i,r){if(e){const n=this.localTrackMap.get(BF.LocalAudioTrack),o=i?this.localTrackMap.get(BF.LocalVideoLowTrack):this.localTrackMap.get(BF.LocalVideoTrack);HL.publish(this.store.sessionId,{eventElapse:Vte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==n?void 0:n.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(Rk.SCREEN_TRACK)),audio:!!n,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;n||(n=[]);const s=n.find((e=>e instanceof IU)),a=i?null===(o=this.localTrackMap.get(BF.LocalVideoTrack))||void 0===o?void 0:o.track:n.find((e=>e instanceof TV));HL.publish(this.store.sessionId,{eventElapse:Vte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(Rk.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,n,i){const r=i===UF.VIDEO?n._videoSSRC:n._audioSSRC;r&&HL.subscribe(this.store.sessionId,{succ:e,ec:t,video:i===UF.VIDEO,audio:i===UF.AUDIO,peerid:n.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:Vte.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){SL.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new JD("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&this.recreateConnection(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(BF.LocalAudioTrack);if((null==e?void 0:e.track)instanceof OU){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.iceFailedCount=0,this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.localDataChannels=[],this.remoteDataChannelMap.clear(),this.pendingLocalDataChannels=[],this.pendingRemoteDataChannels=[],this.state=jF.Disconnected}getStats(){var e;return null===(e=this.connection)||void 0===e?void 0:e.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.connection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(BF.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(BF.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof TV||t&&t.track instanceof IU?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}getRemoteMedia(e){var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return n?{audioTrack:n.audioTrack,audioSSRC:n._audioSSRC,videoTrack:n.videoTrack,videoSSRC:n._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let t=KC(e,1)[0];return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(BF.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=t_(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.connection&&(SL.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=jF.Reconnecting,xP("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=KC(e,1)[0];var n;t._videoTrack&&t._videoTrack._player&&(null===(n=t._videoTrack._player.getVideoElement())||void 0===n||n.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&this.recreateConnection(),0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let n=KC(e,2),i=n[0],r=n[1].track;switch(i){case BF.LocalVideoTrack:Ui(t=r._hints).call(t,Rk.LOW_STREAM)?r.close():this.pendingLocalTracks.push(r);break;case BF.LocalAudioTrack:r instanceof OU?this.pendingLocalTracks=this.pendingLocalTracks.concat(r.trackList):this.pendingLocalTracks.push(r);case BF.LocalVideoLowTrack:}})),this.emit(GF.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1];Array.from(oL(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(n,e)})),this.emit(GF.MediaReconnectStart,n.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),0!==this.localDataChannels.length&&(this.localDataChannels.forEach((e=>{this.pendingLocalDataChannels.push(e)})),this.localDataChannels.length=0),0!==this.remoteDataChannelMap.size&&(Array.from(this.remoteDataChannelMap.entries()).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1];Array.from(oL(i).call(i)).forEach((e=>{this.setPendingRemoteDataChannel(n,e)}))})),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),SL.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))}hasPendingRemoteDataChannel(e,t){for(const n of this.pendingRemoteDataChannels){const i=n.user,r=n.id;if((e instanceof Wte?e.uid:e)===i.uid&&r===t)return!0}return!1}setPendingRemoteDataChannel(e,t){this.hasPendingRemoteDataChannel(e,t)||this.pendingRemoteDataChannels.push({user:e,id:t})}hasPendingRemoteMedia(e,t){for(const n of this.pendingRemoteTracks){const i=n.user,r=n.kind;if((e instanceof Wte?e.uid:e)===i.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}restartICE(e){var t=this;return Ww((function*(){if(!t.connection||t.state!==jF.Connected)return;const n=yield Kw(t.mutex.lock("From P2PChannel.restartICE"));let i;try{i=yield Kw(t.connection.restartICE(e));const r=yield Kw(i.next());if(r.done)return;const o=r.value,s=yield o;switch(Ane(t.connection)&&t.reportPCStats(Date.now(),!1,t._pcStatsUploadType),e){case VF.UDP_TCP_RELAY:t._pcStatsUploadType=xF.UDP_TCP_RESTART;break;case VF.TCP_RELAY:t._pcStatsUploadType=xF.TCP_RESTART;break;case VF.RELAY:t._pcStatsUploadType=xF.RELAY_RESTART;break;default:t._pcStatsUploadType=xF.OLD_RESTART}t._isTryConnecting=!0,i.next(s)}catch(e){var r;yield Kw(null===(r=i)||void 0===r?void 0:r.throw(e))}finally{n()}}))()}getUplinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats(),t=this.localTrackMap.get(BF.LocalVideoTrack),n=this.localTrackMap.get(BF.LocalAudioTrack),i=e.videoSend.find((e=>e.ssrc===(null==t?void 0:t.ssrcs[0].ssrcId))),r=e.audioSend.find((e=>e.ssrc===(null==n?void 0:n.ssrcs[0].ssrcId)));if(!i||!r)return 1;const o=uD(this,GF.NeedSignalRTT),s=i?i.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(Rk.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,n=e.bitrate.actualEncoded;if(t&&n){const e=(1e3*t-n)/(1e3*t);return Ox[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const e=this.connection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((n=>{let i=KC(n,1)[0];const r=i._audioSSRC,o=i._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=uD(this,GF.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new cp(((t,n)=>{this.handleMuteLocalTrack(e,t,n)}))}async replaceTrack(e,t){var n;if(SL.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(e.getTrackId(),"] to [").concat(t.getTrackId(),"]")),!this.connection||this.state!==jF.Connected)return;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=KC(t,2)[1].track;return e===n}));if(!i)return;const r=i[0];if(e!==t&&(this.unbindLocalTrackEvents([{track:e,type:r}]),this.bindLocalTrackEvents([{track:t,type:r}]),i[1].track=t),await(null===(n=this.connection)||void 0===n?void 0:n.replaceTrack(t,i[1].id)),this.isPlanB){const e=i[1];e.id=t._mediaStreamTrack.id,this.localTrackMap.set(r,e)}if(r===BF.LocalVideoTrack&&!xP("DISABLE_DUAL_STREAM_USE_ENCODING")&&JL().supportDualStreamEncoding){const t=this.localTrackMap.get(BF.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new cp(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}}filterTobePublishedTracks(e,t,n){const i=[],r=this.getAllTracks();e=TD(e=e.filter((e=>-1===r.indexOf(e))));let o,s=!1;const a=this.localTrackMap.get(BF.LocalAudioTrack);for(const r of e){if(r instanceof TV&&(this.localTrackMap.has(BF.LocalVideoTrack)||s?new ON(wN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(i.push({track:r,type:BF.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(r,n);i.push({track:e,type:BF.LocalVideoLowTrack})}if(r instanceof IU)if(a){const e=a.track;if(e instanceof OU)yne([r]),e.addAudioTrack(r),this.bindLocalAudioTrackEvents(r,!0);else{const t=Cne([e,r]);SL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(t.getTrackId(),"]")),this.replaceTrack(e,t)}}else if(o instanceof OU)yne([r]),o.addAudioTrack(r);else if(o||!r._useAudioElement&&JL().webAudioMediaStreamDest&&!r._bypassWebAudio){o=Cne(o?[r,o]:[r])}else o=r}return o&&(SL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),i.push({track:o,type:BF.LocalAudioTrack})),i}filterTobeUnpublishedTracks(e){const t=[],n=this.getAllTracks();e=TD(e=e.filter((e=>-1!==n.indexOf(e))));for(const n of e){if(n instanceof IU){const e=this.localTrackMap.get(BF.LocalAudioTrack);if(!e)continue;e.track instanceof OU?(e.track.removeAudioTrack(n),this.unbindLocalAudioTrackEvents(n),0===e.track.trackList.length&&(t.push([BF.LocalAudioTrack,e]),e.track.close())):t.push([BF.LocalAudioTrack,e])}if(n instanceof TV){const e=this.localTrackMap.get(BF.LocalVideoTrack);if(!e)continue;t.push([BF.LocalVideoTrack,e]);const n=this.localTrackMap.get(BF.LocalVideoLowTrack);n&&t.push([BF.LocalVideoLowTrack,n])}}return t}filterTobePublishedDataChannels(e){return e=(e=TD(e)).filter((e=>-1===this.localDataChannels.findIndex((t=>t.id===e.id))))}filterTobeUnpublishedDataChannels(e){return e=(e=(e=TD(e)).filter((e=>-1!==this.localDataChannels.indexOf(e)))).filter((e=>e._originDataChannel))}bindLocalTrackEvents(e){e.forEach((e=>{let t=e.track;switch(e.type){case BF.LocalVideoTrack:t.addListener(Tk.GET_STATS,this.handleGetLocalVideoStats),t.addListener(Tk.GET_RTC_STATS,this.handleGetRTCStats),t.addListener(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(Tk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(Tk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(Tk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case BF.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case BF.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof OU?e.trackList.forEach((e=>{e.addListener(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Tk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(Tk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||(e.addListener(Tk.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.addListener(Tk.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let t=KC(e,2),n=t[0];return{track:t[1].track,type:n}}))),e.forEach((e=>{let t=e.track;switch(e.type){case BF.LocalVideoTrack:t.off(Tk.GET_STATS,this.handleGetLocalVideoStats),t.off(Tk.GET_RTC_STATS,this.handleGetRTCStats),t.off(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(Tk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(Tk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(Tk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case BF.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case BF.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof OU?e.trackList.forEach((e=>{e.off(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Tk.GET_STATS,this.handleGetLocalAudioStats),e.off(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(Tk.GET_STATS,this.handleGetLocalAudioStats),e.off(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Tk.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(Tk.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),e.off(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof xV&&t.addListener(Tk.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof FV&&t.addListener(Tk.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(Tk.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1];i.has(UF.AUDIO)&&this.unbindRemoteTrackEvents(n._audioTrack),i.has(UF.VIDEO)&&this.unbindRemoteTrackEvents(n._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,n)=>{var i;let r,o,s=e.track;switch(e.type){case BF.LocalAudioTrack:r=CF.Audio,o={dtx:s instanceof AU&&s._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case BF.LocalVideoTrack:r=Ui(i=s._hints).call(i,Rk.SCREEN_TRACK)?CF.Screen:CF.High,o=sie(sie({},R7(s)),{},{codec:this.store.codec,svc_mode:O7()});break;case BF.LocalVideoLowTrack:r=CF.Low,o=sie(sie({},R7(s)),{},{codec:this.store.codec,svc_mode:O7()})}return{stream_type:r,attributes:o,ssrcs:t[n]}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let n,i=KC(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case BF.LocalVideoTrack:n=Ui(t=s._hints).call(t,Rk.SCREEN_TRACK)?CF.Screen:CF.High;break;case BF.LocalAudioTrack:n=CF.Audio;break;case BF.LocalVideoLowTrack:n=CF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}assignLocalTracks(e,t){e.forEach(((e,n)=>{let i=e.track,r=e.type;this.localTrackMap.set(r,{track:i,id:t[n].id,ssrcs:t[n].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let t=KC(e,1)[0];this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{if(SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(t,")")),this.emit(GF.PeerConnectionStateChange,t),"connecting"===t&&e instanceof Pne&&!$O()&&xP("FIRST_TCP_CANDIDATE")&&window.setTimeout((()=>{"connecting"===t&&e.extendCandidate()}),xP("FIRST_TCP_CANDIDATE_INTERVAL")),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t){this._restartTimer&&(window.clearTimeout(this._restartTimer),this._restartTimer=void 0),e instanceof Pne&&nie(e,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=xF.DISCONNECTED_OR_FAILED;if("CONNECTED"===uD(this,GF.QueryClientConnectionState)&&this._isWaitPcToRePub){const e=this.pendingLocalTracks.map((e=>e.getTrackId())),t=this.pendingLocalDataChannels.map((e=>"dc_".concat(e.id)));HL.reportApiInvoke(this.store.sessionId,{name:zN.REPUB_AFTER_PC_CONNECTED,options:e.concat(t),tag:ZN.TRACER}).onSuccess(),this.republish()}}if(xP("NEW_ICE_RESTART")&&e instanceof Pne&&!$O()&&!this._forceTurn&&!this.store.useDcSignal){if(Ui(FF).call(FF,t)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const t=t=>{if(Ane(e)){SL.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(t));"CONNECTED"===uD(this,GF.QueryClientConnectionState)&&this.emit(GF.RequestRestartICE,t)}},n=()=>{Ane(e)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),SL.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout((()=>this.emit(GF.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout((()=>{iie(e,t,n)}),800))}}else{if("disconnected"===t&&"disconnected"===e.iceConnectionState)return setTimeout((()=>{if("disconnected"===e.iceConnectionState&&xP("ICE_RESTART")){"CONNECTED"===uD(this,GF.QueryClientConnectionState)&&this.emit(GF.RequestRestartICE)}}),800),void setTimeout((()=>{"disconnected"===e.peerConnectionState&&(SL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection disconnected timeout 4000ms, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),this._isTryConnecting=!1,setTimeout((()=>this.emit(GF.P2PLost)),0),this.iceFailedCount+=1,this.requestReconnect())}),4e3);"failed"===t&&(SL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection state failed, force reconnect")),this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),setTimeout((()=>this.emit(GF.P2PLost)),0),this.iceFailedCount+=1,await this.requestReconnect())}},e.onICEConnectionStateChange=t=>{"connected"!==t||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(t,")")),HL.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:t,tag:ZN.TRACER}).onSuccess(),this.emit(GF.IceConnectionStateChange,{state:t,remoteUfrag:this.connection===e&&e instanceof Pne?e.remoteIceUfrag:void 0})},e.onICETransportStateChange=e=>{SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onAudioMetadata=e=>{this.safeEmit(GF.AudioMetadata,e)},e.onAudioPts=e=>{this.safeEmit(GF.AudioPts,e)},e.onFirstAudioDecoded=e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var i;n&&(this.store.subscribe(n.uid,"audio",void 0,void 0,void 0,Date.now()),null===(i=n.audioTrack)||void 0===i||i.emit(Ak.FIRST_FRAME_DECODED),HL.firstRemoteFrame(this.store.sessionId,bL.FIRST_AUDIO_DECODE,IL.FIRST_AUDIO_DECODE,{peer:n._uintid,subscribeElapse:Vte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));n&&HL.firstRemoteFrame(this.store.sessionId,bL.FIRST_AUDIO_RECEIVED,IL.FIRST_AUDIO_RECEIVED,{peer:n._uintid,subscribeElapse:Vte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,n)=>{var i;const r=Array.from(oL(i=this.remoteUserMap).call(i)).find((t=>t._videoSSRC===e));r&&this.store.firstVideoFrameDecoded(r.uid,{firstDecoded:Date.now()}),this.reportVideoFirstFrameDecoded(e,t,n)},e.onFirstVideoRender=e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&(this.store.firstVideoFrameDecoded(n.uid,{firstPreRender:Date.now()}),this.reportVideoFirstFrameRender(n),this.emit(GF.FirstVideoPreRender,n.uid,e))},e.onFirstVideoReceived=e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&(this.store.firstVideoFrameDecoded(n.uid,{firstReceived:Date.now()}),HL.firstRemoteFrame(this.store.sessionId,bL.FIRST_VIDEO_RECEIVED,IL.FIRST_VIDEO_RECEIVED,{peer:n._uintid,subscribeElapse:Vte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstVideoBufferReady=e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&this.emit(GF.FirstVideoBufferReady,n.uid,e)},e.onSelectedLocalCandidateChanged=(e,t)=>{const n="relay"===e.candidateType,i="relay"===t.candidateType;"unknown"!==t.candidateType&&n===i||this.emit(GF.ConnectionTypeChange,n),SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(I7(t))," -> ").concat(JSON.stringify(I7(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(I7(t))," -> ").concat(JSON.stringify(I7(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),t=this.statsCollector.getRTCStats();return sie(sie({},e),t)},e.onICECandidateError=e=>{this._iceError=e}}fallbackConnection(){SL.debug("[".concat(this.store.clientId,"] [P2PChannel] try to fallback connection")),this.state===jF.Connected?(SL.debug("[".concat(this.store.clientId,"] [P2PChannel] fallback to websocket but P2PChannel state still connected, disconnect first")),this.disconnectForReconnect()):(this.connection&&this.resetConnection(this.connection),this.shouldForwardP2PCreation&&this.recreateConnection())}resetConnection(e){e instanceof Pne&&function(e){$ne.delete(e.id),nie(e)}(e),e.close(),this.emit(GF.PeerConnectionStateChange,"closed"),function(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.getLocalVideoStats=void 0}(e),this._isWaitPcToRePub=!1}recreateConnection(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._p2pBySDPEndPoint=!1,this.connection=Ine(this.store,e),this.emit(GF.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const n=this.localTrackMap.get(BF.LocalAudioTrack);if(e instanceof IU&&(null==n?void 0:n.track)instanceof OU)return n.track.isActive||t.push([BF.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=KC(t,2)[1].track;return e===n}));if(i&&(t.push(i),i[0]===BF.LocalVideoTrack)){const e=this.localTrackMap.get(BF.LocalVideoLowTrack);e&&t.push([BF.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],n=this.localTrackMap.get(BF.LocalAudioTrack);if(e instanceof IU&&(null==n?void 0:n.track)instanceof OU)return n.track.isActive&&t.push([BF.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=KC(t,2)[1].track;return e===n}));if(i)if(i[0]===BF.LocalVideoTrack){t.push(i);const e=this.localTrackMap.get(BF.LocalVideoLowTrack);e&&t.push([BF.LocalVideoLowTrack,e])}else t.push(i);return t}createMuteMessage(e){return e.map((e=>{var t;let n,i=KC(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case BF.LocalAudioTrack:n=CF.Audio;break;case BF.LocalVideoTrack:n=Ui(t=s._hints).call(t,Rk.SCREEN_TRACK)?CF.Screen:CF.High;break;case BF.LocalVideoLowTrack:n=CF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}createUnmuteMessage(e){return e.map((e=>{var t;let n,i=KC(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case BF.LocalAudioTrack:n=CF.Audio;break;case BF.LocalVideoTrack:n=Ui(t=s._hints).call(t,Rk.SCREEN_TRACK)?CF.Screen:CF.High;break;case BF.LocalVideoLowTrack:n=CF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}filterTobeUnSubscribedTracks(e,t){const n=[],i=this.remoteUserMap.get(e);if(!i)return n;if(t){const r=i.get(t);if(!r)return n;n.push([e,{kind:t,id:r}])}else Array.from(i.entries()).forEach((t=>{let i=KC(t,2),r=i[0],o=i[1];n.push([e,{kind:r,id:o}])}));return n}filterTobeUnSubscribedDataChannels(e,t){const n=[];return t.forEach((t=>{var i;null!==(i=this.remoteDataChannelMap.get(e))&&void 0!==i&&i.has(t.id)&&n.push(t)})),n}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let n=KC(e,2),i=n[0],r=n[1],o=r.kind;switch(r.id,o){case UF.VIDEO:return void(i._videoSSRC&&t.push({stream_type:UF.VIDEO,ssrcId:i._videoSSRC}));case UF.AUDIO:return void(i._audioSSRC&&t.push({stream_type:UF.AUDIO,ssrcId:i._audioSSRC}))}})),t}createUnsubscribeAllMessage(e){const t=new Map;return e.forEach((e=>{let n=KC(e,2),i=n[0],r=n[1].kind;if(t.has(i)){let e=t.get(i);r===UF.VIDEO?e|=AF.Video:e|=AF.Audio,t.set(i,e)}else r===UF.VIDEO?t.set(i,AF.Video):t.set(i,AF.Audio)})),{users:Array.from(t.entries()).map((e=>{let t=KC(e,2),n=t[0],i=t[1];return{stream_id:n.uid,stream_type:i}}))}}withdrawRemoteTracks(e){e.forEach((e=>{let t=KC(e,2),n=t[0],i=t[1].kind;const r=this.remoteUserMap.get(n);r&&(r.delete(i),0===Array.from(r.entries()).length&&this.remoteUserMap.delete(n))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(BF.LocalVideoTrack),n=this.localTrackMap.get(BF.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new cp(((e,n)=>{this.handleUpdateVideoEncoder(t.track,e,n,!0)}))),n&&e.low_stream_uplink&&(await n.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new cp(((e,t)=>{this.handleUpdateVideoEncoder(n.track,e,t,!0)})))}isP2PDisconnected(){if(this.connection){return"connected"!==this.connection.peerConnectionState}return!0}isPreallocation(){return!(!this.connection||!("name"in this.connection)||"DataChannelConnection"!==this.connection.name||"closed"===this.connection.peerConnectionState)||this.connection instanceof Pne&&this.connection.isPreallocation}isPreSub(){return(this.connection&&"name"in this.connection&&"DataChannelConnection"===this.connection.name&&"closed"!==this.connection.peerConnectionState||this.connection instanceof Pne)&&this.connection.isPreSub()}isPreRender(){return this.connection instanceof Pne&&this.connection.isPreRender}mapPubResToRemoteConfig(e,t,n){return e.map(((e,i)=>{var r;let o=e.stream_type;const s=null===(r=t.find((e=>{let t=e.stream_type;return o===t})))||void 0===r?void 0:r.attributes;if(s&&xP("DISABLE_SCREEN_SHARE_REMB")){const e=n[i]._hints;(Ui(e).call(e,Rk.SCREEN_TRACK)||Ui(e).call(e,Rk.SCREEN_LOW_TRACK))&&(s.remb=!1,SL.debug("disable remb for screen share, hints:",e))}return s}))}async tryToUnmuteAudio(e){for(let n=0;n<e.length;n++)if(e[n]instanceof IU){var t;const i=this.filterTobeUnmutedTracks(e[n]);if(0===i.length)continue;await(null===(t=this.connection)||void 0===t?void 0:t.unmuteLocal(i.map((e=>KC(e,2)[1].id))));const r=this.createUnmuteMessage(i);return void await lD(this,GF.RequestUnmuteLocal,r)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=()=>this.getStats(),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.connection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(GF.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(GF.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks(),this.statsUploader.requestTransportStats=()=>{var e;return{connectState:(null===(e=this.connection)||void 0===e?void 0:e.peerConnectionState)||"closed"}}}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await LD(qD(this.dtlsFailedCount,ZD)),this.emit(GF.RequestReconnect)}async reconnectP2P(){const e=Array.from(this.localTrackMap.entries()),t=this.createGatewayUnpublishMessage(e);Array.from(this.remoteUserMap.entries()),t.length>0&&await dD(this,GF.RequestUnpublishForReconnectPC,t),this.disconnectForReconnect(),this.emit(GF.RequestReconnectPC)}canPublishLowStream(){return this.localTrackMap.has(BF.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof TV))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof TV)).length>1)throw new ON(wN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof IU)).length>1&&(e.some((e=>e instanceof IU&&e._bypassWebAudio))||!JL().webAudioMediaStreamDest))throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof TV&&this.pendingLocalTracks.some((e=>e instanceof TV)))throw new ON(wN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof IU&&this.pendingLocalTracks.some((e=>e instanceof IU))&&(!JL().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof IU&&e._bypassWebAudio))))throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){var n;const i=!xP("DISABLE_DUAL_STREAM_USE_ENCODING")&&JL().supportDualStreamEncoding,r=sie(sie({},{width:160,height:120,framerate:15,bitrate:50}),t);let o;o=i?e._mediaStreamTrack.clone():kne(e,r);const s=kD(8,"track-low-"),a=new TV(o,sie(sie({},i&&{scaleResolutionDownBy:b7(r,e)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,s);return a.on(bk.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,vk.LOW_STREAM)})),a._hints.push(Rk.LOW_STREAM),Ui(n=e._hints).call(n,Rk.SCREEN_TRACK)&&a._hints.push(Rk.SCREEN_LOW_TRACK),e.on("sei-to-send",(e=>{a.emit("sei-to-send",e)})),e.addListener(Tk.NEED_CLOSE,(()=>{a.close()})),a}async globalLock(){return this.mutex.lock("From P2PChannel.globalLock")}async reportPCStats(e,t,n){let i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;if(this.connection&&this.connection instanceof Pne){var r,o,s,a;const c=this.store.keyMetrics.descriptionStart||0,d=this.connection,l=d.iceConnectionState,u=d.dtlsTransportState,h=d.peerConnectionState,p=await this.connection.getSelectedCandidatePair(),_=p.local,E=p.remote;HL.pcStats(this.store.sessionId,{startTime:c,eventElapse:e-c||0,iceconnectionsate:l,dtlsstate:u,connectionstate:h,intSucc:t?1:2,error:this._iceError||i||"",selectedLocalCandidateProtocol:null!==(r=null==_?void 0:_.protocol)&&void 0!==r?r:"",selectedLocalCandidateType:null!==(o=_.candidateType)&&void 0!==o?o:"",selectedLocalCandidateAddress:"".concat(_.address,":").concat(_.port),selectedRemoteCandidateProtocol:null!==(s=E.protocol)&&void 0!==s?s:"",selectedRemoteCandidateType:null!==(a=E.candidateType)&&void 0!==a?a:"",selectedRemoteCandidateAddress:"".concat(E.address,":").concat(E.port),restartCnt:n,preallocation:this.connection.isPreallocation,sdpEndPoint:this._p2pBySDPEndPoint?1:0}),this._iceError=null}}reportVideoFirstFrameRender(e){const t=this.store.keyMetrics,n=t.firstVideoFrameDecoded.find((t=>t.userId===e.uid));if(!n)return;const i=n.isInternalUpload,r=n.isExternalUpload;if(i&&r)return;const o=n.subscribeEnd,s=n.firstPreRender,a=n.peerPublishDuration,c=n.peerPubStatusMs;let d=n.firstRender,l=void 0===d?0:d;if(o&&(l||s)&&a&&c){n.isInternalUpload=!0;const i=n.playEnd;i&&(n.isExternalUpload=!0);const r=n.firstPreRender,s=void 0===r?0:r;l=s||l;const d=e.videoTrack,u={peer:e._uintid,width:(null==d?void 0:d._videoWidth)||0,height:(null==d?void 0:d._videoHeight)||0,ssrc:e._videoSSRC||0,p2pid:this.store.p2pId,peerPublishDuration:a,peerPubStatusMs:c,joinChannelStart:t.joinStart||0,preloadStart:t.preloadStart||0,preloadEnd:t.preloadEnd||0,apStart:t.requestAPStart||0,apEnd:t.requestAPEnd||0,suaEnd:t.requestSUAEnd||0,beforeConnect:t.beforeConnect||0,peerReceiver:t.peerReceiver||0,ice:t.iceConnectionEnd||0,pc:t.peerConnectionEnd||0,signalConnected:t.signalConnected||0,joinReq:t.joinReq||0,joinRes:t.joinRep||0,userJoinNotify:n.userJoinNotify||0,videoAddNotify:n.videoAddNotify||0,subscribeStart:n.subscribeStart||0,subscribeEnd:n.subscribeEnd||0,firstReceived:n.firstReceived||0,firstDecoded:n.firstDecoded||0,firstPreRender:s||0,firstRender:i?Math.max(l,i):Math.max(l,o),playStart:n.playStart||0,playEnd:n.playEnd||0,isPreSub:!(!e._videoSSRC||!this.isPreSubScribe(e._videoSSRC)),isPrePc:this.isPreallocation(),isPreInstantVideo:$L(this.store),firstReceivedEncodedFrame:n.firstReceivedEncodedFrame||0,frameType:n.frameType||"",rtpTimestamp:n.rtpTimestamp||0,framePayloadType:n.framePayloadType||0,frameDataLength:n.frameDataLength||0,mimeType:n.mimeType||"",sdpEndPoint:this._p2pBySDPEndPoint};HL.firstXLAPeerFirstVideoFrame(this.store.sessionId,u)}}reportVideoFirstFrameDecoded(e,t,n,i){var r;const o=Array.from(oL(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){i||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));HL.firstRemoteVideoDecode(this.store.sessionId,bL.FIRST_VIDEO_DECODE,IL.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:n,subscribeElapse:Vte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:i?1:0,firstFrame:(null==s?void 0:s.firstFrame)||0})}}async remoteMediaSsrcChanged(e,t,n){if(!this.connection)return!1;const i=this.remoteUserMap.get(e);if(!i)return!1;const r=i.get(t);if(!r)return!1;const o=await this.connection.getRemoteSSRC(r);return void 0!==o&&o!==n}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1].track;n===BF.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,vk.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},Zx(rie.prototype,"startP2PConnection",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"startP2PConnection"),rie.prototype),Zx(rie.prototype,"connect",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"connect"),rie.prototype),Zx(rie.prototype,"updateRemoteRTPCapabilities",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"updateRemoteRTPCapabilities"),rie.prototype),Zx(rie.prototype,"publishDataChannel",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"publishDataChannel"),rie.prototype),Zx(rie.prototype,"unpublish",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"unpublish"),rie.prototype),Zx(rie.prototype,"unpublishDataChannel",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"unpublishDataChannel"),rie.prototype),Zx(rie.prototype,"unpublishLowStream",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"unpublishLowStream"),rie.prototype),Zx(rie.prototype,"subscribeDataChannel",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"subscribeDataChannel"),rie.prototype),Zx(rie.prototype,"subscribe",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"subscribe"),rie.prototype),Zx(rie.prototype,"massSubscribe",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"massSubscribe"),rie.prototype),Zx(rie.prototype,"unsubscribe",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"unsubscribe"),rie.prototype),Zx(rie.prototype,"unsubscribeDataChannel",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"unsubscribeDataChannel"),rie.prototype),Zx(rie.prototype,"massUnsubscribe",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"massUnsubscribe"),rie.prototype),Zx(rie.prototype,"muteRemote",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"muteRemote"),rie.prototype),Zx(rie.prototype,"unmuteRemote",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"unmuteRemote"),rie.prototype),Zx(rie.prototype,"hasRemoteMediaWithLock",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"hasRemoteMediaWithLock"),rie.prototype),Zx(rie.prototype,"disconnectForReconnect",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"disconnectForReconnect"),rie.prototype),Zx(rie.prototype,"updateBitrateLimit",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"updateBitrateLimit"),rie.prototype),Zx(rie.prototype,"remoteMediaSsrcChanged",[lie],Object.getOwnPropertyDescriptor(rie.prototype,"remoteMediaSsrcChanged"),rie.prototype),rie);function lie(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From P2PChannel.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}function uie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function hie(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?uie(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):uie(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function pie(e){return null===e||"object"!=typeof e||Object.isFrozen(e)?e:(Object.values(e).forEach((e=>pie(e))),Object.freeze(e))}function _ie(e){return null==e?e:pie(JSON.parse(JSON.stringify(e)))}class Eie{constructor(e){var t,n,i;zA(this,"id",void 0),zA(this,"signalResponse",void 0),zA(this,"initialRole",void 0),zA(this,"channelReady",void 0),zA(this,"_edge",void 0),zA(this,"_preJoinResponse",void 0),zA(this,"_ready",!1),zA(this,"resolveChannelReady",void 0),this.id=e.id,this.signalResponse=_ie(e.signalResponse),this.initialRole=null!==(t=e.initialRole)&&void 0!==t?t:"audience",this._edge=e.edge,this._preJoinResponse=(n=this.signalResponse,i=this._edge,hie(hie({},n),{},{ortc:{dtlsParameters:{role:"client",fingerprints:[{algorithm:"sha-256",fingerprint:i.fingerprint}]},iceParameters:{candidates:[],iceUfrag:i.iceUfrag,icePwd:i.icePwd},rtpCapabilities:n.rtpCapabilities,cname:"o/i14u9pJrxRKAsu"}})),this.channelReady=new cp((e=>{this.resolveChannelReady=e}))}get preJoinResponse(){return this._preJoinResponse}get expectedRemoteUfrag(){return this._edge.iceUfrag}get ready(){return this._ready}matchesRemoteUfrag(e){return!!this._edge.iceUfrag&&e===this._edge.iceUfrag}acceptIceProof(e){if(this._ready||"connected"!==e.state||!this.matchesRemoteUfrag(e.remoteUfrag)||!this.resolveChannelReady)return!1;this._ready=!0;const t=this.resolveChannelReady;return this.resolveChannelReady=void 0,t({kind:"ice",proof:e}),!0}}function mie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function fie(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?mie(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mie(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const gie=Date.now(),Sie=20,Tie=new Map,Rie=new Map;async function vie(e){const t=Tie.get(e),n=Array.isArray(t)&&t[t.length-1],i=Rie.get(e);if(!n)return void(i.isSyncing=!1);const r={uid:n.uid,payload:n.payload};0===i.firstRecvTs&&(i.firstRecvTs=n.recvTs,i.firstSendTs=n.sendTs);const o=n.sendTs-i.firstSendTs,s=o-(Date.now()-i.firstRecvTs);s>0&&(i.firstRecvTs=Date.now()-o);let a=n.mediaDelay+s;a<=0?(t.pop(),yie(n.context,r),a=0):a=Math.min(a,Sie),setTimeout((()=>t.length&&vie(e)),a)}function yie(e,t){e.safeEmit(rD.STREAM_MESSAGE,t.uid,t.payload),e.onStreamMessage&&e.onStreamMessage(t)}function Cie(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=arguments.length>2?arguments[2]:void 0;if(!e.syncWithAudio)return yie(n,{uid:e.uid,payload:e.payload});const i="".concat(n.id,"-").concat(e.uid),r=Tie.get(i)||[],o=r.findIndex((t=>e.sendTs>=t.sendTs)),s=fie(fie({},e),{},{context:n,mediaDelay:t,recvTs:Date.now()});-1===o?r.push(s):r.splice(o,0,s),Tie.set(i,r);let a=!1;var c;Rie.has(i)?a=!(null===(c=Rie.get(i))||void 0===c||!c.isSyncing):Rie.set(i,{isSyncing:a,firstRecvTs:0,firstSendTs:0});a||vie(i)}const bie=GO().name;function Iie(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Aie(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Iie(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Iie(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const wie="websdk_ng_cache_parameter",Oie=xP("MAX_PRELOAD_ASYNC_LENGTH"),Nie=1e4,Die=new Map,Pie=[];let Lie=null,kie=0,Mie=0;const Uie=new Map,Vie=new Uint8Array([241,141,127,212,103,139,200,225,251,157,127,139,143,2,22,163]),xie=function(e,t){const n=[];let i=0;const r=async()=>{const e=n.shift();e&&await e(),n.length>0&&i<t?r():i--};return async function(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return new cp((async(o,a)=>{n.push((async()=>{try{const t=await e(...s);o(t)}catch(e){a(e)}})),i<t&&(i++,r())}))}}(jie,Oie),Fie=DO.CancelToken.source();class Bie{constructor(){zA(this,"_audioContext",null)}createMuteAudioTrack(){this._audioContext=new AudioContext;const e=this._audioContext.sampleRate,t=10*e,n=this._audioContext.createBuffer(2,t,e),i=this._audioContext.createBufferSource();i.buffer=n;const r=this._audioContext.createMediaStreamDestination();i.connect(r),i.start();return r.stream.getAudioTracks()[0]}close(){this._audioContext&&(this._audioContext.close(),this._audioContext=null)}}async function jie(e,t,n,i,r,o,s){try{if(!xP("ENABLE_PRELOAD"))return;if(!JL().supportWebCrypto)return void bD((()=>{SL.warn("Your browser does not support preloading, this feature  be run in a secure environment")}),"preload_webcrypto_not_supported");if(!n&&null!==n)throw new ON(wN.INVALID_PARAMS,"Invalid token: ".concat(n,". If you don not use token, set it to null"));n&&kN(n,"token",1,2047),kN(e,"appid",1,2047),dF(t),i&&lF(i);const c=MD();SL.debug("preload channel ".concat(t,", uid is ").concat(i));const d={appId:e,cname:t,token:n||e,uid:"string"!=typeof i?i:null,sid:c,proxyServer:r,role:s};let l,u;if("string"==typeof i){d.stringUid=i;var a=KC(await cp.all([ute(i,{sid:c,appId:e},Fie.token),Ete(Aie(Aie({},d),{},{token:n||e,uid:0}),Fie.token)]),2);u=a[0],l=a[1],d.uid=u.uid,l.gatewayInfo.uid=d.uid,l.gatewayInfo.res.uid=d.uid}else o&&(d.stringUid=o),l=await Ete(d,Fie.token);const h={sid:c,appId:e,cname:t,token:n||e,uid:d.stringUid||i,intUid:d.uid||l.gatewayInfo.uid,stringUid:d.stringUid,ts:Date.now(),sua:u,ap:l};await Kie(h),kie++}catch(e){throw Mie++,function(e){Lie||(Lie=window.setTimeout((()=>{let t="";Uie.forEach(((e,n)=>{t+="".concat(n,": ").concat(e," ;")})),HL.reportApiInvoke(null,{name:zN.PRELOAD,options:{success:kie,failed:Mie,err:t}}).onError(e),kie=0,Mie=0,Uie.clear(),Lie=null}),Nie));const t=Uie.get(e.code)||0;Uie.set(e.code,t+1)}(e),e}}async function Gie(e){try{if(xP("AP_REQUEST_DETAIL")||xP("AP_REQUEST_DETAIL_EXTEND")||xP("ENABLE_ROLE_SELECT_EDGE")||xP("ENABLE_JOIN_V4"))return;const t=Wie(e);if(!t||"disabled"!==e.cloudProxyServer)return;const n=await async function(e,t){try{const n=await window.crypto.subtle.importKey("raw",wD(t),"AES-GCM",!1,["decrypt"]),i=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:Vie},n,ID(e));return JSON.parse(window.atob(AD(new Uint8Array(i))))}catch(e){return}}(t,e.token||e.appId);if(!n)return;if(!function(e,t){const n=e.cname===t.cname&&e.appId===t.appId&&e.token===t.token;if(!n)return!1;return t.stringUid?e.stringUid===t.stringUid:"number"==typeof t.uid?e.uid===t.uid:e.uid==t.uid}(n,e))return;if(n&&Date.now()-n.ts<xP("AP_CACHE_LIFETIME"))return n}catch(e){SL.warn("Error get preloadInfo",e.message)}}function Wie(e){let t;try{if(t=Jie(wie),!t)return;const n=JSON.parse(t),i=Zie(e),r=function(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}(n,(e=>i in e));if(-1===r)return;const o=n.splice(r,1)[0];return zie(wie,JSON.stringify(n)),o[i]}catch(e){SL.warn("Error delete preload info: ".concat(t),e.message),zie(wie,"")}}async function Kie(e){let t;try{e.uid&&Wie({appId:e.appId,cname:e.cname,token:e.token,uid:e.uid,stringUid:e.stringUid});const n=Zie(e),i=await async function(e,t){try{const n=await window.crypto.subtle.importKey("raw",wD(t),"AES-GCM",!1,["encrypt"]),i=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:Vie},n,ID(window.btoa(JSON.stringify(e))));return AD(new Uint8Array(i))}catch(e){return}}(e,e.token||e.appId);if(!i)return;t=Jie(wie);const r=t?JSON.parse(t):[];r.push({[n]:i}),r.length>xP("AP_CACHE_NUM")&&r.shift(),zie(wie,JSON.stringify(r))}catch(e){SL.warn("Error caching server parameters:",e.message),zie(wie,"")}}function Hie(e){if(e){let t=Die.get(e);t&&(window.clearTimeout(t),t=null,Die.delete(e)),Ui(Pie).call(Pie,e)||"disabled"!==e.cloudProxyServer||Pie.push(e)}if(Die.size<xP("AP_CACHE_NUM")&&Pie.length>0){const e=Pie.shift();Die.set(e,window.setTimeout((async()=>{const t=e.appId,n=e.cname,i=e.token,r=e.stringUid,o=e.uid,s=e.proxyServer,a=e.role;try{await xie(t,n,i,o,s,r,a),Die.has(e)&&Hie(e)}catch(t){SL.warn("update preload failed",t.message),Yie(e)}}),xP("AP_UPDATE_INTERVAL")))}}function Yie(e){const t=Pie.indexOf(e);-1!==t&&Pie.splice(t,1);let n=Die.get(e);n&&(window.clearTimeout(n),n=null,Die.delete(e),Hie())}function Xie(e,t){const n=e.sua,i=e.ap;t&&n&&HL.reqUserAccount(e.sid,{lts:n.requestTime,elapse:n.elapse,success:!0,serverAddr:n.url,stringUid:t,uid:e.intUid,errorCode:null,extend:n.req}),HL.reportResourceTiming(e.ap.url,e.sid),HL.joinWebProxyAP(e.sid,{lts:i.requestTime,elapse:i.elapse,sucess:1,apServerAddr:i.url,turnServerAddrList:i.proxyInfo.addresses.map((e=>e.ip)).join(","),eventType:"disabled",unilbsServerIds:[YW.CHOOSE_SERVER,YW.CLOUD_PROXY_FALLBACK].toString()}),HL.joinChooseServer(e.sid,{lts:i.requestTime,elapse:i.elapse,succ:!0,csAddr:i.url,opid:i.opid,serverList:i.gatewayInfo.gatewayAddrs.map((e=>e.address)),ec:null,cid:i.gatewayInfo.cid.toString(),uid:i.gatewayInfo.uid.toString(),csIp:i.gatewayInfo.csIp,unilbsServerIds:[YW.CHOOSE_SERVER].toString(),isHttp3:i.isHttp3})}function Jie(e){return window.atob(window.localStorage.getItem(e)||"")}function zie(e,t){window.localStorage.setItem(e,window.btoa(t))}function Zie(e){let t="".concat(e.appId,"_").concat(e.cname);return"string"==typeof e.uid&&(t+="_s_".concat(e.uid)),"number"==typeof e.uid&&(t+="_".concat(e.uid)),e.token&&(t+="_".concat(e.token)),HD(t)}function qie(e){let t=function(){const e=tre.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(e,t){let n=e.appId;void 0!==n&&(hre(t,10),cre(t,n));let i=e.cid;void 0!==i&&(hre(t,16),hre(t,i));let r=e.cname;void 0!==r&&(hre(t,26),cre(t,r));let o=e.deviceId;void 0!==o&&(hre(t,34),cre(t,o));let s=e.elapse;void 0!==s&&(hre(t,40),_re(t,s));let a=e.fileSize;void 0!==a&&(hre(t,48),_re(t,ere(a)));let c=e.height;void 0!==c&&(hre(t,56),_re(t,ere(c)));let d=e.jpg;void 0!==d&&(hre(t,66),hre(t,d.length),sre(t,d));let l=e.networkType;void 0!==l&&(hre(t,72),_re(t,ere(l)));let u=e.osType;void 0!==u&&(hre(t,80),_re(t,ere(u)));let h=e.requestId;void 0!==h&&(hre(t,90),cre(t,h));let p=e.sdkVersion;void 0!==p&&(hre(t,98),cre(t,p));let _=e.sequence;void 0!==_&&(hre(t,104),_re(t,ere(_)));let E=e.sid;void 0!==E&&(hre(t,114),cre(t,E));let m=e.timestamp;void 0!==m&&(hre(t,120),_re(t,m));let f=e.uid;void 0!==f&&(hre(t,128),hre(t,f));let g=e.vid;void 0!==g&&(hre(t,136),hre(t,g));let S=e.width;void 0!==S&&(hre(t,144),_re(t,ere(S)));let T=e.service;void 0!==T&&(hre(t,152),hre(t,T));let R=e.callbackData;void 0!==R&&(hre(t,162),hre(t,R.length),sre(t,R));let v=e.ticket;void 0!==v&&(hre(t,170),cre(t,v));let y=e.vendorConfigs;void 0!==y&&(hre(t,178),cre(t,y))}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function Qie(e){return function(e){let t={};e:for(;!ire(e);){let n=ure(e);switch(n>>>3){case 0:break e;case 1:t.code=ure(e);break;case 2:t.msg=are(e,ure(e));break;case 3:t.requestId=are(e,ure(e));break;case 4:t.timestamp=pre(e,!1);break;default:$ie(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function $ie(e,t){switch(t){case 0:for(;128&dre(e););break;case 2:nre(e,ure(e));break;case 5:nre(e,4);break;case 1:nre(e,8);break;default:throw new Error("Unimplemented type: "+t)}}function ere(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let tre=[];function nre(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function ire(e){return e.offset>=e.limit}function rre(e,t){let n=e.bytes,i=e.offset,r=e.limit,o=i+t;if(o>n.length){let t=new Uint8Array(2*o);t.set(n),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),i}function ore(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function sre(e,t){let n=rre(e,t.length);e.bytes.set(t,n)}function are(e,t){let n=ore(e,t),i=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+n];0==(128&u)?s+=i(u):192==(224&u)?e+1>=t?s+=o:(a=r[e+n+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=i(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=i(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],d=r[e+n+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=i(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function cre(e,t){let n=t.length,i=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<n&&(r=(r<<10)+t.charCodeAt(++e)-56613888),i+=r<128?1:r<2048?2:r<65536?3:4}hre(e,i);let r=rre(e,i),o=e.bytes;for(let e=0;e<n;e++){let i=t.charCodeAt(e);i>=55296&&i<=56319&&e+1<n&&(i=(i<<10)+t.charCodeAt(++e)-56613888),i<128?o[r++]=i:(i<2048?o[r++]=i>>6&31|192:(i<65536?o[r++]=i>>12&15|224:(o[r++]=i>>18&7|240,o[r++]=i>>12&63|128),o[r++]=i>>6&63|128),o[r++]=63&i|128)}}function dre(e){return e.bytes[ore(e,1)]}function lre(e,t){let n=rre(e,1);e.bytes[n]=t}function ure(e){let t,n=0,i=0;do{t=dre(e),n<32&&(i|=(127&t)<<n),n+=7}while(128&t);return i}function hre(e,t){for(t>>>=0;t>=128;)lre(e,127&t|128),t>>>=7;lre(e,t)}function pre(e,t){let n,i=0,r=0,o=0;return n=dre(e),i=127&n,128&n&&(n=dre(e),i|=(127&n)<<7,128&n&&(n=dre(e),i|=(127&n)<<14,128&n&&(n=dre(e),i|=(127&n)<<21,128&n&&(n=dre(e),r=127&n,128&n&&(n=dre(e),r|=(127&n)<<7,128&n&&(n=dre(e),r|=(127&n)<<14,128&n&&(n=dre(e),r|=(127&n)<<21,128&n&&(n=dre(e),o=127&n,128&n&&(n=dre(e),o|=(127&n)<<7))))))))),{low:i|r<<28,high:r>>>4|o<<24,unsigned:t}}function _re(e,t){let n=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===i?n<16384?n<128?1:2:n<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:r<128?9:10,s=rre(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?i>>>21|128:i>>>21&127;case 7:a[s+6]=7!==o?i>>>14|128:i>>>14&127;case 6:a[s+5]=6!==o?i>>>7|128:i>>>7&127;case 5:a[s+4]=5!==o?128|i:127&i;case 4:a[s+3]=4!==o?n>>>21|128:n>>>21&127;case 3:a[s+2]=3!==o?n>>>14|128:n>>>14&127;case 2:a[s+1]=2!==o?n>>>7|128:n>>>7&127;case 1:a[s]=1!==o?128|n:127&n}}const Ere={},mre={},fre=4294967296,gre=fre*fre,Sre=gre/2,Tre=bre(0,!0),Rre=bre(0),vre=Ire(0,-2147483648,!1),yre=Ire(-1,2147483647,!1),Cre=Ire(-1,-1,!0);function bre(e,t){let n,i,r;return t?(r=0<=(e>>>=0)&&e<256)&&(i=mre[e],i)?i:(n=Ire(e,0,!0),r&&(mre[e]=n),n):(r=-128<=(e|=0)&&e<128)&&(i=Ere[e],i)?i:(n=Ire(e,e<0?-1:0,!1),r&&(Ere[e]=n),n)}function Ire(e,t,n){return{low:0|e,high:0|t,unsigned:!!n}}function Are(e,t){if(isNaN(e))return t?Tre:Rre;if(t){if(e<0)return Tre;if(e>=gre)return Cre}else{if(e<=-Sre)return vre;if(e+1>=Sre)return yre}return e<0?t?Tre:Rre:Ire(e%fre|0,e/fre|0,t)}function wre(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class Ore extends YN{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(ZF.CONNECTION_STATE_CHANGE,e,t)}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this._qualityTimer&&(window.clearTimeout(this._qualityTimer),this._qualityTimer=null),this._quality>=1||(this._qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this._qualityRatio}),6e4))}constructor(e){var t;super(),zA(this,"name","AgoraRTCImageModeration"),zA(this,"_connectionState",zF.CONNECTING),zA(this,"_sequence",0),zA(this,"_moderationStartTime",void 0),zA(this,"_workerConnection",void 0),zA(this,"_workerMessageLengthLimit",void 0),zA(this,"_qualityRatio",void 0),zA(this,"_connectInfo",void 0),zA(this,"_cancelTokenSource",DO.CancelToken.source()),zA(this,"_retryConfig",void 0),zA(this,"_moderationInterval",void 0),zA(this,"_moderationTimer",null),zA(this,"_moderationMode",1),zA(this,"_quality",1),zA(this,"_qualityTimer",null),zA(this,"_ticket",void 0),zA(this,"_moderationIntervalMinimum",void 0),zA(this,"_uploadFailedNum",0),zA(this,"_uploadNum",0),zA(this,"_uploadTimer",null),zA(this,"_extraInfo",void 0),zA(this,"_vendor",""),zA(this,"_encoder",new TextEncoder),zA(this,"_moderationId",void 0),zA(this,"inspectImage",(()=>{if(this.connectionState!==zF.CONNECTED)throw new YL(wN.OPERATION_ABORTED,"image moderation service connection status is ".concat(this.connectionState));this._moderationTimer&&(window.clearInterval(this._moderationTimer),this._moderationTimer=null),this._moderationTimer=window.setInterval((()=>{this.connectionState===zF.CONNECTED?this.requestToInspectImage():SL.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)}),this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()})),this._moderationId=kD(5,"image-moderation-"),this._workerMessageLengthLimit=xP("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=xP("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=xP("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new gB("worker-"+this._moderationId,ZD),this.on(ZF.STATE_CHANGE,((e,t)=>{SL.debug("[".concat(this._moderationId,"] Moderation operation :").concat(qF[e]," ").concat(t||""))})),this.handleWorkerEvents()}async init(e,t){this.emit(ZF.STATE_CHANGE,qF.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new cp(((i,r)=>{this.on(ZF.CONNECTION_STATE_CHANGE,((e,t)=>{e===zF.CONNECTED&&i()})),this.requestAP(e,n,t).then((e=>{this.connectWorker(e)})).catch((e=>{r(e)}))}))}updateConfig(e){var t;this._moderationInterval=null!==(t=e.interval)&&void 0!==t?t:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),SL.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===zF.CONNECTED&&this.inspectImage()}async requestAP(e,t,n){const i=xP("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,n,i){let r=t.appId,o=t.areaCode,s=t.cname,a=t.sid,c=t.token,d=t.uid;ete++;const l="moderation_plugin",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:ete,seq:ete,sid:a,appToken:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return QD((async()=>{h=Date.now();const e=await Nee(_,{data:u,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new YL(wN.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+e.code,{retry:!0,responseTime:p});throw SL.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new YL(wN.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw SL.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new YL(wN.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:t.code,responseTime:p});throw SL.error(e.toString()),e}if(!t.servers.some((e=>!!e.wss))){const e=new YL(wN.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:t.code,responseTime:p});throw SL.error(e.toString()),e}const i=xP("IMAGE_MODERATION_WORKER_WSS");if(i)return{addressList:[i],workerToken:t.workerToken,vid:t.vid,responseTime:p};const r=xP("IMAGE_MODERATION_WORKER_HOST"),o=t.servers.map((e=>{let t=e.address,n=e.wss;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(r,":").concat(n,"/moderation")})).filter((e=>!!e));return{addressList:o,workerToken:t.workerToken,vid:t.vid,ticket:t.appTicket,responseTime:p}}),((t,n)=>(HL.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:p,serverIp:e[n%e.length]}),!1)),((t,n)=>(HL.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[n%e.length]}),!!(t.code!==wN.OPERATION_ABORTED&&t.code!==wN.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(n+1)%e.length],!0))),i)}(i,e,t,n);this.emit(ZF.STATE_CHANGE,qF.AP_CONNECTED);const o=r.addressList,s=r.ticket;return this._ticket=s,o}async connectWorker(e){this.emit(ZF.STATE_CHANGE,qF.CONNECT_WORKER),await this._workerConnection.init(e,1e4)}handleWorkerEvents(){this._workerConnection.on(cF.CONNECTED,(async()=>{this.emit(ZF.STATE_CHANGE,qF.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=zF.CONNECTED})),this._workerConnection.on(cF.CLOSED,(()=>{this.connectionState=zF.CLOSED})),this._workerConnection.on(cF.FAILED,(()=>{this.connectionState=zF.CLOSED})),this._workerConnection.on(cF.RECONNECTING,(()=>{this.connectionState=this.connectionState===zF.CONNECTED?zF.RECONNECTING:zF.CONNECTING})),this._workerConnection.on(cF.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const t=Qie(new Uint8Array(e.data));xP("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&SL.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(t)),this._uploadNum++,void 0===t.code||0===t.code||(this._uploadFailedNum++,SL.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(t.code,", msg is ").concat(t.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout((()=>{HL.reportApiInvoke(this._connectInfo.sid||null,{name:zN.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,t.code],tag:ZN.TRACER}).onError(new YL(wN.IMAGE_MODERATION_UPLOAD_FAILED,t.msg)),this._uploadTimer=null}),xP("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else SL.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(cF.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this._workerConnection.on(cF.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}async requestToInspectImage(){const e=uD(this,ZF.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void(xP("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&SL.debug("Only the track being played can be inspected"));this._sequence++;const n=await this.generateRequestData(e,t);this._workerConnection.sendMessage(n,!0,!0)}else xP("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&SL.debug("Only the track being published can be inspected")}async generateRequestData(e,t){let n=t.appId,i=t.cname,r=t.cid,o=t.vid,s=t.sid,a=t.uid;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await VM(d,n,i),u=this._sequence+"-"+r+"-"+a+"-"+c+"-"+kD(12,""),h={appId:n,cid:r,cname:i,deviceId:"",elapse:Ore.intToLong(Number(c-this._moderationStartTime)),fileSize:d.buffer.byteLength,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.24.8",sequence:this._sequence,sid:s,timestamp:Are(c),uid:a,vid:o,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};void 0===this._extraInfo&&delete h.callbackData;const p=qie(h);if(p.byteLength<this._workerMessageLengthLimit){if(xP("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?wre(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):wre(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},h);delete e.jpg,SL.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(e))}return p}{const t=this.quality*this._qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:i,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=DO.CancelToken.source(),this._workerConnection&&this._workerConnection.close(),this._moderationTimer&&window.clearInterval(this._moderationTimer),this._moderationTimer=null,this._uploadTimer&&window.clearTimeout(this._uploadTimer),this._uploadTimer=null,this.connectionState=zF.CLOSED,this.emit(ZF.STATE_CHANGE,qF.CLOSED)}}function Nre(e){if(PN(e.interval,"interval",1e3,1/0),e&&e.extraInfo&&e.extraInfo.length>1024)throw new YL(wN.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(e&&e.vendor&&e.vendor.length>1024)throw new YL(wN.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const Dre={name:"ImageModeration",create:function(e){let t=e.config;return Nre(t),new Ore(t)}};var Pre,Lre,kre,Mre,Ure,Vre,xre,Fre,Bre,jre,Gre,Wre,Kre,Hre,Yre,Xre,Jre,zre,Zre,qre,Qre,$re,eoe,toe,noe,ioe,roe,ooe,soe,aoe,coe,doe,loe,uoe,hoe,poe,_oe,Eoe,moe,foe,goe,Soe,Toe;function Roe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function voe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Roe(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Roe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}JD.setLogger(SL);let yoe=(Pre=KL(),Lre=KL({argsMap:(e,t)=>{if(!Array.isArray(t)){if(!(t instanceof Zk))return[t];t=[t]}return t.map((e=>e?Object(e).toString():"null"))}}),kre=KL({argsMap:(e,t)=>(t||(t=[]),Array.isArray(t)||t.trackMediaType!==wk.DATA?(Array.isArray(t)||(t=[t]),t.map((e=>e.getTrackId()))):[t.getChannelId()])}),Mre=KL({argsMap:(e,t,n,i)=>["object"==typeof t?t.uid:t,n,i]}),Ure=KL({argsMap:(e,t,n)=>[t,n]}),Vre=KL({argsMap:(e,t)=>t.map((e=>{let t=e.user,n=e.mediaType;return[null==t?void 0:t.uid,n]}))}),xre=KL({argsMap:(e,t,n,i)=>["object"==typeof t?t.uid:t,n,i]}),Fre=KL({argsMap:(e,t)=>t.map((e=>{let t=e.user,n=e.mediaType;return{uid:null==t?void 0:t.uid,mediaType:n}}))}),Bre=KL(),jre=KL(),Gre=KL(),Wre=KL(),Kre=KL(),Hre=KL(),Yre=KL(),Xre=KL(),Jre=KL(),zre=KL(),Zre=KL(),qre=KL(),Qre=KL(),$re=KL(),eoe=KL(),toe=KL(),noe=KL({argsMap:(e,t)=>[t]}),ioe=KL(),roe=KL(),ooe=KL(),soe=KL(),aoe=KL(),coe=KL(),doe=KL(),loe=KL(),uoe=KL({argsMap:(e,t)=>(Array.isArray(t)||(t=[t]),[JSON.stringify(t)])}),hoe=KL(),poe=KL(),_oe=KL(),Eoe=KL(),moe=KL(),foe=KL(),goe=KL({reportResult:!0}),Soe=KL(),Toe=class extends YN{get connectionState(){return this._gateway.state}get remoteUsers(){return this._users}get localTracks(){return this._p2pChannel.getAllTracks(!0)}get uid(){return this._uid}get channelName(){return this._channelName}get localDataChannels(){return this._p2pChannel.getAllDataChannels()}get mode(){return this._config.mode}get role(){var e;return(null===(e=this._config)||void 0===e?void 0:e.role)||"audience"}get codec(){return this._config.codec}get audioCodec(){return this._config.audioCodec||"opus"}get isStringUID(){return!!this._joinInfo&&!!this._joinInfo.stringUid}get __className__(){return"Client"}constructor(e,t){super(),zA(this,"store",void 0),zA(this,"_uid",void 0),zA(this,"_channelName",void 0),zA(this,"_uintUid",void 0),zA(this,"_users",[]),zA(this,"_config",void 0),zA(this,"_clientId",void 0),zA(this,"_appId",void 0),zA(this,"_sessionId",null),zA(this,"_key",void 0),zA(this,"_rtmConfig",{}),zA(this,"_joinInfo",void 0),zA(this,"_gateway",void 0),zA(this,"_statsCollector",void 0),zA(this,"_configDistribute",void 0),zA(this,"_leaveMutex",void 0),zA(this,"_publishMutex",void 0),zA(this,"_renewTokenMutex",void 0),zA(this,"_subscribeMutex",void 0),zA(this,"_encryptionMode","none"),zA(this,"_encryptionSecret",null),zA(this,"_encryptionSalt",null),zA(this,"_encryptDataStream",!1),zA(this,"_encryptDataStreamKey",null),zA(this,"_encryptDataStreamIv",null),zA(this,"_proxyServer",void 0),zA(this,"_turnServer",{servers:[],mode:"auto"}),zA(this,"_cloudProxyServerMode","disabled"),zA(this,"_isDualStreamEnabled",!1),zA(this,"_defaultStreamFallbackType",void 0),zA(this,"_lowStreamParameter",void 0),zA(this,"_streamFallbackTypeCacheMap",new Map),zA(this,"_remoteStreamTypeCacheMap",new Map),zA(this,"_axiosCancelSource",DO.CancelToken.source()),zA(this,"_audioVolumeIndicationInterval",void 0),zA(this,"_networkQualityInterval",void 0),zA(this,"_userOfflineTimeout",void 0),zA(this,"_streamRemovedTimeout",void 0),zA(this,"_rteDetailInterval",void 0),zA(this,"_liveTranscodeStreamingClient",void 0),zA(this,"_liveRawStreamingClient",void 0),zA(this,"_channelMediaRelayClient",void 0),zA(this,"_networkQualitySensitivity","normal"),zA(this,"_p2pChannel",void 0),zA(this,"_useLocalAccessPoint",!1),zA(this,"_setLocalAPVersion",void 0),zA(this,"_joinAndNotLeaveYet",!1),zA(this,"_numberOfJoinCount",0),zA(this,"_joinResponse",null),zA(this,"_earlyJoinAttempt",void 0),zA(this,"_remoteDefaultVideoStreamType",void 0),zA(this,"_inspect",void 0),zA(this,"_moderation",void 0),zA(this,"_license",void 0),zA(this,"_pendingPublishedUsers",[]),zA(this,"ntpAlignErrorCount",0),zA(this,"remoteInboundOffset",0),zA(this,"_peerConnectionState",void 0),zA(this,"_pendingRtpCapabilityChange",void 0),zA(this,"_fallbackServerInfo",void 0),zA(this,"_dualStreamMode",void 0),zA(this,"_handleLocalTrackEnable",((e,t,n)=>{this.publish(e,!1).then(t).catch(n)})),zA(this,"_handleLocalTrackDisable",((e,t,n)=>{this.unpublish(e).then(t).catch(n)})),zA(this,"_handleUserOnline",(e=>{if(xP("BLOCK_LOCAL_CLIENT")&&Px(e.uid,this.channelName))return void SL.debug("[".concat(e.uid,"] will be ignored in local"));this.isStringUID&&"string"!=typeof e.uid&&SL.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const t=this._users.find((t=>t.uid===e.uid));if(t)t._trust_in_room_=!0,t._is_pre_created&&(t._is_pre_created=!1,this.safeEmit(rD.USER_JOINED,t));else{const t=new Wte(e.uid,e.uint_id||e.uid);this._users.push(t),SL.debug("[".concat(this._clientId,"] user online"),e.uid),this.store.firstVideoFrameDecoded(t.uid,{userJoinNotify:Date.now()}),this.safeEmit(rD.USER_JOINED,t)}})),zA(this,"_handleUserOffline",(e=>{if(xP("BLOCK_LOCAL_CLIENT")&&Px(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));t&&(this._handleRemoveStream(e),this._handleRemoveDataChannels(e),t._audio_pre_subscribed||t._video_pre_subscribed?t._is_pre_created=!0:SD(this._users,t),this._remoteStreamTypeCacheMap.delete(t.uid),this._streamFallbackTypeCacheMap.delete(t.uid),SL.debug("[".concat(this._clientId,"] user offline"),e.uid,"reason:",e.reason),this.safeEmit(rD.USER_LEAVED,t,e.reason))})),zA(this,"_handleAddAudioOrVideoStream",((e,t,n,i,r,o,s,a)=>{if(xP("BLOCK_LOCAL_CLIENT")&&Px(t,this.channelName))return;const c=this._users.find((e=>e.uid===t));if(!c)return void SL.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));SL.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(c.uid,e,void 0,void 0,void 0,Date.now()),"video"===e&&this.store.firstVideoFrameDecoded(c.uid,{videoAddNotify:Date.now()});const d="audio"===e?c.hasAudio:c.hasVideo;c._uintid||(c._uintid=o||t),"audio"===e?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,"audio"===e?(c._audio_added_=!0,void 0!==n&&(c._audioSSRC=n),void 0!==i&&(c._cname=i),s&&(c._audioOrtc=s)):(c._video_added_=!0,void 0!==n&&(c._videoSSRC=n),void 0!==i&&(c._cname=i),void 0!==a&&(c._rtxSsrcId=a),s&&(c._videoOrtc=s)),("audio"===e?c.hasAudio:c.hasVideo)&&!d&&(SL.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(e)),this.safeEmit(rD.USER_PUBLISHED,c,e)),"video"===e?HL.onGatewayStream(this._sessionId,bL.ON_ADD_VIDEO_STREAM,IL.ON_ADD_VIDEO_STREAM,{peer:o||t,ssrc:c._videoSSRC}):HL.onGatewayStream(this._sessionId,bL.ON_ADD_AUDIO_STREAM,IL.ON_ADD_AUDIO_STREAM,{peer:o||t,ssrc:c._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(c,e,n).then((t=>{if(t&&(SL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof die))return this._p2pChannel.unsubscribe(c,e,!0).then((()=>this._subscribe(c,e,!0).catch((e=>{SL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())}))))})),this._p2pChannel.hasPendingRemoteMedia(c,e)&&(SL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,e,!0).catch((e=>{SL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})));const l=this._getEncodingName(r);"video"===e&&("unknown"===l?this.safeEmit(rD.AV1_DECODABLE_RESULT,!1):zO()||eN()||(null==l?void 0:l.toLocaleLowerCase())!==GP.av1||rte().then((e=>{xP("FLS_ENABLE_AV1_DECODE_DETECT")&&this.safeEmit(rD.AV1_DECODABLE_RESULT,e),e||this._gateway.downgradeCodec(l)})))})),zA(this,"_handleRemoveStream",(e=>{if(xP("BLOCK_LOCAL_CLIENT")&&Px(e.uid,this.channelName))return;const t=this._users.find((t=>t.uid===e.uid));if(!t)return void SL.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));SL.debug("[".concat(this._clientId,"] stream removed with uid ").concat(e.uid));let n=()=>{};t.hasAudio&&t.hasVideo?n=()=>{SL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(rD.USER_UNPUBLISHED,t,"audio"),SL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(rD.USER_UNPUBLISHED,t,"video")}:t.hasVideo?n=()=>{SL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished video track")),this.safeEmit(rD.USER_UNPUBLISHED,t,"video")}:t.hasAudio&&(n=()=>{SL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished audio track")),this.safeEmit(rD.USER_UNPUBLISHED,t,"audio")}),t._video_pre_subscribed||t._audio_pre_subscribed||(t._trust_audio_stream_added_state_=!0,t._trust_video_stream_added_state_=!0,t._audio_added_=!1,t._video_added_=!1,this._p2pChannel instanceof die&&this._p2pChannel.unsubscribe(t).then((e=>{if(e)return this._gateway.unsubscribe(e,t.uid)})),t._audioSSRC=void 0,t._videoSSRC=void 0,t._audioOrtc=void 0,t._videoOrtc=void 0,t._rtxSsrcId=void 0),HL.onGatewayStream(this._sessionId,bL.ON_REMOVE_STREAM,IL.ON_REMOVE_STREAM,{peer:e.uint_id||e.uid}),n()})),zA(this,"_handleSetStreamLocalEnable",((e,t,n)=>{if(xP("BLOCK_LOCAL_CLIENT")&&Px(t,this.channelName))return;const i=this._users.find((e=>e.uid===t));if(!i)return void SL.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));SL.debug("[".concat(this._clientId,"] local ").concat(e," ").concat(n?"enabled":"disabled"," with uid ").concat(t));const r="audio"===e?i.hasAudio:i.hasVideo;if("audio"===e){i._trust_audio_enabled_state_=!0;const e=i._audio_enabled_;if(i._audio_enabled_=n,i._audio_enabled_===e)return;{const e=i._audio_enabled_?"enable-local-audio":"disable-local-audio";SL.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(rD.USER_INFO_UPDATED,t,e)}}else{i._trust_video_enabled_state_=!0;const e=i._video_enabled_;if(i._video_enabled_=n,i._video_enabled_===e)return;{const e=i._video_enabled_?"enable-local-video":"disable-local-video";SL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(t,", msg: ").concat(e)),this.safeEmit(rD.USER_INFO_UPDATED,t,e)}}const o="audio"===e?i.hasAudio:i.hasVideo;return r!==o?!r&&o?(SL.info("[".concat(this._clientId,"] remote user ").concat(t," published ").concat(e)),void this.safeEmit(rD.USER_PUBLISHED,i,e)):("video"===e&&i._videoTrack&&i._videoTrack._destroy(),"audio"===e&&i._audioTrack,this._p2pChannel.muteRemote(i,e),SL.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished ").concat(e)),void this.safeEmit(rD.USER_UNPUBLISHED,i,e)):void 0})),zA(this,"_handleMuteStream",((e,t,n)=>{if(xP("BLOCK_LOCAL_CLIENT")&&Px(e,this.channelName))return;SL.debug("[".concat(this._clientId,"] receive mute message"),e,t,n);const i=this._users.find((t=>t.uid===e));if(!i)return void SL.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(e));const r="audio"===t?i.hasAudio:i.hasVideo;if("audio"===t){i._trust_audio_mute_state_=!0;const t=i._audio_muted_;if(i._audio_muted_=n,i._audio_muted_===t)return;{this.store.aiClientMode&&(n?Ree.mute():Ree.unmute());const t=i._audio_muted_?"mute-audio":"unmute-audio";SL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(rD.USER_INFO_UPDATED,e,t)}}else{i._trust_video_mute_state_=!0;const t=i._video_muted_;if(i._video_muted_=n,i._video_muted_===t)return;{const t=i._video_muted_?"mute-video":"unmute-video";SL.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(e,", msg: ").concat(t)),this.safeEmit(rD.USER_INFO_UPDATED,e,t)}}const o="audio"===t?i.hasAudio:i.hasVideo;if(r!==o){if(!r&&o){return("audio"===t?i._audioSSRC:i._videoSSRC)?(SL.info("[".concat(this._clientId,"] remote user ").concat(e," published ").concat(t)),void this.safeEmit(rD.USER_PUBLISHED,i,t)):void SL.warning("[".concat(this._clientId,"] remote user ").concat(e," receive ").concat(t," unmute message  before add stream message, ").concat(t," SSRC doesn't exist yet."))}"video"===t&&i._videoTrack&&!i._video_pre_subscribed&&i._videoTrack._destroy(),"audio"===t&&i._audioTrack,this._p2pChannel.muteRemote(i,t),SL.info("[".concat(this._clientId,"] remote user ").concat(e," unpublished ").concat(t)),this.safeEmit(rD.USER_UNPUBLISHED,i,t)}})),zA(this,"_handleP2PLost",(async e=>{SL.debug("[".concat(this._clientId,"] receive p2p lost"),e),parseInt(e.p2pid,10)===this.store.p2pId?"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?this._gateway.reconnect("tryNext"):await this._p2pChannel.requestReconnect():SL.warning("[".concat(this._clientId,"] P2PLost stream not found"),e)})),zA(this,"_handleTokenWillExpire",(()=>{SL.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(rD.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)})),zA(this,"_handleBeforeUnload",(e=>{"beforeunload"===e.type&&void 0!==e.returnValue&&""!==e.returnValue||(this.leave(),SL.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))})),zA(this,"_handleUpdateNetworkQuality",(()=>{if("normal"===this._networkQualitySensitivity)return;if(navigator&&void 0!==navigator.onLine&&!navigator.onLine)return void this.safeEmit(rD.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const e={downlinkNetworkQuality:0,uplinkNetworkQuality:0};e.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),e.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(rD.NETWORK_QUALITY,e)})),zA(this,"_handleP2PAddAudioOrVideoStream",((e,t,n,i)=>{const r=this._users.find((e=>e.uid===t));if(!r)return void SL.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));SL.debug("[".concat(this._clientId,"] stream added with uid ").concat(t,", type ").concat(e)),this.store.subscribe(r.uid,e,void 0,void 0,void 0,Date.now());const o="audio"===e?r.hasAudio:r.hasVideo;"audio"===e?r._trust_audio_stream_added_state_=!0:r._trust_video_stream_added_state_=!0,"audio"===e?(r._audio_added_=!0,void 0!==n&&(r._audioSSRC=n),void 0!==i&&(r._audioMid=i)):(r._video_added_=!0,void 0!==n&&(r._videoSSRC=n),void 0!==i&&(r._videoMid=i)),("audio"===e?r.hasAudio:r.hasVideo)&&!o&&(SL.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published ").concat(e)),this.safeEmit(rD.USER_PUBLISHED,r,e)),this._p2pChannel.hasPendingRemoteMedia(r,e)&&(SL.debug("[".concat(this._clientId,"] resubscribe ").concat(e," for user ").concat(r.uid," after reconnect.")),this._subscribe(r,e,!0).catch((e=>{SL.error("[".concat(this._clientId,"] resubscribe error"),e.toString())})))})),this._config=e,this._clientId=t||kD(5,"client-"),this.store=new class{constructor(e,t,n,i,r){CN(this,"state",void 0),this.state={codec:e,audioCodec:t,mode:n,clientId:i,sessionId:null,p2pId:0,dcId:0,mediaDcId:555,pubId:0,subId:0,keyMetrics:{publish:[],subscribe:[],firstVideoFrameDecoded:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:NP.Default,hasStartJoinChannel:!1,isABTestSuccess:!1,rteUrl:void 0,rteSid:void 0,autoSubscribe:!1,autoReceiveAndPlayAudio:!1,enableInstantMuteRestore:!1,networkQualityProbe:!1,useDcSignal:!!r,aiClientMode:!1,preSubOptions:void 0,flexiblePC:!1}}dispatch(e){this.state=function(e,t){switch(t.type){case jP.SET_SESSION_ID:return IN(IN({},e),{},{sessionId:t.sessionId});case jP.SET_P2P_ID:return IN(IN({},e),{},{p2pId:t.p2pId});case jP.SET_UID:return IN(IN({},e),{},{uid:t.uid});case jP.SET_INT_UID:return IN(IN({},e),{},{intUid:t.intUid});case jP.SET_PUB_ID:return IN(IN({},e),{},{pubId:t.pubId});case jP.KEY_METRIC_CLIENT_CREATED:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{clientCreated:t.metric})});case jP.KEY_METRIC_JOIN_START:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{joinStart:t.metric})});case jP.KEY_METRIC_PRELOAD_START:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{preloadStart:t.metric})});case jP.KEY_METRIC_PRELOAD_END:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{preloadEnd:t.metric})});case jP.KEY_METRIC_JOIN_END:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{joinEnd:t.metric})});case jP.KEY_METRIC_REQUEST_AP_START:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{requestAPStart:t.metric})});case jP.KEY_METRIC_REQUEST_AP_END:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{requestAPEnd:t.metric})});case jP.KEY_METRIC_REQUEST_SUA_END:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{requestSUAEnd:t.metric})});case jP.KEY_METRIC_BEFORE_CONNECT:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{beforeConnect:t.metric})});case jP.KEY_METRIC_PEER_RECEIVER:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{peerReceiver:t.metric})});case jP.KEY_METRIC_SIGNAL_CONNECTED:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{signalConnected:t.metric})});case jP.KEY_METRIC_JOIN_REQ:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{joinReq:t.metric})});case jP.KEY_METRIC_JOIN_REP:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{joinRep:t.metric})});case jP.KEY_METRIC_JOIN_GATEWAY_START:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{joinGatewayStart:t.metric})});case jP.KEY_METRIC_JOIN_GATEWAY_END:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{joinGatewayEnd:t.metric})});case jP.KEY_METRIC_PEER_CONNECTION_START:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{peerConnectionStart:t.metric})});case jP.KEY_METRIC_PEER_CONNECTION_END:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{peerConnectionEnd:t.metric})});case jP.KEY_METRIC_DESCRIPTION_START:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{descriptionStart:t.metric})});case jP.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{signalChannelOpen:t.metric})});case jP.KEY_METRIC_ICE_CONNECTION_END:return IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{iceConnectionEnd:t.metric})});case jP.KEY_METRIC_PUBLISH:{const n=e.keyMetrics.publish,i=n.findIndex((e=>e.trackId===t.metric.trackId));return-1!==i?(n[i]=IN(IN({},n[i]),t.metric),IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{publish:[...n]})})):IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{publish:[...e.keyMetrics.publish,t.metric]})})}case jP.KEY_METRIC_SUBSCRIBE:{const n=e.keyMetrics.subscribe,i=n.findIndex((e=>e.userId===t.metric.userId&&e.type===t.metric.type));return-1!==i?(n[i]=IN(IN({},n[i]),t.metric),IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{subscribe:[...n]})})):IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{subscribe:[...e.keyMetrics.subscribe,t.metric]})})}case jP.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED:{const n=e.keyMetrics.firstVideoFrameDecoded,i=n.findIndex((e=>e.userId===t.metric.userId));return-1!==i?(n[i]=IN(IN({},n[i]),t.metric),IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{firstVideoFrameDecoded:[...n]})})):IN(IN({},e),{},{keyMetrics:IN(IN({},e.keyMetrics),{},{firstVideoFrameDecoded:[...e.keyMetrics.firstVideoFrameDecoded,t.metric]})})}case jP.RESET_FIRST_VIDEO_FRAME_DECODED:return e.keyMetrics.firstVideoFrameDecoded=[],e;case jP.SET_CLOUD_PROXY_SERVER_MODE:return e.cloudProxyServerMode=t.mode,e;case jP.RECORD_JOIN_CHANNEL_SERVICE:return"number"!=typeof t.index?e.joinChannelServiceRecords=[...e.joinChannelServiceRecords,t.record]:(e.joinChannelServiceRecords[t.index]=IN(IN({},e.joinChannelServiceRecords[t.index]),t.record),e.joinChannelServiceRecords=[...e.joinChannelServiceRecords]),e;case jP.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return e.joinChannelServiceRecords=[],e;case jP.RESET_KEY_METRICS:return e.keyMetrics={publish:[],subscribe:[],firstVideoFrameDecoded:[]},e;case jP.SET_USE_P2P:return IN(IN({},e),{},{useP2P:t.val});case jP.SET_TRANSPORT_TYPE:return IN(IN({},e),{},{p2pTransport:t.val});case jP.SET_RTE_URL:return IN(IN({},e),{},{rteUrl:t.rteUrl});case jP.SET_RTE_SID:return IN(IN({},e),{},{rteSid:t.rteSid});default:return e}}(this.state,e)}get useDcSignal(){return this.state.useDcSignal}set useDcSignal(e){this.state.useDcSignal=e}get aiClientMode(){return this.state.aiClientMode}set aiClientMode(e){this.state.aiClientMode=e}set autoSubscribe(e){this.state.autoSubscribe=e}get autoSubscribe(){return this.state.autoSubscribe}set autoReceiveAndPlayAudio(e){this.state.autoReceiveAndPlayAudio=e}get autoReceiveAndPlayAudio(){return this.state.autoReceiveAndPlayAudio}set enableInstantMuteRestore(e){this.state.enableInstantMuteRestore=e}get enableInstantMuteRestore(){return this.state.enableInstantMuteRestore}set networkQualityProbe(e){this.state.networkQualityProbe=e}get networkQualityProbe(){return this.state.networkQualityProbe}set preSubOptions(e){this.state.preSubOptions=e}get preSubOptions(){return this.state.preSubOptions}set sessionId(e){this.dispatch({type:jP.SET_SESSION_ID,sessionId:e})}get sessionId(){return this.state.sessionId}set rteUrl(e){this.dispatch({type:jP.SET_RTE_URL,rteUrl:e})}get rteUrl(){return this.state.rteUrl}set rteSid(e){this.dispatch({type:jP.SET_RTE_SID,rteSid:e})}get rteSid(){return this.state.rteSid}set cid(e){this.state.cid=e}get cid(){return this.state.cid}set codec(e){this.state.codec=e}get codec(){return this.state.codec}get mode(){return this.state.mode}get audioCodec(){return this.state.audioCodec}get clientId(){return this.state.clientId}set p2pId(e){this.dispatch({type:jP.SET_P2P_ID,p2pId:e})}get p2pId(){return this.state.p2pId}set dcId(e){this.dispatch({type:jP.SET_DC_ID,dcId:e})}get dcId(){return this.state.dcId}set mediaDcId(e){this.state.mediaDcId=e}get mediaDcId(){return this.state.mediaDcId}set uid(e){this.dispatch({type:jP.SET_UID,uid:e})}get uid(){return this.state.uid}set intUid(e){this.dispatch({type:jP.SET_INT_UID,intUid:e})}get intUid(){return this.state.intUid}set pubId(e){this.dispatch({type:jP.SET_PUB_ID,pubId:e})}get pubId(){return this.state.pubId}set cloudProxyServerMode(e){this.dispatch({type:jP.SET_CLOUD_PROXY_SERVER_MODE,mode:e})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(e){this.dispatch({type:jP.SET_USE_P2P,val:e})}get useP2P(){return this.state.useP2P}set p2pTransport(e){this.dispatch({type:jP.SET_TRANSPORT_TYPE,val:e})}get p2pTransport(){return this.state.p2pTransport}set hasStartJoinChannel(e){this.state.hasStartJoinChannel=e}get hasStartJoinChannel(){return this.state.hasStartJoinChannel}set flexiblePC(e){this.state.flexiblePC=e}get flexiblePC(){return this.state.flexiblePC}set isABTestSuccess(e){this.state.isABTestSuccess=e}get isABTestSuccess(){return this.state.isABTestSuccess}clientCreated(){this.dispatch({type:jP.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:jP.KEY_METRIC_JOIN_START,metric:Date.now()})}preloadStart(){this.dispatch({type:jP.KEY_METRIC_PRELOAD_START,metric:Date.now()})}preloadEnd(){this.dispatch({type:jP.KEY_METRIC_PRELOAD_END,metric:Date.now()})}joinEnd(){this.dispatch({type:jP.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:jP.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:jP.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}requestSUAEnd(){this.dispatch({type:jP.KEY_METRIC_REQUEST_SUA_END,metric:Date.now()})}beforeConnect(){this.dispatch({type:jP.KEY_METRIC_BEFORE_CONNECT,metric:Date.now()})}peerReceiver(){this.dispatch({type:jP.KEY_METRIC_PEER_RECEIVER,metric:Date.now()})}signalConnected(){this.dispatch({type:jP.KEY_METRIC_SIGNAL_CONNECTED,metric:Date.now()})}joinReq(){this.dispatch({type:jP.KEY_METRIC_JOIN_REQ,metric:Date.now()})}joinRep(){this.dispatch({type:jP.KEY_METRIC_JOIN_REP,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:jP.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:jP.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:jP.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:jP.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}firstVideoFrameDecoded(e,t){this.dispatch({type:jP.KEY_METRIC_FIRST_VIDEO_FRAME_DECODED,metric:IN({userId:e},t)})}descriptionStart(){this.dispatch({type:jP.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:jP.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:jP.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(e,t,n,i){this.dispatch({type:jP.KEY_METRIC_PUBLISH,metric:IN(IN({trackId:e,type:t},n&&{publishStart:n}),i&&{publishEnd:i})})}subscribe(e,t,n,i,r,o,s){this.dispatch({type:jP.KEY_METRIC_SUBSCRIBE,metric:IN(IN(IN(IN(IN({userId:e,type:t},n&&{subscribeStart:n}),i&&{subscribeEnd:i}),r&&{firstFrame:r}),o&&{streamAdded:o}),s&&{firstDecoded:s})})}massSubscribe(e,t,n,i){e.forEach((e=>{this.dispatch({type:jP.KEY_METRIC_SUBSCRIBE,metric:IN(IN(IN({userId:e.userId,type:e.type},t&&{subscribeStart:t}),n&&{subscribeEnd:n}),i&&{firstFrame:i})})}))}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(e,t){"gateway"===e.service&&Array.isArray(e.urls)&&(e.urls=e.urls.map((e=>e.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2"))));try{return"number"!=typeof t?(this.dispatch({type:jP.RECORD_JOIN_CHANNEL_SERVICE,record:IN(IN({},e),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(t<0||t>=this.state.joinChannelServiceRecords.length||this.dispatch({type:jP.RECORD_JOIN_CHANNEL_SERVICE,record:e,index:t}),t)}catch(e){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:jP.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:jP.RESET_KEY_METRICS})}resetFirstVideoFrameDecoded(){this.dispatch({type:jP.RESET_FIRST_VIDEO_FRAME_DECODED})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(e){return[]}}}(e.codec,e.audioCodec,e.mode,this._clientId,1===xP("SIGNAL_CHANNEL")&&fee("DataChannelConnection"));const n=!gN()&&!$O();let i;if(!n&&e.aiClientMode&&SL.warning("[".concat(t,"] aiClientMode is only supported on desktop Chrome, Safari, and Edge. ")+"falling back to WebRTC audio reception."),this.store.aiClientMode=n&&!!e.aiClientMode&&fee("AiAudioModeExtension"),this._leaveMutex=new JD("client-leave",this._clientId),this._publishMutex=new JD("client-publish",this._clientId),this._renewTokenMutex=new JD("client-renewtoken",this._clientId),this._subscribeMutex=new JD("client-subscribe",this._clientId),this.store.clientCreated(),e.proxyServer&&this.setProxyServer(e.proxyServer,!0),e.turnServer&&this.setTurnServer(e.turnServer,!0),SL.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(wP," build: ").concat(kP,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),e.clientRoleOptions)try{iD(e.clientRoleOptions),i=Object.assign({},e.clientRoleOptions)}catch(e){SL.warning("[".concat(this._clientId,"] ").concat(e.toString()))}var r;this._statsCollector=new Bte(this.store),this._statsCollector.onStatsException=(e,t,n)=>{SL.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(e,", msg: ").concat(t,", uid: ").concat(n)),e===Ute.VIDEO_ENCODE_FAILED&&this.localTracks.forEach((e=>{e instanceof RV&&xP("ENABLE_ENCODE_EXCEPTION")&&e.findClosestProfile()})),this.safeEmit(rD.EXCEPTION,{code:e,msg:t,uid:n})},this._statsCollector.onUploadPublishDuration=(e,t,n,i)=>{const r=this._users.find((t=>t.uid===e));if(r){this.store.keyMetrics&&(this.store.firstVideoFrameDecoded(r.uid,{peerPublishDuration:n,peerPubStatusMs:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(r)),HL.peerPublishStatus(this._sessionId,{subscribeElapse:i,audioPublishDuration:t,videoPublishDuration:n,peer:r._uintid})}},this._statsCollector.onVideoCodecChanged=e=>{if(xP("VIDEO_STANDARD_BITRATE_VERSION")&&("av1"===e||"h265"===e||"h264"===e)){const t=this.localTracks.find((e=>e instanceof TV));t&&1!==t._saveEncodeBitrateRatio&&t.setSaveEncodeBitrateRatio("h264"===e?xP("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P="p2p"===e.mode,this._gateway=new Iee(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:e.websocketRetryConfig||ZD,httpRetryConfig:e.httpRetryConfig||ZD,forceWaitGatewayResponse:void 0===e.forceWaitGatewayResponse||e.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:e.role,clientRoleOptions:i}),this._configDistribute=new kte(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(r={store:this.store,statsCollector:this._statsCollector},mee("P2PChannel").create(r)),this._handleP2PEvents()):this._p2pChannel=new die(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}async joinMeta(e,t,n,i,r){let o=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];VP("JOIN_GATEWAY_USE_443PORT_ONLY",o),VP("JOIN_GATEWAY_USE_DUAL_DOMAIN",s);const a=this._gateway.signal.websocket;return a instanceof fB&&(a.use443PortOnly=o,a.tryDoubleDomain=s),async function(e,t,n){kO.get(e)||kO.set(e,[]),MO.get(e)||MO.set(e,t),UO.get(e)||UO.set(e,0);const i=kO.get(e),r=MO.get(e);if(!i||!r)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(UO.get(e)===r){const e=LO();i.push(e),await e.promise}UO.set(e,UO.get(e)+1);for(var o=arguments.length,s=new Array(o>3?o-3:0),a=3;a<o;a++)s[a-3]=arguments[a];const c=await n(...s);return UO.set(e,UO.get(e)-1),UO.get(e)===r-1&&i.length>0&&(i[0].resolve(),i.shift()),0===UO.get(e)&&(kO.set(e,[]),MO.set(e,0),UO.set(e,0)),c}("client.join",xP("JOIN_MAX_CONCURRENCY"),this.join.bind(this),e,t,n,i,r)}async join(e,t,n,i,r){SL.scheduleUploadStart();const o=++this._numberOfJoinCount;this.store.joinStart(),i&&(this.store.uid=i);const s="HTTPS"===($D||$D||($D=(window.location.protocol.split(":")[0]||"").toUpperCase(),$D)),a=oP()?window.isSecureContext:"Browser Not Support";if(!oP()&&!s||!window.isSecureContext){const e="The website must be running in a secure context (About secure context: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts ), otherwise the media collection will be restricted by the browser";SL.warning(e)}let c;HL.setAppId(e);try{if(!n&&null!==n)throw new YL(wN.INVALID_PARAMS,"Invalid token: ".concat(n,". If you don not use token, set it to null"));if(n&&kN(n,"token",1,2047),kN(e,"appid",1,2047),dF(t),i&&lF(i),r)if("string"==typeof r)kN(r,"optionalInfo",1,256),c=r;else{if("object"!=typeof r)throw new YL(wN.INVALID_PARAMS,"Invalid options: options is not a string or object");{const e=r.autoSubscribe,t=r.enableInstantMuteRestore,n=r.networkQualityProbe,i=r.preSubOptions,o=r.autoReceiveAndPlayAudio;void 0!==e&&(NN(e,"autoSubscribe"),SL.info("[".concat(this._clientId,"] join: autoSubscribe: ").concat(e)),this.store.autoSubscribe=e),void 0!==o&&(NN(o,"autoReceiveAndPlayAudio"),SL.info("[".concat(this._clientId,"] join: autoReceiveAndPlayAudio: ").concat(o)),o&&(this.store.autoSubscribe=!0,this.store.autoReceiveAndPlayAudio=!0)),t&&(NN(t,"enableInstantMuteRestore"),SL.info("[".concat(this._clientId,"] join: enableInstantMuteRestore: ").concat(t)),this.store.enableInstantMuteRestore=t),n&&(NN(n,"networkQualityProbe"),SL.info("[".concat(this._clientId,"] join: networkQualityProbe: ").concat(n)),this.store.networkQualityProbe=n),Array.isArray(i)&&(MN(i,"preSubOptions"),i.forEach((e=>{lF(e.uid),function(e,t){if("string"!=typeof e&&!(e instanceof HTMLElement||e instanceof HTMLVideoElement))throw new ON(wN.INVALID_PARAMS,"".concat(t," should be a string or a HTML element"))}(e.element,"element")})),SL.info("[".concat(this._clientId,"] join: preSubOptions: ").concat(i.map((e=>"".concat(e.uid,": ").concat("string"==typeof e.element?e.element:e.element.id))).join(","))),this.store.preSubOptions=i),this.store.aiClientMode&&this.store.autoSubscribe&&(SL.info("[".concat(this._clientId,"] join: enable AIQoS preload playback for aiClientMode + autoSubscribe")),this.store.autoReceiveAndPlayAudio=!0)}}}catch(r){throw HL.reportApiInvoke(MD(),{clientId:this._clientId,name:zN.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:ZN.TRACER}).onError(r),r}if(this._leaveMutex.isLocked){SL.debug("[".concat(this._clientId,"] join: waiting leave operation"));(await this._leaveMutex.lock())(),SL.debug("[".concat(this._clientId,"] join: continue"))}if(this._joinAndNotLeaveYet=!0,"DISCONNECTED"!==this.connectionState){const r=new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw HL.reportApiInvoke(MD(),{clientId:this._clientId,name:zN.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:ZN.TRACER}).onError(r),r}const d=Dte(this._clientId);try{this._gateway.state="CONNECTING",this.store.preloadStart();const r=await Gie({appId:e,cname:t,uid:i,stringUid:"string"==typeof i?i:void 0,token:n||e,cloudProxyServer:this._cloudProxyServerMode});if(this.store.preloadEnd(),!this._joinAndNotLeaveYet)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const p=(null==r?void 0:r.sid)||MD();SL.info("[".concat(this._clientId,"] start join channel ").concat(t,", join number: ").concat(o)),this._sessionId||(this._sessionId=p,this.store.sessionId=this._sessionId);const _=HL.reportApiInvoke(this._sessionId,{id:this._clientId,clientId:this._clientId,name:zN.JOIN,options:[e,t,n,i],states:{isHttps:s,isSecureContext:a},tag:ZN.TRACER}),E=voe(voe(voe({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:e,sid:this._sessionId,cname:t,uid:"string"!=typeof i?i:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:n||e,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:c,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!r},void 0!==this._remoteDefaultVideoStreamType&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:xP("AP_REQUEST_DETAIL")||void 0,apRequestDetailExtend:xP("AP_REQUEST_DETAIL_EXTEND")});if(this._useLocalAccessPoint&&(E.setLocalAPVersion=this._setLocalAPVersion),"string"==typeof i&&(E.stringUid=i,this._uintUid?(E.uid=this._uintUid,this._uintUid=void 0):E.uid=0),"none"!==this._encryptionMode&&this._encryptionSecret){if(E.aesmode=this._encryptionMode,E.aespassword=await(async e=>{const t=function(e){const t=window.atob("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu\nSTM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+\nHvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy\nxQiYDz3vqa6bP29adwIDAQAB"),n=new Uint8Array(new ArrayBuffer(t.length));for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);return n}(),n=await window.crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),i=WN(e),r=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},n,i);return function(e){let t="";for(let n=0;n<e.length;n+=1)t+=String.fromCharCode(e[n]);return window.btoa(t)}(new Uint8Array(r))})(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(E.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&("aes-128-gcm2"===this._encryptionMode||"aes-256-gcm2"===this._encryptionMode))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){const e=new TextEncoder,t=xP("USE_PURE_ENCRYPTION_MASTER_KEY")?e.encode(E.appId+this._encryptionSecret+this._encryptionSecret):e.encode(E.appId+E.cname+this._encryptionSecret);this._encryptDataStreamIv=await async function(e,t,n){const i=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256,o=await window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:HP,hash:"SHA-256",salt:n},i,r+KP);return new Uint8Array(o).subarray(r/8)}(this._encryptionMode,t,ID(this._encryptionSalt)),this._encryptDataStreamKey=await async function(e,t,n){const i=await window.crypto.subtle.importKey("raw",t,"PBKDF2",!1,["deriveBits","deriveKey"]),r="aes-128-gcm2"===e?128:256;return await window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:HP,hash:"SHA-256",salt:n},i,{name:"AES-GCM",length:r},!0,["encrypt","decrypt"])}(this._encryptionMode,t,ID(this._encryptionSalt))}else a?SL.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):SL.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,SL.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:t,appId:e,stringUid:E.stringUid});const m=this._sessionId;setTimeout((()=>{"CONNECTING"===this.connectionState&&m===this._sessionId&&HL.joinChannelTimeout(this._sessionId,5)}),5e3);try{var l;let i;const s=E.cloudProxyServer;if(Ui(l=["proxy3","proxy4","proxy5"]).call(l,s)){const e=xP("PROXY_SERVER_TYPE3");Array.isArray(e)?E.proxyServer=e[0]:E.proxyServer=e}HL.setProxyServer(E.proxyServer),SL.setProxyServer(E.proxyServer),this.store.requestAPStart(),this.store.flexiblePC=!!xP("FLEXIBLE_PC");const a=xP("ENABLE_JOIN_V4")&&JL().supportPCSetConfiguration&&!this.store.useDcSignal&&!this.store.useP2P&&!this._p2pChannel.isPlanB&&"disabled"===E.cloudProxyServer&&!E.proxyServer&&!E.useLocalAccessPoint&&!this.store.aiClientMode,c=()=>{if(!this._joinAndNotLeaveYet||this._numberOfJoinCount!==o)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))};if(a){this.store.flexiblePC=!0;try{E.stringUid&&!E.uid&&(E.uid=await lte(E.stringUid,E,this._axiosCancelSource.token,this._config.httpRetryConfig||ZD,this.store).finally((()=>{this.store.requestSUAEnd()})),SL.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(E.stringUid," => ").concat(E.uid)),c()),SL.debug("[".concat(this._clientId,"] try use best first frame line"));const e=await this._p2pChannel.startP2PConnection({isPreallocation:!0,turnServer:E.turnServer});c(),i=await dte(E,this._axiosCancelSource.token,this._config.httpRetryConfig||ZD,this.store,e),c(),SL.debug("[".concat(this._clientId,"] get serverInfo from sdp endpoint")),xP("ENABLE_SDP_ENDPOINT_LOG")&&SL.debug("[".concat(this._clientId,"] serverInfo: "),i)}catch(e){if((null==e?void 0:e.code)===wN.INVALID_OPERATION||(null==e?void 0:e.code)===wN.OPERATION_ABORTED)throw e;if(!this._joinAndNotLeaveYet||this._numberOfJoinCount!==o)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));i=void 0,SL.debug("[".concat(this._clientId,"] join channel with sdp endpoint failed, fallback to normal join ap"),e)}}if(i);else if(r){if(SL.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(E.stringUid?", ".concat(E.stringUid," => ").concat(r.intUid):""," ")),E.stringUid&&!E.uid&&(E.uid=r.intUid),i={gatewayInfo:r.ap.gatewayInfo},xP("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&"auto"===E.turnServer.mode)if(0===r.ap.proxyInfo.addresses.length)SL.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const e=(await C7(r.ap.proxyInfo,r.ap.gatewayInfo.uid)).map((e=>({turnServerURL:e.address,tcpport:e.tcpport||DP.tcpport,udpport:e.udpport||DP.udpport,username:e.username||DP.username,password:e.password||DP.password,forceturn:!1,security:!0})));E.turnServer={mode:"manual",servers:e}}Xie(r,E.stringUid)}else if(E.stringUid&&!E.uid){let e;var u=KC(await cp.all([lte(E.stringUid,E,this._axiosCancelSource.token,this._config.httpRetryConfig||ZD,this.store).finally((()=>{this.store.requestSUAEnd()})),cte(E,this._axiosCancelSource.token,this._config.httpRetryConfig||ZD,!0,this.store).finally((()=>{this.store.requestAPEnd()}))]),2);e=u[0],i=u[1],SL.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(E.stringUid," => ").concat(e)),E.uid=e,i.gatewayInfo.uid=e,i.gatewayInfo.res.uid=e}else i=await cte(E,this._axiosCancelSource.token,this._config.httpRetryConfig||ZD,!0,this.store);if(!this._joinAndNotLeaveYet)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));a&&c(),this.store.requestAPEnd(),setTimeout((()=>{this._configDistribute.startGetConfigDistribute(E,this._axiosCancelSource.token),this._configDistribute.on(PF.UPDATE_BITRATE_LIMIT,(e=>{this._p2pChannel.updateBitrateLimit(e)})),this._configDistribute.on(PF.UPDATE_CLIENT_ROLE_OPTIONS,(e=>{this._setClientRoleOptions(e)})),this._configDistribute.on(PF.UPDATE_REMOTE_VIDEO_STREAM_TYPE,(e=>{var t;Ui(t=[0,1,4,5,6,7,8,9]).call(t,e)&&(this.remoteUsers.forEach((t=>{this._remoteStreamTypeCacheMap.get(t.uid)!==e&&this.setRemoteVideoStreamType(t.uid,e)})),this.setRemoteDefaultVideoStreamType(e))})),this._configDistribute.on(PF.FALLBACK_TO_HLS,(e=>{e&&this.safeEmit(rD.FALLBACK_TO_HLS,oD.CONFIG)})),this._configDistribute.on(PF.UPDATE_VOS_CONFIGURE,(e=>{this._gateway.setConfigure(e).catch((e=>{SL.debug("[".concat(this._clientId,"] auto set vos config failed"),e)}))}))}),0),this._key=n||e;const p=i.gatewayInfo,m=E.uid?E.uid:p.uid;this._joinInfo=voe(voe({},E),{},{cid:p.cid,uid:m,vid:p.vid,apResponse:p.res,apGatewayAddress:p.apGatewayAddress,uni_lbs_ip:p.uni_lbs_ip,gatewayAddrs:p.gatewayAddrs}),this.store.intUid=m,this.store.cid=p.cid;const f=this._joinInfo.apResponse.signalResponse,g=this._joinInfo.apResponse.addresses[0],S=!(!(this._p2pChannel instanceof die)||this._p2pChannel.isPlanB||this.store.useDcSignal||this.store.useP2P||!f||!g.iceUfrag||!g.icePwd||!xP("FINGERPRINT")&&!g.fingerprint);this._earlyJoinAttempt=S?function(e){if(!xP("ENABLE_JOIN_V4")||!e.signalResponse)return;const t=e.edgeAddress,n=xP("FINGERPRINT")||(null==t?void 0:t.fingerprint);return null!=t&&t.iceUfrag&&t.icePwd&&n?new Eie({id:e.id,signalResponse:e.signalResponse,initialRole:e.initialRole,edge:{iceUfrag:t.iceUfrag,icePwd:t.icePwd,fingerprint:n}}):void 0}({id:o,signalResponse:f,initialRole:E.role,edgeAddress:g}):void 0,this._earlyJoinAttempt?this._joinResponse=this._earlyJoinAttempt.preJoinResponse:this.store.flexiblePC=!!xP("FLEXIBLE_PC");const T=await this._joinGateway();if(!this._joinAndNotLeaveYet)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));a&&c(),_.onSuccess(T),this._appId=e,this._channelName=E.cname,this._uid=T,this.store.uid=T,setTimeout((()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),!zO()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(zO()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()}),0);const R=E.stringUid?"string uid: ".concat(E.stringUid,",uid: ").concat(E.uid):"uid: ".concat(this._uid);return SL.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(t,",").concat(R)),this.store.joinEnd(),h=this,Ui(Nx).call(Nx,h)||Nx.push(h),"disabled"===this._cloudProxyServerMode&&JL().supportWebCrypto&&xP("ENABLE_PRELOAD")&&Hie(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0),this._sessionId&&HL.reportRteDetail(this._sessionId),this._rteDetailInterval=window.setInterval((()=>{this._sessionId&&HL.reportRteDetail(this._sessionId)}),xP("RTE_DETAIL_REPORT_INTERVAL")||6e4),d.markJoined(),T}catch(e){const t=Array.isArray(e)?e[0]:e;throw t&&t.code===wN.OPERATION_ABORTED?SL.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t):SL.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),t),t.code!==wN.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),_.onError(t),t}}finally{d.releaseIfNotJoined()}var h}async _joinGateway(){if(!this._joinInfo||!this._key)throw new YL(wN.INVALID_OPERATION);try{return this._earlyJoinAttempt?await this._gateway.joinWithSDPEndpoint(this._joinInfo,this._key,this._earlyJoinAttempt):await this._gateway.join(this._joinInfo,this._key)}catch(e){if(e.code===wN.INIT_DATACHANNEL_TIMEOUT){if(this._gateway.leave(!0,$N.FALLBACK),SL.debug("[".concat(this._clientId,"] join by datachannel timeout, fallback to websocket")),!this._joinInfo||!this._key)throw new YL(wN.INVALID_OPERATION);return HL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:zN.DATACHANNEL_FAILBACK,options:[this.store.clientId],tag:ZN.TRACER}).onSuccess(),await this._joinGateway()}throw e}}async leave(){SL.info("[".concat(this._clientId,"] Leaving channel"));const e=()=>{!zO()&&this.store.useDcSignal?(window.addEventListener("beforeunload",this._handleBeforeUnload),window.addEventListener("pagehide",this._handleBeforeUnload)):window.addEventListener(zO()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const t=Nx.indexOf(e);-1!==t&&Nx.splice(t,1)}(this),this._statsCollector.stopUpdateStats()};this.store.useDcSignal||e();const t=await this._leaveMutex.lock();if("DISCONNECTED"===this.connectionState)return SL.info("[".concat(this._clientId,"] Leaving channel repeated, success")),t(),void Nte(this._clientId);await this._gateway.leave("CONNECTED"!==this.connectionState,$N.LEAVE),SL.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),t(),this.store.useDcSignal&&e(),Nte(this._clientId)}async publish(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!Array.isArray(e)){if(!(e instanceof Zk))return this._publishDataChannel(e);e=[e]}if(0===e.length)throw new YL(wN.INVALID_PARAMS,"param list is empty");const n=e;if("audience"===this._gateway.role)throw new YL(wN.INVALID_OPERATION,"audience can not publish stream");for(const e of n){if(!(e instanceof Zk))throw new YL(wN.INVALID_PARAMS,"parameter is not local track");if(!e._enabled&&t)throw new YL(wN.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(e.getTrackId()))}SL.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(n.map((e=>"".concat(e.getTrackId()," ")))));const i=await this._publishMutex.lock();await this._configDistribute.awaitConfigDistributeComplete(),t&&n.forEach((e=>{const t=this._configDistribute.getBitrateLimit();e instanceof TV&&t&&e.setBitrateLimit(t.uplink)}));try{await this._publishHighStream(n),SL.info("[".concat(this._clientId,"] Publish success, id ").concat(n.map((e=>"".concat(e.getTrackId()," ")))))}catch(e){throw SL.error("[".concat(this._clientId,"] publish error"),e.toString()),e}finally{i()}}async _publishDataChannel(e){if(null==e)throw new YL(wN.INVALID_PARAMS,"parameter is not local track or datachannel config, config is ".concat(JSON.stringify(e)));PN(e.id,"id",0,65535,!0),NN(e.ordered,"ordered"),kN(e.metadata,"metadata",0,512),SL.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(e.id));const t=await this._publishMutex.lock();try{if(-1!==this._p2pChannel.getAllDataChannels().findIndex((t=>t.id===e.id)))throw new YL(wN.INVALID_PARAMS,"Invalid id: ".concat(e.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||void 0===this._uid)throw new YL(wN.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&xP("FORCE_TURN")&&!xP("TURN_ENABLE_TCP")&&!xP("TURN_ENABLE_UDP"))throw new YL(wN.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const n=function(e){return gee(e,!1)}(e),i=await this._p2pChannel.publishDataChannel([n]);if(i.length>0){if("number"!=typeof n._originDataChannelId)throw SL.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new YL(wN.CREATE_DATACHANNEL_ERROR);try{await cp.all(i.map((e=>this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)))),await n._waitTillOpen()}catch(e){if(e.code!==wN.DISCONNECT_P2P)throw e}}return SL.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(n.id)),n}catch(e){throw SL.error("[".concat(this._clientId,"] publish datachannels error"),e.toString()),e}finally{t()}}async unpublish(e){if(!this._joinInfo||void 0===this._uid)throw new YL(wN.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let t=[];if(e)if(Array.isArray(e))t=e;else{if(!(e instanceof Zk))return this._unpublishDataChannel([e]);t=[e]}else this.store.useP2P||await this._unpublishDataChannel(),t=this._p2pChannel.getAllTracks(!0);SL.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(t.map((e=>"".concat(e.getTrackId()," ")))," "));const n=await this._publishMutex.lock();try{if(this.store.useP2P){const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.sendExtensionMessage(QF.UNPUBLISH,{unpubMsg:e},!0)}else{const e=await this._p2pChannel.unpublish(t);e&&await this._gateway.unpublish(e,this._uid),SL.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(t.map((e=>"".concat(e.getTrackId())))))}}catch(e){throw SL.error("[".concat(this._clientId,"] unpublish error"),e.toString()),e}finally{n&&n()}}async _unpublishDataChannel(e){void 0!==e&&0!==e.length||(e=this._p2pChannel.getAllDataChannels()),SL.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(e.map((e=>"".concat(e.id," ")))," "));const t=await this._publishMutex.lock();try{const n=await this._p2pChannel.unpublishDataChannel(e);n&&await this._gateway.unpublishDataChannel(n),SL.info("[".concat(this._clientId,"] Unpublish dataChannel success, dataChannel ids: ").concat(e.map((e=>"".concat(e.id)))))}catch(e){throw SL.error("[".concat(this._clientId,"] unpublish dataChannel error"),e.toString()),e}finally{t&&t()}}async subscribe(e,t,n){if(!(e instanceof Wte)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new YL(wN.INVALID_REMOTE_USER,"user is not in the channel");e=t}return"datachannel"===t?this._subscribeDataChannel(e,n):this._subscribe(e,t)}async presubscribe(e,t){if(DN(t,"mediaType",["audio","video"]),this.store.useP2P)throw new YL(wN.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"can't presub when not join");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const n=t===UF.AUDIO,i=t===UF.VIDEO,r=await this._subscribeMutex.lock();try{const o=await this._gateway.presubscribe(e,t,!0),s=o.ssrcId,a=o.ortc,c=o.rtxSsrcId,d=o.cname,l=o.uint_id;if(null==s)throw new YL(wN.UNEXPECTED_RESPONSE,"no ssrc id");let u=this._users.find((t=>t.uid===e));u||(u=new Wte(e,l||e),u._is_pre_created=!0,this._users.push(u)),d&&(u._cname=d),u._uintid||(u._uintid=l||e),n&&(u._audioSSRC=s,u._audio_pre_subscribed=!0,a&&(u._audioOrtc=a)),i&&(u._videoSSRC=s,u._video_pre_subscribed=!0,a&&(u._videoOrtc=a),null!=c&&(u._rtxSsrcId=c)),SL.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(s)),await this._p2pChannel.subscribe(u,t,s,c,a);const h=n?u._audioTrack:u._videoTrack;if(!h)throw new YL(wN.UNEXPECTED_ERROR,"can not find remote track in user");return n&&(u._trust_audio_stream_added_state_=!0,u._audio_added_=!0),i&&(u._trust_video_stream_added_state_=!0,u._video_added_=!0),h}catch(t){throw SL.error("[".concat(this._clientId,"] presub user ").concat(e," error"),t),t}finally{r()}}async _subscribeDataChannel(e,t){var n;if(PN(t,"channelId",0,65535,!0),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i)throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),new YL(wN.INVALID_REMOTE_USER,"user is not in the channel");if(!e.hasAudio&&!e.hasVideo&&0===e._dataChannels.length)throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),new YL(wN.INVALID_REMOTE_USER,"user is not published");const r=null===(n=e._dataChannels)||void 0===n?void 0:n.find((e=>e.id===t));if(!r)throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, remote datachannel is not published")),new YL(wN.REMOTE_USER_IS_NOT_PUBLISHED);const o=await this._subscribeMutex.lock();SL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: datachannel"));try{const t=await this._p2pChannel.subscribeDataChannel(e,[r]);if(t&&Ui(t).call(t,r.id))try{var s;if("number"!=typeof r._originDataChannelId)throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType datachannel, cannot get RTCDatachannel")),new YL(wN.CREATE_DATACHANNEL_ERROR);const t={id:r.id,datachannelId:r._originDataChannelId,ordered:r.ordered,maxRetransmits:r.maxRetransmits,metadata:null!==(s=r.metadata)&&void 0!==s?s:""};await this._gateway.subscribeDataChannel(e.uid,t,!0),await r._waitTillOpen()}catch(t){if((null==t?void 0:t.code)!==wN.WS_ABORT)throw await this._p2pChannel.unsubscribeDataChannel(e,[r]),t;await this._p2pChannel.unsubscribeDataChannel(e,[r]),this._p2pChannel.setPendingRemoteDataChannel(e,r.id)}return SL.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: datachannel")),r}finally{o()}}async _p2pSubscribe(e,t,n){if(DN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i){const t=new YL(wN.INVALID_REMOTE_USER,"user is not in the channel");throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new YL(wN.INVALID_REMOTE_USER,"user is not published");throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!n&&("audio"===t&&!e.hasAudio||"video"===t&&!e.hasVideo)){const n=new YL(wN.REMOTE_USER_IS_NOT_PUBLISHED);throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),n}const r=await this._subscribeMutex.lock();SL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const n="audio"===t?e._audioSSRC:e._videoSSRC,i="audio"===t?e._audioMid:e._videoMid;this.store.subscribe(e.uid,t,Date.now()),this.store.useP2P&&await this._p2pChannel.subscribe(e,t,n,i)}catch(e){throw e}SL.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{SL.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const n="audio"===t?e._audioTrack:e._videoTrack;if(!n)throw new YL(wN.UNEXPECTED_ERROR,"can not find remote track in user object");return n}catch(t){throw SL.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{r()}}async _subscribe(e,t,n){if(this.store.useP2P)return this._p2pSubscribe(e,t);if(DN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const i=this._users.find((t=>t===e));if(!i){const t=new YL(wN.INVALID_REMOTE_USER,"user is not in the channel");throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", this user is not in the channel")),t}if(!e.hasAudio&&!e.hasVideo){const t=new YL(wN.INVALID_REMOTE_USER,"user is not published");throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid,", user is not published")),t}if(!(n||("audio"!==t||e.hasAudio&&void 0!==e._audioSSRC)&&("video"!==t||e.hasVideo&&void 0!==e._videoSSRC))){const n=new YL(wN.REMOTE_USER_IS_NOT_PUBLISHED);throw SL.error("[".concat(this._clientId,"] can not subscribe ").concat(e.uid," with mediaType ").concat(t,", remote track is not published")),n}let r="audio"===t?e._audioSSRC:e._videoSSRC,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?UF.AUDIO:UF.VIDEO,ssrcId:r};"video"===t&&this.store.firstVideoFrameDecoded(e.uid,{subscribeStart:Date.now()});const c=await this._subscribeMutex.lock();SL.info("[".concat(this._clientId,"] subscribe user ").concat(e.uid,", mediaType: ").concat(t));try{if(await this._p2pChannel.hasRemoteMediaWithLock(e,t))await this._p2pChannel.unmuteRemote(e,t);else try{const n="audio"===t?e._audioSSRC:e._videoSSRC;void 0!==n&&n!==r&&(r=n,o="audio"===t?e._audioOrtc:e._videoOrtc,s="video"===t?e._rtxSsrcId:void 0,a={stream_type:"audio"===t?UF.AUDIO:UF.VIDEO,ssrcId:r}),Vte.markSubscribeStart(this.store.clientId,r),this.store.subscribe(e.uid,t,Date.now()),await this._p2pChannel.subscribe(e,t,r,s,o);try{this._p2pChannel.isPreSubScribe(r)||await this._gateway.subscribe(e.uid,a,!0)}catch(n){if((null==n?void 0:n.code)!==wN.WS_ABORT)throw await this._p2pChannel.unsubscribe(e,t),n;await this._p2pChannel.unsubscribe(e,t,!0),this._p2pChannel.setPendingRemoteMedia(e,t)}this.store.subscribe(e.uid,t,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,e,t)}catch(n){throw this._p2pChannel.reportSubscribeEvent(!1,null==n?void 0:n.code,e,t),n}SL.info("[".concat(this._clientId,"] subscribe success user ").concat(e.uid,", mediaType: ").concat(t)),void 0!==this._defaultStreamFallbackType&&this.setStreamFallbackOption(e.uid,this._defaultStreamFallbackType).catch((e=>{SL.warning("[".concat(this._clientId,"] auto set fallback failed"),e)}));const n="audio"===t?e._audioTrack:e._videoTrack;if(this.store.aiClientMode&&"audio"===t&&n&&(n.play=()=>{Ree.play()},n.stop=()=>{Ree.stop()}),!n)throw new YL(wN.UNEXPECTED_ERROR,"can not find remote track in user object");return"video"===t&&(this.store.firstVideoFrameDecoded(e.uid,{subscribeEnd:Date.now()}),this._p2pChannel.reportVideoFirstFrameRender(e)),n}catch(t){throw SL.error("[".concat(this._clientId,"] subscribe user ").concat(e.uid," error"),t),t}finally{c()}}async massSubscribe(e){if(MN(e,"subscribeList"),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"Can't subscribe stream, not joined");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const t=Date.now(),n=new Map,i=await this._subscribeMutex.lock();SL.info("[".concat(this._clientId,"]start massSubscribe user ").concat(e.map((e=>{let t=e.user,n=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n)})).join("; ")));const r=(e=[...e]).map((e=>({user:e.user,mediaType:e.mediaType}))),o=await this._p2pChannel.globalLock();try{var s;for(let t=e.length-1;t>=0;t--){const i=e[t],o=i.user,s=i.mediaType;if(DN(s,"mediaType",["audio","video"]),!o){const e=new YL(wN.INVALID_PARAMS,"user property does not exist in subscribeList item");throw SL.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),e}const a=this._users.find((e=>e===o));if(!a){const n=new YL(wN.INVALID_REMOTE_USER,"user is not in the channel");SL.error("[".concat(this._clientId,"] can not massSubscribe ").concat(o.uid,", this user is not in the channel")),r[t].error=n,e.splice(t,1);continue}if("audio"===s&&(!o.hasAudio||void 0===o._audioSSRC)||"video"===s&&(!o.hasVideo||void 0===o._videoSSRC)){const n=new YL(wN.REMOTE_USER_IS_NOT_PUBLISHED);SL.error("[".concat(this._clientId,"] can not subscribe ").concat(o.uid," with mediaType ").concat(s,", remote user is not published")),r[t].error=n,e.splice(t,1);continue}const c=AF.Video|AF.LowVideo,d=n.get(o);if(d){if("video"===s?d&c:d&AF.Audio){e.splice(t,1),SL.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(o.uid,", mediaType:").concat(s," twice"));continue}n.set(o,d|("video"===s?c:AF.Audio))}else n.set(o,"video"===s?c:AF.Audio)}for(let t=e.length-1;t>=0;t--){const i=e[t],r=i.user,o=i.mediaType,s=AF.Video|AF.LowVideo;if(this._p2pChannel.hasRemoteMedia(r,o)){await this._p2pChannel.unmuteRemoteNoLock(r,o);const i=n.get(r);n.set(r,"video"===o?i^s:i^AF.Audio),e.splice(t,1)}}this.store.massSubscribe(e.map((e=>({userId:e.user.uid,type:e.mediaType}))),t);let a=sr(s=Array.from(n.entries())).call(s,((e,t)=>{let n=KC(t,2),i=n[0],r=n[1];if(0===r)return e;const o={stream_id:i.uid,stream_type:r};return r&AF.Audio&&(o.audio_ssrc=i._audioSSRC),r&AF.Video&&(o.video_ssrc=i._videoSSRC),e.push(o),e}),[]);try{e.length>0&&await this._p2pChannel.massSubscribeNoLock(e.map((e=>{let t=e.user,n=e.mediaType;return{user:t,mediaType:n,ssrcId:n===UF.VIDEO?t._videoSSRC:t._audioSSRC,rtxSsrcId:n===UF.VIDEO?t._rtxSsrcId:void 0}})));const n=new Map;if(a=a.filter((e=>e.video_ssrc&&!this._p2pChannel.isPreSubScribe(e.video_ssrc)||e.audio_ssrc&&!this._p2pChannel.isPreSubScribe(e.audio_ssrc)||!e.video_ssrc&&!e.audio_ssrc)),a.length>0){const e=await this._gateway.subscribeAll(a,!0);((null==e?void 0:e.users)||[]).forEach((e=>{let t=e.stream_id,i=e.video_error_code,r=e.audio_error_code,o=e.error_code;(i||r||o)&&n.set(t,{video_error_code:i,audio_error_code:r,error_code:o})}))}if(Array.from(n.entries()).length>0){const e=[];Array.from(n.entries()).forEach((t=>{let n=KC(t,2),i=n[0],r=n[1];const o=this.remoteUsers.find((e=>e.uid===i));if(o){let t;r.error_code||r.video_error_code&&r.audio_error_code?t=void 0:r.video_error_code?t=UF.VIDEO:r.audio_error_code&&(t=UF.AUDIO),e.push({user:o,mediaType:t})}})),e.length>0&&await this._p2pChannel.massUnsubscribeNoLock(e)}for(const e of r){const t=n.get(e.user.uid);if(t){const n=t.error_code||"audio"===e.mediaType&&t.audio_error_code||"video"===e.mediaType&&t.video_error_code;if(n){const t=oB(n);SL.error("user:".concat(e.user.uid," mediaType:").concat(e.mediaType," has massSubscribe error ").concat(t.desc)),e.error=new YL(wN.SUBSCRIBE_FAILED,"code ".concat(n,": ").concat(t.desc))}}e.error||("video"===e.mediaType?e.track=e.user.videoTrack:e.track=e.user.audioTrack)}return this.store.massSubscribe(r.filter((e=>!e.error)).map((e=>({userId:e.user.uid,type:e.mediaType}))),void 0,Date.now()),r.forEach((e=>{var n;HL.subscribe(this.store.sessionId,{succ:!!e.error,ec:(null===(n=e.error)||void 0===n?void 0:n.code)||null,video:e.mediaType===UF.VIDEO,audio:e.mediaType===UF.AUDIO,peerid:e.user.uid,subscribeRequestid:e.mediaType===UF.VIDEO?e.user._videoSSRC:e.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-t),preSsrc:this._p2pChannel.isPreSubScribe(e.user._videoSSRC)},!0)})),SL.info("[".concat(this._clientId,"] massSubscribe success ").concat(e.map((e=>{let t=e.user,n=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n)})).join("; "))),r}catch(t){throw await this._p2pChannel.massUnsubscribeNoLock(e),t}}finally{o(),i()}}async unsubscribe(e,t,n){if(!(e instanceof Wte)){const t=this.remoteUsers.find((t=>t.uid===e));if(!t)throw new YL(wN.INVALID_REMOTE_USER,"user is not in the channel");e=t}if(t||this.store.useP2P){if("datachannel"===t)return this._unsubscribeDataChannel(e,n)}else await this._unsubscribeDataChannel(e,n);if(t&&DN(t,"mediaType",["audio","video"]),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");const i=this._users.find((t=>t===e));if(!i){const t=new YL(wN.INVALID_REMOTE_USER,"user is not in the channel");throw SL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}SL.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: ").concat(t));const r=await this._subscribeMutex.lock();try{if(this.store.useP2P)await this._p2pChannel.unsubscribe(e,t);else{const n=await this._p2pChannel.unsubscribe(e,t);n&&await this._gateway.unsubscribe(n,e.uid),t&&"audio"!==t||(e._audio_pre_subscribed=!1),t&&"video"!==t||(e._video_pre_subscribed=!1),e._is_pre_created&&SD(this._users,e),SL.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(e.uid,", mediaType: ").concat(t))}}catch(t){if(t.code===wN.DISCONNECT_P2P)return void SL.warning("disconnecting p2p, abort unsubscribe request.");throw SL.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}finally{r()}}async _unsubscribeDataChannel(e,t){if(t&&PN(t,"id",0,65535,!0),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");const n=this._users.find((t=>t===e));if(!n){const t=new YL(wN.INVALID_REMOTE_USER,"user is not in the channel");throw SL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid,", user is not in the channel")),t}let i;if("number"==typeof t){const n=e._dataChannels.find((e=>e.id===t));n&&(i=[n])}else i=e._dataChannels;if(void 0===i){const n=new YL(wN.REMOTE_USER_IS_NOT_PUBLISHED);throw SL.error("[".concat(this._clientId,"] can not unsubscribe ").concat(e.uid," with channelId ").concat(t,", remote datachannel is not published")),n}SL.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(i.map((e=>e.id))));try{const t=await this._p2pChannel.unsubscribeDataChannel(e,i);t&&await this._gateway.unsubscribeDataChannel(t,e.uid),SL.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(e.uid,", mediaType: datachannel, ids: ").concat(t))}catch(t){if(t.code===wN.DISCONNECT_P2P)return void SL.warning("disconnecting p2p, abort unsubscribe request.");throw SL.error("[".concat(this._clientId,"] unsubscribe user ").concat(e.uid," error"),t.toString()),t}}async massUnsubscribe(e){if(MN(e,"unsubscribeList"),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");SL.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(e.map((e=>{let t=e.user,n=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n,";")})).join())),e=[...e];const t=new Map;for(let n=e.length-1;n>=0;n--){const i=e[n],r=i.user,o=i.mediaType;if(!r){const e=new YL(wN.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw SL.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),e}DN(o,"mediaType",["video","audio",void 0]);const s=this._users.find((e=>e===r));if(!s){SL.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(r.uid,", user is not in the channel")),e.splice(n,1);continue}const a=AF.Video|AF.LowVideo;if(t.has(r)){const i=t.get(r);let s;switch(o){case"video":s=i&a;break;case"audio":s=i&AF.Audio;break;default:s=i&(AF.Audio|a)}if(s){SL.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(r.uid,",mediaType:").concat(o," twice.")),e.splice(n,1);continue}o?"audio"===o?t.set(r,i|AF.Audio):"video"===o&&t.set(r,i|a):t.set(r,i|AF.Audio|a)}else o?"audio"===o?t.set(r,AF.Audio):"video"===o&&t.set(r,a):t.set(r,AF.Audio|a)}try{const t=await this._p2pChannel.massUnsubscribe(e);t&&await this._gateway.massUnsubscribe(t),SL.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(e.map((e=>{let t=e.user,n=e.mediaType;return"user: ".concat(null==t?void 0:t.uid,", mediaType: ").concat(n,";")})).join()))}catch(e){if(e.code===wN.DISCONNECT_P2P)return void SL.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw SL.error("[".concat(this._clientId,"] massUnsubscribe error"),e.toString()),e}}async setLowStreamParameter(e){!function(e){if(!e)throw new ON(wN.INVALID_PARAMS);UN(e.width)||LN(e.width,"streamParameter.width"),UN(e.height)||LN(e.height,"streamParameter.height"),UN(e.framerate)||LN(e.framerate,"streamParameter.framerate"),UN(e.bitrate)||PN(e.bitrate,"streamParameter.bitrate")}(e),(!e.width&&e.height||e.width&&!e.height)&&SL.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),SL.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(e));const t=this._configDistribute.getLowStreamConfigDistribute();if(t&&t.bitrate&&e.bitrate&&t.bitrate<e.bitrate&&(e.bitrate=t.bitrate),this._lowStreamParameter=e,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(e,BF.LocalVideoLowTrack)}async setDualStreamMode(e,t){DN(e,"mode",[0,1,-1]);try{switch(t&&await this.setLowStreamParameter(t),this._dualStreamMode=e,this._joinInfo?this._gateway.setDualStreamMode(e).catch((e=>{SL.warning("[".concat(this._clientId,"] set dual stream mode failed"),e.toString())})):SL.debug("[".concat(this._clientId,"] haven't joined yet, cache dual stream mode ").concat(e)),e){case nD.AUTO_SIMULCAST_STREAM:SL.info("[".concat(this._clientId,"] set dual stream mode to ").concat(e));break;case nD.DISABLE_SIMULCAST_STREM:return this.disableDualStream();case nD.ENABLE_SIMULCAST_STREAM:return this.enableDualStream()}}catch(e){throw SL.error("[".concat(this._clientId,"] set dual stream mode error"),e.toString()),e}}async enableDualStream(){if(!JL().supportDualStream)throw HL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new YL(wN.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new YL(wN.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{await this._publishLowStream()}catch(e){throw HL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),e}this._isDualStreamEnabled=!0,this._dualStreamMode=nD.ENABLE_SIMULCAST_STREAM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{SL.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),HL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),SL.info("[".concat(this._clientId,"] enable dual stream"))}async disableDualStream(){if(this._isDualStreamEnabled){if(!this._joinInfo)return this._isDualStreamEnabled=!1,void SL.info("[".concat(this._clientId,"] disable dual stream before join"));if(this._p2pChannel.getLocalMedia(BF.LocalVideoLowTrack))try{const e=await this._p2pChannel.unpublishLowStream();e&&await this._gateway.unpublish(e,this._joinInfo.stringUid||this._joinInfo.uid)}catch(e){throw HL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),e}this._isDualStreamEnabled=!1,this._dualStreamMode=nD.DISABLE_SIMULCAST_STREM,this._joinInfo&&this._gateway.setDualStreamMode(this._dualStreamMode,!0,!0).catch((e=>{SL.debug("[".concat(this._clientId,"] try to inform gateway to set dual stream mode to ").concat(this._dualStreamMode," ,but failed"),e.toString())})),HL.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),SL.info("[".concat(this._clientId,"] disable dual stream"))}}async setClientRole(e,t){if(function(e){DN(e,"role",["audience","host"])}(e),t&&iD(t),"rtc"===this.mode||"p2p"===this.mode)throw SL.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new YL(wN.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(t&&t.level&&"host"===e)throw new YL(wN.INVALID_OPERATION,"host mode can not set audience latency level");if("audience"===e&&this._p2pChannel.hasLocalMedia())throw new YL(wN.INVALID_OPERATION,"can not set client role to audience when publishing stream");const n=this._config.role;if(this._joinInfo&&(this._joinInfo.role=e),e!==n&&xP("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(e,t),this._config.role=e,this._gateway.reconnect("recover",sD.REGIONAL_DISTRIBUTION)):(await this._gateway.setClientRole(e,t),this._config.role=e),SL.info("[".concat(this._clientId,"] set client role to ").concat(e,", level: ").concat(t&&t.level)),"audience"===n&&"audience"!==e&&this._pendingRtpCapabilityChange&&this._p2pChannel instanceof die){const e=this._pendingRtpCapabilityChange.video_codec;this._p2pChannel.updateRemoteRTPCapabilities(e.map((e=>e.toLowerCase())).filter((e=>{var t;return Ui(t=Object.keys(GP)).call(t,e)})))}}async _setClientRoleOptions(e){if("rtc"===this.mode||"p2p"===this.mode)return;if("audience"!==this._config.role||this._p2pChannel.hasLocalMedia())return;let t=!1;try{e&&iD(e),await this._gateway.setClientRole(this._config.role,e),t=!0}catch(e){}finally{SL.info("[".concat(this._clientId,"] set client role options ").concat(t?"succeed":"failed",", options is ").concat(e))}}getRemoteInboundOffset(){var e;const t=null===(e=this._p2pChannel.getStats())||void 0===e?void 0:e.audioSend[0];if(!t||!t.timestamp)return 0;const n=t.timestamp-Date.now();return Math.abs(n)>1e3+t.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?n:0}getNtpWallTimeInMs(){return"visible"===document.visibilityState&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(e,t){if(kN(e,"proxyServer"),!t){if("DISCONNECTED"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"Set proxy server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new YL(wN.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=e,HL.setProxyServer(this._proxyServer),SL.setProxyServer(this._proxyServer),SL.info("[".concat(this._clientId,"] Set proxy server ").concat(t?"by initialize call":""," success."))}setTurnServer(e,t){if(Array.isArray(e)||(e=[e]),!t){if("DISCONNECTED"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"Set turn server before join channel");if("disabled"!==this._cloudProxyServerMode||this._useLocalAccessPoint)throw new YL(wN.INVALID_OPERATION,"You have already set the proxy")}if(eD(e))return this._turnServer={servers:e,mode:"original-manual"},void SL.info("[".concat(this._clientId,"] Set original turnserver ").concat(t?"by initialize call":""," success: ").concat(e.map((e=>e.urls)).join(","),"."));e.forEach((e=>tD(e))),this._turnServer={servers:e,mode:"manual"},SL.info("[".concat(this._clientId,"] Set turnserver ").concat(t?"by initialize call":""," success."))}setLicense(e){if("DISCONNECTED"!==this.connectionState){throw new YL(wN.INVALID_OPERATION,"you should set license before join channel")}if(kN(e,"license",32,32),!/^[A-Za-z\d]+$/.test(e))throw new YL(wN.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=e,SL.info("[".concat(this._clientId,"] set license success"),e)}startProxyServer(e){if("DISCONNECTED"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||"manual"===this._turnServer.mode||this._useLocalAccessPoint)throw new YL(wN.INVALID_OPERATION,"You have already set the proxy");const t=[3,4,5];let n;switch(void 0===e&&(e=3),e){case 1:case 2:throw new YL(wN.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:n="proxy3";break;case 4:n="proxy4";break;case 5:n="proxy5";break;default:throw new YL(wN.INVALID_PARAMS,"proxy server mode must be ".concat(t.join("|")))}this._cloudProxyServerMode=n,this.store.cloudProxyServerMode=n,SL.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if("DISCONNECTED"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"Stop proxy server after leave channel");HL.setProxyServer(),SL.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",SL.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(e){if(!e.accessPoints)throw new YL(wN.INVALID_PARAMS,"accessPoints is required.");MN(e.accessPoints.serverList,"accessPoints.serverList"),kN(e.accessPoints.domain,"accessPoints.domain");const t=(e,t)=>{PN(e,t,0,65535,!0)};let n=443;if(e.accessPoints.port&&(t(e.accessPoints.port,"accessPoints.port"),n=e.accessPoints.port),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new YL(wN.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");xP("CLOSE_AFB_FOR_LOCAL_AP")&&(VP("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),VP("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const i=/^((\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,r=e.accessPoints.domain,o=e.accessPoints.serverList.map((e=>i.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(r):e)),s=o.map((e=>"".concat(e,":").concat(n)));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,VP("WEBCS_DOMAIN",s),VP("WEBCS_DOMAIN_BACKUP_LIST",s),VP("GATEWAY_DOMAINS",[r]),e.report&&e.report.hostname&&Array.isArray(e.report.hostname)&&e.report.hostname.length?(MN(e.report.hostname,"report.hostname"),VP("EVENT_REPORT_DOMAIN",e.report.hostname[0]),VP("EVENT_REPORT_BACKUP_DOMAIN",e.report.hostname[1]||e.report.hostname[0])):(VP("EVENT_REPORT_DOMAIN",o[0]),VP("EVENT_REPORT_BACKUP_DOMAIN",o[1]||o[0]));let a=6443;e.report&&e.report.port&&(t(e.report.port,"report.port"),a=e.report.port),VP("STATS_COLLECTOR_PORT",a),e.report?VP("ENABLE_EVENT_REPORT",!0):VP("ENABLE_EVENT_REPORT",!1);let c="";e.log&&e.log.hostname&&Array.isArray(e.log.hostname)&&e.log.hostname.length?(MN(e.log.hostname,"log.hostname"),c=e.log.hostname[0]):c=o[0];let d=6444;e.log&&e.log.port&&(t(e.log.port,"log.port"),d=e.log.port),VP("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];e.cds&&e.cds.hostname&&Array.isArray(e.cds.hostname)&&e.cds.hostname.length?(MN(e.cds.hostname,"cds.hostname"),l=e.cds.hostname):l=o;let u=443;e.cds&&e.cds.port&&(t(e.cds.port,"cds.port"),u=e.cds.port),VP("CDS_AP",l.map((e=>"".concat(e,":").concat(u)))),e.cds?VP("ENABLE_CONFIG_DISTRIBUTE",!0):VP("ENABLE_CONFIG_DISTRIBUTE",!1),SL.info("set local access point v2 success")}setLocalAccessPoints(e,t){if(MN(e,"serverList"),kN(t,"domain"),this._proxyServer||"disabled"!==this._cloudProxyServerMode)throw new YL(wN.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const n=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;e=e.map((e=>n.test(e)?"".concat(e.replace(/\./g,"-"),".").concat(t):e)),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,VP("WEBCS_DOMAIN",e),VP("WEBCS_DOMAIN_BACKUP_LIST",e),VP("GATEWAY_DOMAINS",[t]),VP("EVENT_REPORT_DOMAIN",e[0]),VP("EVENT_REPORT_BACKUP_DOMAIN",e[1]||e[0]),VP("LOG_UPLOAD_SERVER","".concat(e[0],":6444")),SL.info("[".concat(this._clientId,"] set local access point success"))}async setRemoteDefaultVideoStreamType(e){if(DN(e,"streamType",[0,1,4,5,6,7,8,9]),this._remoteDefaultVideoStreamType=e,this._joinInfo)try{await this._gateway.setDefaultRemoteVideoStreamType(e),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw SL.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else SL.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(e))}async setRemoteVideoStreamType(e,t){DN(t,"streamType",[0,1,4,5,6,7,8,9]);try{await this._gateway.setRemoteVideoStreamType(e,t),setTimeout((()=>{const t=this._users.find((t=>t.uid===e));t&&t.videoTrack&&t.videoTrack.updateMediaStreamTrackResolution()}),2e3)}catch(e){throw SL.error("[".concat(this._clientId,"] set remote video stream type error"),e.toString()),e}SL.info("[".concat(this._clientId,"] set remote ").concat(e," video stream type to ").concat(t)),this._remoteStreamTypeCacheMap.set(e,t)}async setStreamFallbackOption(e,t){DN(t,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{await this._gateway.setStreamFallbackOption(e,t)}catch(e){throw SL.error("[".concat(this._clientId,"] set stream fallback option"),e.toString()),e}SL.info("[".concat(this._clientId,"] set remote ").concat(e," stream fallback type to ").concat(t)),this._streamFallbackTypeCacheMap.set(e,t)}setEncryptionConfig(e,t,n,i){!function(e){DN(e,"encryptionMode",["aes-128-xts","aes-256-xts","aes-128-ecb","sm4-128-ecb","aes-128-gcm","aes-256-gcm","aes-128-gcm2","aes-256-gcm2","none"])}(e),kN(t,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(Ui(r).call(r,e)){if(!n||!(n instanceof Uint8Array&&32===n.length))throw new YL(wN.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(n)throw new YL(wN.INVALID_PARAMS,"current encrypt mode does not need salt");if(i){if(NN(i,"encryptDataStream"),!Ui(r).call(r,e))throw new YL(wN.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'\"|{}\\[\\]])(?=.{8,})").test(t)||SL.warning("The secret is not strong:\n      The secret must contain at least 1 lowercase alphabetical character,\n      The secret must contain at least 1 uppercase alphabetical character,\n      The secret must contain at least 1 numeric character,\n      The secret must contain at least one special character,\n      The secret must be eight characters or longer.\n      "),this._encryptionMode=e,this._encryptionSecret=t,n&&(this._encryptionSalt=AD(n))}async renewToken(e){if(kN(e,"token",1,2047),!this._key||!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"renewToken should not be called before user join");const t=this._key;this._key=e,this._joinInfo&&(this._joinInfo.token=e);const n=await this._renewTokenMutex.lock();try{if(xP("USE_NEW_TOKEN")){SL.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const t=await gte(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ZD);SL.debug("[".concat(this._clientId,"] get ticket from unilbs success")),await this._gateway.renewToken({token:e,ticket:t})}else SL.debug("[".concat(this._clientId,"] start renew token without ticket")),await this._gateway.renewToken({token:e});SL.debug("[".concat(this._clientId,"] renewToken success"))}catch(e){throw this._key=t,this._joinInfo.token=t,SL.error("[".concat(this._clientId,"] renewToken failed"),e.toString()),e}finally{n()}}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?SL.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval((()=>{const e=this._p2pChannel.getAudioLevels();this.safeEmit(rD.VOLUME_INDICATOR,e)}),xP("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const e=this._statsCollector.getRTCStats(),t=this._gateway.getInChannelInfo();return e.Duration=Math.round(t.duration/1e3),e}async startLiveStreaming(e,t){if(!t){if("h264"!==this.codec)throw new YL(wN.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new YL(wN.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(e)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(e))throw new YL(wN.LIVE_STREAMING_TASK_CONFLICT);const n=t?uF.TRANSCODE:uF.RAW;return this._createLiveStreamingClient(n).startLiveStreamingTask(e,n)}setLiveTranscoding(e){return this._createLiveStreamingClient(uF.TRANSCODE).setTranscodingConfig(e)}async stopLiveStreaming(e){const t=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter((t=>t&&t.hasUrl(e)));if(!t.length)throw new YL(wN.INVALID_PARAMS,"can not find live streaming url to stop");await cp.all(t.map((t=>t&&t.stopLiveStreamingTask(e))))}async startChannelMediaRelay(e){Gte(e);const t=this._createChannelMediaRelayClient();await t.startChannelMediaRelay(e)}async updateChannelMediaRelay(e){Gte(e);const t=this._createChannelMediaRelayClient();await t.updateChannelMediaRelay(e)}async stopChannelMediaRelay(){const e=this._createChannelMediaRelayClient();await e.stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)}sendAudioMetadata(e){this._p2pChannel instanceof die&&this._p2pChannel.addAudioMetadata(e)}async sendStreamMessage(e){var t;let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"can not send data stream, not joined");if(("string"==typeof e||e instanceof Uint8Array)&&(e={payload:e}),"string"==typeof e.payload){const t=new TextEncoder;e.payload=t.encode(e.payload)}let i=!1;this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Ui(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)&&(i=!0,e.payload=await async function(e,t,n){var i;const r=sr(i=Array.from(n)).call(i,((e,t)=>e+t),0),o={serverTs:0,seq:XP++,length:n.length,checkSum:r},s=new Uint8Array(jD(r,2)),a=new ArrayBuffer(YP),c=new DataView(a);c.setUint32(0,o.serverTs),c.setUint16(4,o.seq),c.setUint16(6,o.length),c.setUint16(8,o.checkSum);const d=16-n.length%16;n=OD(n,new Uint8Array(d));const l=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:WP,additionalData:s},t,n);return OD(new Uint8Array(a),new Uint8Array(l))}(this._encryptDataStreamIv,this._encryptDataStreamKey,e.payload));if(new Blob([e.payload]).size>1024)throw new YL(wN.INVALID_PARAMS,i?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(rF.DATA_STREAM,{payload:AD(e.payload),syncWithAudio:e.syncWithAudio,sendTs:Date.now()-gie},!n)}sendMetadata(e){if(!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([e]).size>1024)throw new YL(wN.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(rF.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:AD(e)})}async sendCustomReportMessage(e){if(Array.isArray(e)||(e=[e]),e.forEach(RL),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"can not send custom report, not joined");await HL.sendCustomReportMessage(this._joinInfo.sid,e)}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){const e=this._statsCollector.getRemoteNetworkQualityStats();if(xP("DELETE_NEQ_AFTER_USER_LEAVE")){const t=this._users.map((e=>e.uid+""));Object.keys(e).forEach((n=>{Ui(t).call(t,n)||delete e[n]}))}return e}getNetworkQuality(){return this._statsCollector.getNetworkQuality()}async pickSVCLayer(e,t){DN(t.spatialLayer,"spatialLayer",[0,1,2,3]),DN(t.temporalLayer,"temporalLayer",[0,1,2,3]);try{await this._gateway.pickSVCLayer(e,t)}catch(e){throw SL.error("[".concat(this._clientId,"] pick SVC layer failed"),e.toString()),e}}async setRTMConfig(e){const t=e.apRTM,n=void 0!==t&&t,i=e.rtmFlag;if(NN(n,"apRTM"),PN(i,"rtmFlag",0),this._rtmConfig.apRTM=n,this._rtmConfig.rtmFlag=i,SL.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(e)," in ").concat(this.connectionState," state")),("CONNECTED"===this.connectionState||"RECONNECTING"===this.connectionState)&&this._joinInfo)return this._joinInfo.apRTM=n,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i)}_reset(){if(SL.debug("[".concat(this._clientId,"] reset client")),function(e){const t=Dx.indexOf(e);-1!==t&&Dx.splice(t,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this.store.flexiblePC=!1,this.store.autoSubscribe=!1,this.store.autoReceiveAndPlayAudio=!1,this._pendingRtpCapabilityChange=void 0,this._earlyJoinAttempt=void 0,this._axiosCancelSource.cancel(),this._axiosCancelSource=DO.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&Yie(this._joinInfo),this._rteDetailInterval&&(window.clearInterval(this._rteDetailInterval),this._rteDetailInterval=void 0,this._sessionId&&HL.reportRteDetail(this._sessionId)),this._fallbackServerInfo=void 0,this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&HL.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,this.store.resetFirstVideoFrameDecoded(),this._statsCollector.reset(),this._key=void 0,this._appId=void 0,this._uid=void 0,this.store.uid=void 0,this._channelName=void 0,this._encryptionMode="none",this._encryptionSecret=null,this._encryptionSalt=null,this._encryptDataStreamKey=null,this._encryptDataStreamIv=null,this._pendingPublishedUsers=[],this._users.forEach((e=>{e._audioTrack&&e._audioTrack._destroy(),e._videoTrack&&e._videoTrack._destroy(),e._dataChannels&&(e._dataChannels.forEach((e=>e._close())),e._dataChannels.length=0)})),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),"fallback"===this._cloudProxyServerMode&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new JD("client-publish",this._clientId),this._subscribeMutex=new JD("client-subscribe",this._clientId),this._networkQualityInterval&&(window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=void 0),this._liveRawStreamingClient&&(this._liveRawStreamingClient.terminate(),this._liveRawStreamingClient.removeAllListeners(),this._liveRawStreamingClient=void 0),this._liveTranscodeStreamingClient&&(this._liveTranscodeStreamingClient.terminate(),this._liveTranscodeStreamingClient.removeAllListeners(),this._liveTranscodeStreamingClient=void 0),this._channelMediaRelayClient&&(this._channelMediaRelayClient.dispose(),this._channelMediaRelayClient=void 0),this._inspect)try{this._inspect.close(),this._inspect=void 0}catch(e){}if(this._moderation)try{this.setImageModeration(!1)}catch(e){}}_startSession(e,t){var n;const i=e||MD();e?SL.debug("[".concat(this._clientId,"] new Session ").concat(i)):SL.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(i));const r=e?"":this._sessionId||"";this._sessionId=i,this.store.sessionId=i,HL.addSid(i);const o={lts:(new Date).getTime(),mode:this.mode,buildFormat:2,stringUid:(null==t?void 0:t.stringUid)||(null===(n=this._joinInfo)||void 0===n?void 0:n.stringUid),channelProfile:"live"===this.mode?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:"audience"===this.role?2:1,rteUrl:this.store.rteUrl,rteSid:this.store.rteSid};HL.sessionInit(this._sessionId,voe({cname:t.channel,appid:t.appId},o)),this._joinInfo&&(this._joinInfo.sid=i),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=i)}async _publishHighStream(e){if(!this._joinInfo||void 0===this._uid)throw new YL(wN.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if("auto"===this._turnServer.mode&&xP("FORCE_TURN")&&!xP("TURN_ENABLE_TCP")&&!xP("TURN_ENABLE_UDP"))throw new YL(wN.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");SL.debug("[".concat(this._clientId,"] publish high stream"));try{const n=await this._p2pChannel.publish(e,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const e=(await n.next()).value;if(e){try{await this._gateway.sendExtensionMessage(QF.PUBLISH,e,!0)}catch(e){throw n.throw(e),e}await n.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const i=(await n.next()).value;if(i){var t;let e;try{e=await this._gateway.publish(this._uid,i,!0)}catch(e){if(e.code!==wN.DISCONNECT_P2P)throw n.throw(e),e}await n.next((null===(t=e)||void 0===t?void 0:t.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const t of e)t instanceof TV&&t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig).catch((e=>{SL.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))})),!t.muted&&t.enabled||await this._p2pChannel.muteLocalTrack(t)}}catch(t){if(this._p2pChannel.reportPublishEvent(!1,null==t?void 0:t.code,e),(null==t?void 0:t.code)===wN.WS_ABORT)return;throw t}}async _publishLowStream(){if(!this._joinInfo||void 0===this._uid)throw new YL(wN.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if("CONNECTED"!==this.connectionState&&"RECONNECTING"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));SL.debug("[".concat(this._clientId,"] publish low stream"));const e=this._configDistribute.getLowStreamConfigDistribute();e&&e.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&e.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=e.bitrate));try{const e=await this._p2pChannel.publishLowStream(this._lowStreamParameter),n=(await e.next()).value;if(n){var t;let i;try{i=await this._gateway.publish(this._uid,n,!0)}catch(t){if(t.code!==wN.DISCONNECT_P2P)throw e.throw(t),t}e.next((null===(t=i)||void 0===t?void 0:t.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(e){if(this._p2pChannel.reportPublishEvent(!1,null==e?void 0:e.code,void 0,!0),(null==e?void 0:e.code)===wN.WS_ABORT)return;throw e}}_createLiveStreamingClient(e){const t=()=>{if(!this._joinInfo||!this._appId){return new YL(wN.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw()}const e=(t={joinInfo:this._joinInfo,appId:this._appId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig},mee("LiveStreaming").create(t));var t;return e.onLiveStreamError=(e,t)=>{HL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:zN.ON_LIVE_STREAM_ERROR,options:[e,t],tag:ZN.TRACER}).onSuccess(),this.safeEmit(rD.LIVE_STREAMING_ERROR,e,t)},e.onLiveStreamWarning=(e,t)=>{HL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:zN.ON_LIVE_STREAM_WARNING,options:[e,t],tag:ZN.TRACER}).onSuccess(),this.safeEmit(rD.LIVE_STREAMING_WARNING,e,t)},e.on(fF.REQUEST_WORKER_MANAGER_LIST,((e,t,n)=>{if(!this._joinInfo)return n(new YL(wN.INVALID_OPERATION,"can not find join info to get worker manager"));(async function(e,t,n,i){const r=xP("UAP_AP").slice(0,xP("AJAX_REQUEST_CONCURRENT")).map((e=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(e+"/api/v1?action=uap"):"https://".concat(e,"/api/v1?action=uap")));return await Wee(r,e,t,n,i)})(e,this._joinInfo,this._axiosCancelSource.token,ZD).then(t).catch(n)})),e};return e===uF.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||t(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||t(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo){return new YL(wN.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw()}if(!this._channelMediaRelayClient){const t=this.getLocalVideoStats(),n=t.sendResolutionWidth,i=t.sendResolutionHeight,r=(e={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:n,height:i}},mee("ChannelMediaRelay").create(e));r.on("state",(e=>{e===vF.RELAY_STATE_FAILURE&&r&&r.dispose(),this.safeEmit(rD.CHANNEL_MEDIA_RELAY_STATE,e)})),r.on("event",(e=>{this.safeEmit(rD.CHANNEL_MEDIA_RELAY_EVENT,e)})),this._channelMediaRelayClient=r,this._statsCollector.onStatsChanged=(e,t)=>{var n;"resolution"===e&&(null===(n=this._channelMediaRelayClient)||void 0===n||n.setVideoProfile(t))}}var e;return this._channelMediaRelayClient}_handleFullDatachannel(e){const t=[],n=[];this._users.forEach((i=>{const r=i._dataChannels;r.forEach((n=>{e.some((e=>e.uid===i._uintid&&e.stream_id===n.id&&e.metadata===n.metadata))||t.push({uid:i._uintid,stream_id:n.id,ordered:n.ordered,max_retrans_times:n.maxRetransmits,metadata:n.metadata})})),e.filter((e=>e.uid===i._uintid)).forEach((e=>{if(!r.some((t=>i._uintid===e.uid&&t.id===e.stream_id&&t.metadata===e.metadata))){const r=t.findIndex((t=>i._uintid===t.uid&&t.stream_id===e.stream_id));-1!==r&&(n.push(e),t.splice(r,1))}}))})),this._handleDataChannelDeleted(t),this._handleDataChannelUpdated(n),this._handleDataChannelAdded(e,!0),SL.debug("[".concat(this._clientId,"] emit full infos, data_channel ids: ").concat(e.map((e=>e.stream_id)))),this.safeEmit(rD.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]}_handleDataChannelAdded(e,t){const n=[];Array.isArray(e)&&e.length>0&&(SL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," added")),e.forEach((e=>{const i=e.uid,r=e.stream_id,o=e.ordered,s=e.max_retrans_times,a=e.metadata,c=this._users.find((e=>e._uintid===i));if(!c)return void SL.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));SL.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(i)),Ui(n).call(n,c)||n.push(c),c._uintid||(c._uintid=i);const d=-1!==c._dataChannels.findIndex((t=>t.id===e.stream_id));if(d){const t=c._dataChannels.find((t=>t.id===e.stream_id));null==t||t._updateDataChannelConfig(voe(voe({},null==t?void 0:t.getConfig()),{},{metadata:e.metadata}))}else{const e={id:r,ordered:!!o,maxRetransmits:s,metadata:a},n=function(e){return gee(e,!0)}(e);c._dataChannels.push(n),SL.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published datachannel")),t||this.safeEmit(rD.USER_PUBLISHED,c,"datachannel",e)}this._p2pChannel.hasPendingRemoteDataChannel(c,e.stream_id)&&(SL.debug("[".concat(this._clientId,"] resubscribe datachannel id: ").concat(e.stream_id," for user ").concat(c.uid," after reconnect.")),this._subscribeDataChannel(c,e.stream_id).catch((e=>{SL.error("[".concat(this._clientId,"] resubscribe datachannel error"),e.toString())})))})))}_handleDataChannelUpdated(e){Array.isArray(e)&&e.length>0&&(SL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," updated")),e.forEach((e=>{var t;const n=e.uid,i=e.stream_id,r=e.metadata,o=this._users.find((e=>e._uintid===n));if(!o)return void SL.error("[".concat(this._clientId,"] can not find target user!(on_update_data_channel)"));const s=o._dataChannels.find((e=>e.id===i));SL.debug("[".concat(this._clientId,"] data_channel: ").concat(i," updated with uid ").concat(n,", last metadata: ").concat(null==s||null===(t=s._config)||void 0===t?void 0:t.metadata,", new metadata: ").concat(r)),this.safeEmit(rD.USER_UNPUBLISHED,o,"datachannel",null==s?void 0:s._config),this.safeEmit(rD.USER_PUBLISHED,o,"datachannel",{id:i,ordered:!!e.ordered,maxRetransmits:e.max_retrans_times,metadata:r})})))}_handleDataChannelDeleted(e){Array.isArray(e)&&e.length>0&&(SL.debug("[".concat(this._clientId,"] data_channel ids: ").concat(e.map((e=>e.stream_id))," deleted")),e.forEach((e=>{const t=e.uid;e.stream_id;const n=this._users.find((e=>e._uintid===t));if(!n)return void SL.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const i=n._dataChannels.find((t=>t.id===e.stream_id));i&&(SL.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(t)),n._dataChannels=n._dataChannels.filter((e=>e.id!==i.id)),this._p2pChannel.unsubscribeDataChannel(n,[i]).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,n.uid)})),SL.info("[".concat(this._clientId,"] remote user ").concat(t," unpublished datachannel , id:").concat(i.id)),this.safeEmit(rD.USER_UNPUBLISHED,n,"datachannel",i._config))})))}_handleUpdateDataChannel(e){const t=e.added,n=e.deleted;this._handleDataChannelDeleted(null!=n?n:[]),this._handleDataChannelAdded(null!=t?t:[])}_getEncodingName(e){var t,n;if(!this._joinResponse)return;const i=null===(t=this._joinResponse.ortc.rtpCapabilities.sendrecv)||void 0===t?void 0:t.videoCodecs;if(!i)return;for(const t of i){var r;if(t.payloadType===e)return null==t||null===(r=t.rtpMap)||void 0===r?void 0:r.encodingName}const o=null===(n=this._joinResponse.ortc.rtpCapabilities.recv)||void 0===n?void 0:n.videoCodecs;if(o)for(const t of o){var s;if(t.payloadType===e)return null==t||null===(s=t.rtpMap)||void 0===s?void 0:s.encodingName}return 0===e?"unknown":void 0}_handleRemoveDataChannels(e){const t=this._users.find((t=>t.uid===e.uid));if(t){if(void 0!==t._dataChannels&&t._dataChannels.length>0){SL.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(e.uid));const n=()=>{SL.info("[".concat(this._clientId,"] remote user ").concat(t.uid," unpublished datachannel")),t._dataChannels.forEach((e=>{this.safeEmit(rD.USER_UNPUBLISHED,t,"datachannel",e._config)}))};this._p2pChannel.unsubscribeDataChannel(t,t._dataChannels).then((e=>{if(e)return this._gateway.unsubscribeDataChannel(e,t.uid)})),n()}}else SL.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(bF.UPDATE_GATEWAY_CONFIG,(()=>{!function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void SL.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();Object.keys(t).forEach((e=>{const i=t[e],r=i.value,o=i.type,s=i.expires;s&&s<=n||o||Lx()||!Object.prototype.hasOwnProperty.call(PP,e)||(BP[e]=r,UP[e]=r,SL.debug("Update gateway parameters from config distribute",e,r))}))}catch(e){SL.error("Error update config from local cache",e.message)}}()})),this._gateway.on(bF.DISCONNECT_P2P,(async()=>{this._earlyJoinAttempt=void 0,await this._p2pChannel.disconnectForReconnect()})),this._gateway.on(bF.CONNECTION_STATE_CHANGE,((e,t,n)=>{var i;if(n===$N.FALLBACK)return;const r=()=>{this.safeEmit(rD.CONNECTION_STATE_CHANGE,e,t,n)};if(HL.reportApiInvoke(this._sessionId||(null===(i=this._gateway.joinInfo)||void 0===i?void 0:i.sid)||null,{clientId:this._clientId,name:zN.CONNECTION_STATE_CHANGE,options:[e,t,n],tag:ZN.TRACER}).onSuccess(JSON.stringify({cur:e,prev:t,reason:n})),SL.info("[".concat(this._clientId,"] signal connection state change: ").concat(t," -> ").concat(e)),"DISCONNECTED"===e)return this._reset(),void r();if("RECONNECTING"===e)this._users.forEach((e=>{e._trust_in_room_=!1,e._trust_audio_enabled_state_=!1,e._trust_video_enabled_state_=!1,e._trust_audio_mute_state_=!1,e._trust_video_mute_state_=!1,e._trust_audio_stream_added_state_=!1,e._trust_video_stream_added_state_=!1,e._is_pre_created||(e._audio_pre_subscribed||(e._audioSSRC=void 0,e._audioOrtc=void 0),e._video_pre_subscribed||(e._videoSSRC=void 0,e._videoOrtc=void 0,e._rtxSsrcId=void 0),e._cname=void 0)})),this._userOfflineTimeout&&window.clearTimeout(this._userOfflineTimeout),this._streamRemovedTimeout&&window.clearTimeout(this._streamRemovedTimeout),this._userOfflineTimeout=void 0,this._streamRemovedTimeout=void 0;else if("CONNECTED"===e){var o;this._streamFallbackTypeCacheMap.forEach(((e,t)=>{this._gateway.setStreamFallbackOption(t,e).catch((e=>{SL.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),e)}))})),this._remoteStreamTypeCacheMap.forEach(((e,t)=>{this._gateway.setRemoteVideoStreamType(t,e).catch((e=>{SL.warning("[".concat(this._clientId,"] auto set remote stream type failed"),e)}))})),xP("VOS_CONFIGURE")&&Array.isArray(xP("VOS_CONFIGURE"))&&xP("VOS_CONFIGURE").length>0&&(this._gateway.setConfigure(xP("VOS_CONFIGURE")).catch((e=>{SL.debug("[".concat(this._clientId,"] auto set vos config failed"),e)})),SL.debug("[".concat(this._clientId,"] ws connected auto set vos config"))),void 0!==this._remoteDefaultVideoStreamType&&void 0===(null===(o=this._joinInfo)||void 0===o?void 0:o.defaultVideoStream)&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then((()=>{SL.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))})).catch((e=>{SL.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(e))})),this._dualStreamMode&&this._gateway.setDualStreamMode(this._dualStreamMode).catch((e=>{SL.warning("[".concat(this._clientId,"] auto set dual stream mode failed"),e)})),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout((()=>{if("CONNECTED"!==this.connectionState)return;this._userOfflineTimeout=void 0;this._users.filter((e=>!e._trust_in_room_)).forEach((e=>{SL.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(e.uid)),this._handleUserOffline({uid:e.uid})}))}),3e3),this._streamRemovedTimeout=window.setTimeout((()=>{"CONNECTED"===this.connectionState&&(this._streamRemovedTimeout=void 0,this._users.forEach((e=>{e._trust_audio_mute_state_||(SL.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,UF.AUDIO,!1)),e._trust_video_mute_state_||(SL.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(e.uid)),this._handleMuteStream(e.uid,UF.VIDEO,!1)),e._trust_audio_enabled_state_||(SL.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(e.uid)),this._handleSetStreamLocalEnable("audio",e.uid,!0)),e._trust_video_enabled_state_||(SL.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(e.uid)),this._handleSetStreamLocalEnable("video",e.uid,!0)),e._trust_video_stream_added_state_||(SL.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(e.uid)),this._handleResetAddStream(e,"video")),e._trust_audio_stream_added_state_||(SL.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(e.uid)),this._handleResetAddStream(e,"audio")),e._video_added_||e._audio_added_||(SL.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(e.uid)),this._handleRemoveStream({uid:e.uid,uint_id:e._uintid}))})))}),1e3))}r()})),this._gateway.on(bF.REQUEST_NEW_GATEWAY_LIST,(async(e,t)=>{if(!this._joinInfo)return t(new YL(wN.UNEXPECTED_ERROR,"can not recover, no join info"));try{let t;if(this._fallbackServerInfo)t=this._fallbackServerInfo,this._fallbackServerInfo=void 0,this._joinInfo.preload=!1,HL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:zN.VOS_FALLBACK_CN,options:{cur:t.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!0},tag:ZN.TRACER}).onSuccess(),SL.info("[".concat(this._clientId,"] use fallback cn server info"));else{const e=await Gie(voe(voe({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));e?(t=e.ap,Xie(e),this._joinInfo.preload=!0):(t=await ate(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ZD,this.store),this._joinInfo.preload=!1)}this._joinInfo&&(this._joinInfo.apResponse=t.gatewayInfo.res,this._joinInfo.gatewayAddrs=t.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=t.gatewayInfo.uni_lbs_ip,this._earlyJoinAttempt=void 0);const n=[];t.gatewayInfo.gatewayAddrs.forEach((e=>{const t=KC(e.address.split(":"),2),i=t[0],r=t[1];this._joinInfo&&this._joinInfo.proxyServer?n.push({proxy:this._joinInfo.proxyServer,host:i,port:r}):n.push({host:i,port:r})})),e(n)}catch(e){t(e)}})),this._gateway.on(bF.NETWORK_QUALITY,(e=>{"normal"===this._networkQualitySensitivity&&this.safeEmit(rD.NETWORK_QUALITY,e)})),this._gateway.on(bF.STREAM_TYPE_CHANGE,((e,t)=>{this.safeEmit(rD.STREAM_TYPE_CHANGED,e,t);HL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:zN.STREAM_TYPE_CHANGE,options:[e,t],tag:ZN.TRACER}).onSuccess(JSON.stringify({uid:e,streamType:t}))})),this._gateway.isPreSub=()=>"isPreSub"in this._p2pChannel&&this._p2pChannel.isPreSub(),this._gateway.isPreallocation=()=>"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation(),this._gateway.on(bF.IS_P2P_DISCONNECTED,(e=>{this._p2pChannel.isP2PDisconnected()?e(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?e(!1):e(!0)})),this._gateway.on(bF.REQUEST_P2P_CONNECTION_PARAMS,(async(e,t,n)=>{try{let n=await this._p2pChannel.getEstablishParams();n&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?this._p2pChannel.updateConnectionConfiguration(e):n=await this._p2pChannel.startP2PConnection(e),t(n)}catch(e){n(e)}})),this._gateway.on(bF.JOIN_RESPONSE,((e,t)=>{var n;if(this.store.useP2P)return;let i;this._joinResponse=voe(voe(voe({},this._joinResponse),e),{},{ortc:e.ortc||(null===(n=this._joinResponse)||void 0===n?void 0:n.ortc)}),e.attributes?i=e.attributes.userAttributes.preSubSsrcs:SL.debug("no attributes in joinResponse");const r=G7(this._joinResponse.ortc,t,i),o=this._joinInfo;this._p2pChannel.connect(r).catch((e=>{if(this._joinInfo===o)throw e;SL.debug("[".concat(this._clientId,"] ignore P2P connect from a stale join"),e)}))})),this._gateway.on(bF.PRE_CONNECT_PC,(async(e,t,n)=>{const i=e.candidates,r=e.fingerprint,o=e.turnServer,s=e.rtpCapabilities,a=e.originalPreSubSsrcs;if(this._joinInfo&&i.length>0&&!this._p2pChannel.isPlanB){const d=this._joinInfo.apResponse,l=d.cert,u=d.cid,h="".concat(u,"_").concat(l),p=e.iceUfrag||h,_=e.icePwd||h;if(!vee(p,_))return SL.debug("[".concat(this._clientId,"] ufrag/pwd length is not valid, length: ").concat(p.length," / ").concat(_.length)),void t();let E;await this._p2pChannel.getEstablishParams()&&"isPreallocation"in this._p2pChannel&&this._p2pChannel.isPreallocation()?(this._p2pChannel.updateConnectionConfiguration({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0}),SL.debug("pre pc before connect ws/dc, use sdp endpoint")):await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer,isPreallocation:!0}),e.isSDPEndpoint&&this._p2pChannel instanceof die&&this._p2pChannel.markSDPEndpointConnection(),Array.isArray(a)&&a.length>0&&(E=W7(a));try{var c;t(await this._p2pChannel.connect(voe({iceParameters:{iceUfrag:p,icePwd:_},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:null!==(c=xP("FINGERPRINT"))&&void 0!==c?c:r}]},candidates:i,rtpCapabilities:s?vD(s):{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0},E?{preSSRCs:E}:{})))}catch(e){e.code&&e.code===wN.EXCHANGE_SDP_FAILED&&(SL.debug("try to pre connect pc, but exchange sdp failed, reset p2p connection",e),await this._p2pChannel.startP2PConnection({turnServer:o,cloudProxyServer:this._joinInfo.cloudProxyServer},!0)),n(e)}}})),this._gateway.on(bF.VOS_FALLBACK,(e=>{"fallback_hls"===e&&this.safeEmit(rD.FALLBACK_TO_HLS,oD.VOSERROR)})),this._gateway.on(bF.RESET_SIGNAL,(()=>{this._p2pChannel instanceof die&&this._p2pChannel.fallbackConnection(),this._handleGatewaySignalEvents()})),this._gateway.on(bF.DATACHANNEL_FAILBACK,(()=>{HL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:zN.DATACHANNEL_FAILBACK,options:{},tag:ZN.TRACER}).onSuccess(),this._joinGateway()}))}_handleGatewaySignalEvents(){this._gateway.signal.on(sF.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(sF.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(sF.ON_ADD_AUDIO_STREAM,(e=>this._handleAddAudioOrVideoStream("audio",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc))),this._gateway.signal.on(sF.ON_ADD_VIDEO_STREAM,(e=>this._handleAddAudioOrVideoStream("video",e.uid,e.ssrcId,e.cname,e.pt,e.uint_id,e.ortc,e.rtxSsrcId))),this._gateway.signal.on(sF.ON_REMOTE_DATASTREAM_UPDATE,(e=>{this._handleUpdateDataChannel(e)})),this._gateway.signal.on(sF.ON_REMOTE_FULL_DATASTREAM_INFO,(e=>{var t;this._handleFullDatachannel(null!==(t=e.datastreams)&&void 0!==t?t:[])})),this._gateway.signal.on(sF.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(sF.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(sF.MUTE_AUDIO,(e=>this._handleMuteStream(e.uid,UF.AUDIO,!0))),this._gateway.signal.on(sF.UNMUTE_AUDIO,(e=>this._handleMuteStream(e.uid,UF.AUDIO,!1))),this._gateway.signal.on(sF.MUTE_VIDEO,(e=>this._handleMuteStream(e.uid,UF.VIDEO,!0))),this._gateway.signal.on(sF.UNMUTE_VIDEO,(e=>this._handleMuteStream(e.uid,UF.VIDEO,!1))),this._gateway.signal.on(sF.RECEIVE_METADATA,(e=>{const t=ID(e.metadata);this.safeEmit(rD.RECEIVE_METADATA,e.uid,t)})),this._gateway.signal.on(sF.ON_DATA_STREAM,(async e=>{var t;if(!e)return;let n=ID(e.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&Ui(t=["aes-128-gcm2","aes-256-gcm2"]).call(t,this._encryptionMode)){if(e.payload.length<YP)throw new YL(wN.UNEXPECTED_RESPONSE,"payload length ".concat(e.payload.length," is less than header length ").concat(YP));const t=await async function(e,t,n){const i=n.subarray(0,YP),r=i.slice(8,YP),o=(r[0]<<8)+r[1],s=(i[6]<<8)+i[7],a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:e,tagLength:WP,additionalData:new Uint8Array(jD(o,2))},t,n.subarray(YP));return new Uint8Array(a).subarray(0,s)}(this._encryptDataStreamIv,this._encryptDataStreamKey,n);n=t}let i=0;if(e.ordered||e.syncWithAudio){const t=this._p2pChannel.getStats(),n=this.remoteUsers.find((t=>t.uid===e.uid)),r=null==t?void 0:t.audioRecv.find((e=>e.ssrc===(null==n?void 0:n._audioSSRC)));i=null==r?void 0:r.jitterBufferMs}(null==i||Number.isNaN(i))&&(i=0),Cie(voe(voe({},e),{},{payload:n}),i,{id:this._clientId,onStreamMessage:"function"==typeof this.onStreamMessage?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(sF.ON_CRYPT_ERROR,(()=>{bD((()=>{SL.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(rD.CRYPT_ERROR)}),this._sessionId)})),this._gateway.signal.on(sF.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(sF.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{SL.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,$N.TOKEN_EXPIRE),this.safeEmit(rD.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()})),this._gateway.signal.on(sF.ON_STREAM_FALLBACK_UPDATE,(e=>{SL.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(e.stream_id,", attr: ").concat(e.stream_type)),this.safeEmit(rD.STREAM_FALLBACK,e.stream_id,1===e.stream_type?"fallback":"recover")})),this._gateway.signal.on(sF.ENABLE_MULTI_STREAM,(e=>{this._dualStreamMode===nD.AUTO_SIMULCAST_STREAM&&this.enableDualStream().catch((e=>{SL.debug("[".concat(this._clientId,"] set dual stream mode error"),e.toString())}))})),this._gateway.signal.on(sF.ON_PUBLISH_STREAM,(e=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:e.proxy})),SL.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(e))))})),this._gateway.signal.on(sF.ENABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!0)})),this._gateway.signal.on(sF.DISABLE_LOCAL_VIDEO,(e=>{this._handleSetStreamLocalEnable("video",e.uid,!1)})),this._gateway.signal.on(iF.REQUEST_TIMEOUT,((e,t)=>{if(this._joinInfo)switch(e){case rF.PUBLISH:{if(!t)return;const e=t.ortc;if(e){var n,i;const r=e.some((e=>e.stream_type===CF.Audio)),o=e.some((e=>e.stream_type!==CF.Audio)),s=e.some((e=>{let t=e.stream_type;return t===CF.Screen||t===CF.ScreenLow}));"offer"===t.state&&HL.publish(this._joinInfo.sid,{eventElapse:Vte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:wN.TIMEOUT,audio:r,video:o,p2pid:t.p2p_id,publishRequestid:this.store.pubId,screenshare:s,audioName:r?null===(n=e.find((e=>e.stream_type===CF.Audio)))||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId.toString():void 0,videoName:o?null===(i=e.find((e=>e.stream_type!==CF.Audio)))||void 0===i||null===(i=i.ssrcs[0])||void 0===i?void 0:i.ssrcId.toString():void 0})}break}case rF.SUBSCRIBE:t&&HL.subscribe(this._joinInfo.sid,{succ:!1,ec:wN.TIMEOUT,audio:t.stream_type===UF.AUDIO,video:t.stream_type===UF.VIDEO,peerid:t.stream_id,subscribeRequestid:t.ssrcId,p2pid:this.store.p2pId,eventElapse:Vte.measureFromSubscribeStart(this.store.clientId,t.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(t.ssrcId)})}})),this._gateway.signal.on(sF.ON_P2P_OK,(e=>{this.uid,this._uid})),this._gateway.signal.on(sF.ON_PUBLISHED_USER_LIST,(e=>{if(null==e||!e.users)return;let t=e.users;xP("BLOCK_LOCAL_CLIENT")&&(t=t.filter((e=>!Px(e.string_id||e.stream_id,this.channelName)))),this._handleUserList(t)})),this._gateway.signal.on(sF.ON_USER_LIST,(e=>{if(!e||!Array.isArray(e.users)||0===e.users.length)return;let t=e.users;t=xP("BLOCK_LOCAL_CLIENT")?t.filter((e=>!Px(e.string_id||e.stream_id,this.channelName))):t,this._handleUserList(t)})),this._gateway.signal.on(sF.ON_RTP_CAPABILITY_CHANGE,(e=>{const t=e.video_codec;if(this._p2pChannel instanceof die){if("audience"===this.role&&xP("UPDATE_RTP_CAP_IN_HOST"))return this._pendingRtpCapabilityChange=e,void SL.debug("[".concat(this._clientId,"] no need to change rtp capability because of audience, params: ").concat(JSON.stringify(e)));this._p2pChannel.updateRemoteRTPCapabilities(t.map((e=>e.toLowerCase())).filter((e=>{var t;return Ui(t=Object.keys(GP)).call(t,e)})))}})),this._gateway.signal.on(iF.VOS_FALLBACK_PROMISE,(async(e,t,n)=>{if("FALLBACKCN"===e&&xP("ENABLE_QUALITY_FALLBACK")){if(!this._joinInfo)return n(new YL(wN.UNEXPECTED_ERROR,"can not recover, no join info"));SL.info("[".concat(this._clientId,"] try fallback to cn, start request new server info"));const r=this._joinInfo.apRequestDetail;try{this._joinInfo.apRequestDetail=e;const i=await ate(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ZD,this.store);if(xP("QUALITY_FALLBACK_REHEARSAL"))return HL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:zN.VOS_FALLBACK_CN,options:{cur:i.gatewayInfo.gatewayAddrs,prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:ZN.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r,void n();this._fallbackServerInfo=i,t()}catch(e){var i;const t=null==e||null===(i=e.data)||void 0===i?void 0:i.desc;xP("QUALITY_FALLBACK_REHEARSAL")?(HL.reportApiInvoke(this._sessionId,{clientId:this._clientId,name:zN.VOS_FALLBACK_CN,options:{cur:"failed, errorReason: "+t||"unknown",prev:this._joinInfo.gatewayAddrs,is_done:!1},tag:ZN.TRACER}).onSuccess(),this._joinInfo.apRequestDetail=r):Array.isArray(t)&&Ui(t).call(t,"request downgrade fallback")&&this.safeEmit(rD.FALLBACK_TO_HLS,oD.AP_ERROR),n(e)}}else n()}))}_handleUserList(e){var t=this;if(0===e.length)return;const n=[],i=[],r=[],o=[],s=[],a=[],c=this.getListeners(rD.USER_LIST).length>0,d=this.getListeners(rD.PUBLISHED_USER_LIST).length>0;for(const t of e){let e=this._users.find((e=>e._uintid===t.stream_id));const c=!!e;e?e._trust_in_room_=!0:(e=new Wte(t.string_id||t.stream_id,t.stream_id),this._users.push(e),this.store.firstVideoFrameDecoded(e.uid,{userJoinNotify:Date.now()}));const d=AF.Audio&t.stream_type,l=(AF.Video|AF.LowVideo)&t.stream_type,u=0!=(65280&t.stream_type),h=d&&e.hasAudio,p=l&&e.hasVideo;l&&(e._trust_video_stream_added_state_=!0,e._video_added_=!0,e._videoSSRC=t.video_ssrc,e._rtxSsrcId=t.video_rtx),d&&(e._trust_audio_stream_added_state_=!0,e._audio_added_=!0,e._audioSSRC=t.audio_ssrc),(d&&!h||l&&!p||u)&&(i.push(e),d&&!h&&r.push(e),l&&!p&&o.push(e)),c||s.push(e),l&&this._p2pChannel.hasPendingRemoteMedia(e,"video")&&a.push({user:e,mediaType:"video"}),d&&this._p2pChannel.hasPendingRemoteMedia(e,"audio")&&a.push({user:e,mediaType:"audio"}),n.push(e)}a.length>0&&(SL.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(a.map((e=>"user: ".concat(e.user.uid,", mediaType: ").concat(e.mediaType))).join("; ")," ")),this.massSubscribe(a).catch((e=>{SL.error("[".concat(this._clientId,"] mass resubscribe error"),e.toString())})));const l=function(){let e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];SL.info("[".concat(t._clientId,"] client not emit user-list event case there is no user-list listener...")),e||s.forEach((e=>{SL.debug("[".concat(t._clientId,"] user online"),e._uintid),t.safeEmit(rD.USER_JOINED,e)})),i.length>0&&(r.forEach((e=>{SL.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published audio")),t.safeEmit(rD.USER_PUBLISHED,e,"audio")})),o.forEach((e=>{SL.info("[".concat(t._clientId,"] remote user ").concat(e.uid," published video")),t.safeEmit(rD.USER_PUBLISHED,e,"video")})))};if(xP("ENABLE_USER_LIST"))c?(this.safeEmit(rD.USER_LIST,n),l(!0)):l();else if(d){if(i.length>0){const e=sr(i).call(i,((e,t)=>"".concat(e&&e+", ").concat(t.uid)),"");xP("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=i:(SL.info("[".concat(this._clientId,"] client emit published-user-list, users: ").concat(e)),this.safeEmit(rD.PUBLISHED_USER_LIST,i))}}else l()}_handleP2PEvents(){this._gateway.signal.on(sF.ON_USER_OFFLINE,(()=>{this._p2pChannel.disconnectForReconnect()})),this._gateway.signal.on(QF.PUBLISH,((e,t,n)=>{const i=e.uid;e.forEach((e=>{const r=e.kind,o=e.ssrcs,s=e.mid,a=e.isMuted;this._handleP2PAddAudioOrVideoStream(r,i,o[0].ssrcId,s);const c=this._users.find((e=>e.uid===i));return c&&this.store.useP2P?this._p2pChannel.mockSubscribe(c,r,o[0].ssrcId,s).then((()=>{t()})).catch(n):t(),this._handleMuteStream(i,r,!!a)}))})),this._gateway.signal.on(QF.CALL,(async(e,t,n)=>{if(this.store.useP2P)try{var i;t(await this._p2pChannel.startP2P({turnServer:null===(i=this._joinInfo)||void 0===i?void 0:i.turnServer},e))}catch(e){n(e)}})),this._gateway.signal.on(iF.P2P_CONNECTION,(async e=>{this.store.useP2P&&(await this._p2pChannel).p2pConnect(e)})),this._gateway.signal.on(QF.UNPUBLISH,(async(e,t,n)=>{if(this.store.useP2P){const i=e.unpubMsg,r=e.uid,o=this._users.find((e=>e.uid===r));if(!o)return SL.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void t();try{i.forEach((async e=>{const t=e.stream_type===CF.Audio?UF.AUDIO:UF.VIDEO;await this._p2pChannel.unsubscribe(o,t),this._handleMuteStream(r,t,!0)})),t()}catch(e){n(e)}}})),this._gateway.signal.on(QF.CONTROL,(async(e,t)=>{switch(e.action){case eB.MUTE_LOCAL_VIDEO:this._handleMuteStream(t,UF.VIDEO,!0);break;case eB.MUTE_LOCAL_AUDIO:this._handleMuteStream(t,UF.AUDIO,!0);break;case eB.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",t),this._handleMuteStream(t,UF.VIDEO,!1);break;case eB.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",t),this._handleMuteStream(t,UF.AUDIO,!1)}})),this._gateway.signal.on(QF.RESTART_ICE,(async(e,t,n)=>{if(this.store.useP2P)try{const n=e.direction,i=e.iceParameter;if(n!==aF.SEND_ONLY||i){t(await this._p2pChannel.restartICE(n,i))}else this._p2pChannel.handleDisconnect(n),t()}catch(e){n(e)}})),this._gateway.signal.on(QF.CANDIDATE,(e=>{if(this.store.useP2P){const t=e.candidate,n=e.direction;this._p2pChannel.addRemoteCandidate(t,n)}})),this._p2pChannel.on(GF.RequestP2PRestartICE,(async(e,t,n)=>{try{const n=e.direction;t(await this._gateway.sendExtensionMessage(QF.RESTART_ICE,e,n===aF.SEND_ONLY))}catch(e){n(e)}})),this._p2pChannel.on(GF.LocalCandidate,(e=>{this._gateway.sendExtensionMessage(QF.CANDIDATE,JSON.stringify(e),!0)})),this._p2pChannel.on(GF.RequestP2PMuteLocal,(async(e,t,n)=>{try{await this._gateway.sendExtensionMessage(QF.CONTROL,e,!0),t()}catch(e){n(e)}})),this._p2pChannel.on(GF.RequestP2PUnmuteRemote,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.unmuteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===wN.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(GF.RequestP2PMuteRemote,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.muteRemote(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===wN.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(GF.StateChange,((e,t)=>{t===jF.Connected&&this._p2pChannel.republish()}))}_handleP2PChannelEvents(){this._p2pChannel.on(GF.IceConnectionStateChange,(e=>{if("string"==typeof e||"connected"!==e.state&&"completed"!==e.state)return;const t=this._earlyJoinAttempt;t&&e.remoteUfrag&&t.acceptIceProof({remoteUfrag:e.remoteUfrag,state:"connected",at:Date.now()})})),this._p2pChannel.on(GF.PeerConnectionStateChange,(e=>{const t=this._peerConnectionState;e!==t&&(this.safeEmit(rD.PEERCONNECTION_STATE_CHANGE,e,t),this._peerConnectionState=e)})),this._p2pChannel.on(GF.RequestMuteLocal,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.muteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===wN.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(GF.RequestUnmuteLocal,(async(e,t,n)=>{if(this._joinInfo)try{await this._gateway.unmuteLocal(e,this._joinInfo.stringUid||this._joinInfo.uid),t()}catch(e){e.code===wN.DISCONNECT_P2P?t():n(e)}else t()})),this._p2pChannel.on(GF.RequestRePublish,((e,t,n)=>{this.publish(e,!1).then(t).catch(n)})),this._p2pChannel.on(GF.RequestRePublishDataChannel,((e,t,n)=>{cp.all(e.map((async e=>{const t=await this._p2pChannel.publishDataChannel([e]);try{t.forEach((e=>{this._uid&&this._gateway.publishDataChannel(this._uid,e,!0)}))}catch(e){if(e.code!==wN.DISCONNECT_P2P)throw e}}))).then(t).catch(n)})),this._p2pChannel.on(GF.RequestReSubscribe,(async(e,t,n)=>{try{for(const t of e){const e=t.user;t.kind===UF.VIDEO?await this.subscribe(e,"video"):await this.subscribe(e,"audio")}t()}catch(e){n(e)}})),this._p2pChannel.on(GF.RequestUpload,((e,t)=>{this._gateway.upload(e,t)})),this._p2pChannel.on(GF.RequestUploadStats,(e=>{this._gateway.uploadWRTCStats(e)})),this._p2pChannel.on(GF.MediaReconnectStart,(e=>{this.safeEmit(rD.MEDIA_RECONNECT_START,e)})),this._p2pChannel.on(GF.MediaReconnectEnd,(e=>{this.safeEmit(rD.MEDIA_RECONNECT_END,e)})),this._p2pChannel.on(GF.NeedSignalRTT,(e=>{e(this._gateway.getSignalRTT())})),this._p2pChannel.on(GF.RequestRestartICE,(async e=>{if(this.store.useP2P)return;const t=await this._p2pChannel.restartICE(e),n=await t.next();if(n.done)return;const i=n.value;let r;try{r=await this._gateway.restartICE({iceParameters:i})}catch(e){return void await t.throw(e)}const o=function(e){const t=e.iceParameters;return{iceParameters:{iceUfrag:t.iceUfrag,icePwd:t.icePwd}}}(r).iceParameters;await t.next({remoteIceParameters:o})})),this._p2pChannel.on(GF.RequestReconnect,(async()=>{this._gateway.reconnect()})),this._p2pChannel.on(GF.RequestReconnectPC,(async()=>{var e;const t=await this._p2pChannel.startP2PConnection({turnServer:null===(e=this._joinInfo)||void 0===e?void 0:e.turnServer}),n=t.iceParameters,i=t.dtlsParameters,r=t.rtpCapabilities,o=await this._gateway.reconnectPC({iceParameters:n,dtlsParameters:i,rtpCapabilities:r}),s=G7(o.gatewayEstablishParams,o.gatewayAddress);await this._p2pChannel.connect(s),await this._p2pChannel.republish(),await this._p2pChannel.reSubscribe()})),this._p2pChannel.on(GF.RequestUnpublishForReconnectPC,(async(e,t,n)=>{this._joinInfo&&void 0!==this._uid?(await this._gateway.unpublish(e,this._uid),t()):n()})),this._p2pChannel.on(GF.P2PLost,(()=>{this.safeEmit(rD.P2P_LOST,this.store.uid)})),this._p2pChannel.on(GF.UpdateVideoEncoder,(e=>{e._encoderConfig&&this._gateway.setVideoProfile(e._encoderConfig)})),this._p2pChannel.on(GF.ConnectionTypeChange,(e=>{this.safeEmit(rD.IS_USING_CLOUD_PROXY,e),this._gateway.setUsingProxy(e)})),this._p2pChannel.on(GF.FirstVideoBufferReady,((e,t)=>{this.safeEmit(rD.FIRST_VIDEO_BUFFER_READY,e,t)})),this._p2pChannel.on(GF.FirstVideoPreRender,((e,t)=>{this.safeEmit(rD.FIRST_VIDEO_PRE_RENDER,e,t)})),this._p2pChannel.on(GF.RequestLowStreamParameter,(e=>{e(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})})),this._p2pChannel.on(GF.QueryClientConnectionState,(e=>{e(this.connectionState)})),this._p2pChannel.on(GF.AudioMetadata,(e=>{this.safeEmit(rD.AUDIO_METADATA,e)})),this._p2pChannel.on(GF.AudioPts,(e=>{this.safeEmit(rD.AUDIO_PTS,Number(e))}))}getKeyMetrics(){return this.store.keyMetrics}async enableContentInspect(e){if(!this._joinInfo||"CONNECTED"!==this.connectionState)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const n=(t={config:e},mee("ContentInspect").create(t));this._inspect=n,this.handleVideoInspectEvents(n);const i=this._joinInfo,r=i.appId,o=i.cname,s=i.sid,a=i.token,c=i.uid,d=i.cid,l=i.vid;await n.init({appId:r,areaCode:"",cname:o,sid:s,token:a,uid:c,cid:d,vid:l?Number(l):0},ZD)}catch(e){throw Array.isArray(e)?e[0]:e}var t}handleVideoInspectEvents(e){e.on(HF.CONNECTION_STATE_CHANGE,((t,n)=>{if(this.safeEmit(rD.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,t,n),n===WF.CONNECTED){if("CONNECTED"!==this.connectionState)return void this.safeEmit(rD.CONTENT_INSPECT_ERROR,new YL(wN.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));e.inspectImage()}})),e.on(HF.INSPECT_RESULT,((e,t)=>{var n;if((null==t?void 0:t.code)===wN.INVALID_OPERATION&&"DISCONNECTED"===this.connectionState)return SL.debug("Stop inspect content because that has left channel"),null==this||null===(n=this._inspect)||void 0===n||n.close(),void(this._inspect=void 0);this.safeEmit(rD.CONTENT_INSPECT_RESULT,e,t)})),e.on(HF.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}async disableContentInspect(){if(!this._inspect)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}async setImageModeration(e,t){if(NN(e,"enabled"),e){if(!t)throw new YL(wN.INVALID_PARAMS,"config is required");if(Nre(t),!this._joinInfo)throw new YL(wN.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(t);else{const e=(n={config:t},mee("ImageModeration").create(n));this._moderation=e,this.handleImageModerationEvents(e);const i=this._joinInfo,r=i.appId,o=i.cname,s=i.sid,a=i.token,c=i.uid,d=i.cid,l=i.vid;await e.init({appId:r,areaCode:"",cname:o,sid:s,token:a,uid:c,cid:d,vid:l?Number(l):0},ZD)}}catch(e){throw Array.isArray(e)?e[0]:e}}else{var n;if(!this._moderation)throw new YL(wN.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(e){throw Array.isArray(e)?e[0]:e}}}handleImageModerationEvents(e){e.on(ZF.CONNECTION_STATE_CHANGE,((t,n)=>{if(this.safeEmit(rD.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,t,n),t===zF.CONNECTED){if("CONNECTED"!==this.connectionState)throw this.setImageModeration(!1),new YL(wN.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");e.inspectImage()}})),e.on(ZF.CLIENT_LOCAL_VIDEO_TRACK,(e=>{e(this.localTracks.filter((e=>"video"===e.trackMediaType))[0])}))}setP2PTransport(e){if(function(e){DN(e,"transport",["default","auto","relay","sd-rtn"])}(e),"p2p"!==this.mode)throw new YL(wN.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=e,SL.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(e))}getJoinChannelServiceRecords(){return SL.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}async setPublishAudioFilterEnabled(e){NN(e,"enabled"),VP("ENABLE_PUBLISH_AUDIO_FILTER",e),this._joinInfo&&await this._gateway.setPublishAudioFilterEnabled(e)}_setRteInfo(e,t){this.store.rteUrl=e,this.store.rteSid=t}_isPreRender(){return"isPreRender"in this._p2pChannel&&this._p2pChannel.isPreRender()}_handleResetAddStream(e,t){switch(t){case"audio":e._audio_added_=!1,e._trust_audio_stream_added_state_=!0;break;case"video":e._video_added_=!1,e._trust_video_stream_added_state_=!0}}},Zx(Toe.prototype,"leave",[Pre],Object.getOwnPropertyDescriptor(Toe.prototype,"leave"),Toe.prototype),Zx(Toe.prototype,"publish",[Lre],Object.getOwnPropertyDescriptor(Toe.prototype,"publish"),Toe.prototype),Zx(Toe.prototype,"unpublish",[kre],Object.getOwnPropertyDescriptor(Toe.prototype,"unpublish"),Toe.prototype),Zx(Toe.prototype,"subscribe",[Mre],Object.getOwnPropertyDescriptor(Toe.prototype,"subscribe"),Toe.prototype),Zx(Toe.prototype,"presubscribe",[Ure],Object.getOwnPropertyDescriptor(Toe.prototype,"presubscribe"),Toe.prototype),Zx(Toe.prototype,"massSubscribe",[Vre],Object.getOwnPropertyDescriptor(Toe.prototype,"massSubscribe"),Toe.prototype),Zx(Toe.prototype,"unsubscribe",[xre],Object.getOwnPropertyDescriptor(Toe.prototype,"unsubscribe"),Toe.prototype),Zx(Toe.prototype,"massUnsubscribe",[Fre],Object.getOwnPropertyDescriptor(Toe.prototype,"massUnsubscribe"),Toe.prototype),Zx(Toe.prototype,"setLowStreamParameter",[Bre],Object.getOwnPropertyDescriptor(Toe.prototype,"setLowStreamParameter"),Toe.prototype),Zx(Toe.prototype,"setDualStreamMode",[jre],Object.getOwnPropertyDescriptor(Toe.prototype,"setDualStreamMode"),Toe.prototype),Zx(Toe.prototype,"enableDualStream",[Gre],Object.getOwnPropertyDescriptor(Toe.prototype,"enableDualStream"),Toe.prototype),Zx(Toe.prototype,"disableDualStream",[Wre],Object.getOwnPropertyDescriptor(Toe.prototype,"disableDualStream"),Toe.prototype),Zx(Toe.prototype,"setClientRole",[Kre],Object.getOwnPropertyDescriptor(Toe.prototype,"setClientRole"),Toe.prototype),Zx(Toe.prototype,"_setClientRoleOptions",[Hre],Object.getOwnPropertyDescriptor(Toe.prototype,"_setClientRoleOptions"),Toe.prototype),Zx(Toe.prototype,"setProxyServer",[Yre],Object.getOwnPropertyDescriptor(Toe.prototype,"setProxyServer"),Toe.prototype),Zx(Toe.prototype,"setTurnServer",[Xre],Object.getOwnPropertyDescriptor(Toe.prototype,"setTurnServer"),Toe.prototype),Zx(Toe.prototype,"setLicense",[Jre],Object.getOwnPropertyDescriptor(Toe.prototype,"setLicense"),Toe.prototype),Zx(Toe.prototype,"startProxyServer",[zre],Object.getOwnPropertyDescriptor(Toe.prototype,"startProxyServer"),Toe.prototype),Zx(Toe.prototype,"stopProxyServer",[Zre],Object.getOwnPropertyDescriptor(Toe.prototype,"stopProxyServer"),Toe.prototype),Zx(Toe.prototype,"setLocalAccessPointsV2",[qre],Object.getOwnPropertyDescriptor(Toe.prototype,"setLocalAccessPointsV2"),Toe.prototype),Zx(Toe.prototype,"setLocalAccessPoints",[Qre],Object.getOwnPropertyDescriptor(Toe.prototype,"setLocalAccessPoints"),Toe.prototype),Zx(Toe.prototype,"setRemoteDefaultVideoStreamType",[$re],Object.getOwnPropertyDescriptor(Toe.prototype,"setRemoteDefaultVideoStreamType"),Toe.prototype),Zx(Toe.prototype,"setRemoteVideoStreamType",[eoe],Object.getOwnPropertyDescriptor(Toe.prototype,"setRemoteVideoStreamType"),Toe.prototype),Zx(Toe.prototype,"setStreamFallbackOption",[toe],Object.getOwnPropertyDescriptor(Toe.prototype,"setStreamFallbackOption"),Toe.prototype),Zx(Toe.prototype,"setEncryptionConfig",[noe],Object.getOwnPropertyDescriptor(Toe.prototype,"setEncryptionConfig"),Toe.prototype),Zx(Toe.prototype,"renewToken",[ioe],Object.getOwnPropertyDescriptor(Toe.prototype,"renewToken"),Toe.prototype),Zx(Toe.prototype,"enableAudioVolumeIndicator",[roe],Object.getOwnPropertyDescriptor(Toe.prototype,"enableAudioVolumeIndicator"),Toe.prototype),Zx(Toe.prototype,"startLiveStreaming",[ooe],Object.getOwnPropertyDescriptor(Toe.prototype,"startLiveStreaming"),Toe.prototype),Zx(Toe.prototype,"setLiveTranscoding",[soe],Object.getOwnPropertyDescriptor(Toe.prototype,"setLiveTranscoding"),Toe.prototype),Zx(Toe.prototype,"stopLiveStreaming",[aoe],Object.getOwnPropertyDescriptor(Toe.prototype,"stopLiveStreaming"),Toe.prototype),Zx(Toe.prototype,"startChannelMediaRelay",[coe],Object.getOwnPropertyDescriptor(Toe.prototype,"startChannelMediaRelay"),Toe.prototype),Zx(Toe.prototype,"updateChannelMediaRelay",[doe],Object.getOwnPropertyDescriptor(Toe.prototype,"updateChannelMediaRelay"),Toe.prototype),Zx(Toe.prototype,"stopChannelMediaRelay",[loe],Object.getOwnPropertyDescriptor(Toe.prototype,"stopChannelMediaRelay"),Toe.prototype),Zx(Toe.prototype,"sendCustomReportMessage",[uoe],Object.getOwnPropertyDescriptor(Toe.prototype,"sendCustomReportMessage"),Toe.prototype),Zx(Toe.prototype,"pickSVCLayer",[hoe],Object.getOwnPropertyDescriptor(Toe.prototype,"pickSVCLayer"),Toe.prototype),Zx(Toe.prototype,"setRTMConfig",[poe],Object.getOwnPropertyDescriptor(Toe.prototype,"setRTMConfig"),Toe.prototype),Zx(Toe.prototype,"enableContentInspect",[_oe],Object.getOwnPropertyDescriptor(Toe.prototype,"enableContentInspect"),Toe.prototype),Zx(Toe.prototype,"disableContentInspect",[Eoe],Object.getOwnPropertyDescriptor(Toe.prototype,"disableContentInspect"),Toe.prototype),Zx(Toe.prototype,"setImageModeration",[moe],Object.getOwnPropertyDescriptor(Toe.prototype,"setImageModeration"),Toe.prototype),Zx(Toe.prototype,"setP2PTransport",[foe],Object.getOwnPropertyDescriptor(Toe.prototype,"setP2PTransport"),Toe.prototype),Zx(Toe.prototype,"getJoinChannelServiceRecords",[goe],Object.getOwnPropertyDescriptor(Toe.prototype,"getJoinChannelServiceRecords"),Toe.prototype),Zx(Toe.prototype,"setPublishAudioFilterEnabled",[Soe],Object.getOwnPropertyDescriptor(Toe.prototype,"setPublishAudioFilterEnabled"),Toe.prototype),Toe);function Coe(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const t=kD(5,"client-"),n=HL.reportApiInvoke(null,{id:t,clientId:t,name:zN.CREATE_CLIENT,options:[e],tag:ZN.TRACER});try{var i;!function(e){DN(e.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),DN(e.mode,"config.mode",["rtc","live","p2p"]),void 0!==e.audioCodec&&DN(e.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),void 0!==e.aiClientMode&&NN(e.aiClientMode,"config.aiClientMode"),void 0!==e.proxyServer&&kN(e.proxyServer,"config.proxyServer",1,1e4),void 0!==e.turnServer&&tD(e.turnServer),void 0!==e.httpRetryConfig&&qN(e.httpRetryConfig),void 0!==e.websocketRetryConfig&&qN(e.websocketRetryConfig)}(e),(cN(16,0,!0)||dN(16,0,!0))&&("vp9"===e.codec&&(e.codec="vp8",SL.debug("browser not support vp9, force use vp8")),VP("UNSUPPORTED_VIDEO_CODEC",["vp9"])),void 0===e.audioCodec&&(e.audioCodec="opus");const r=new yoe(voe(voe({forceWaitGatewayResponse:!0},e),{},{role:Ui(i=["rtc","p2p"]).call(i,e.mode)?"host":e.role||"audience"}),t);return n.onSuccess(),Ote((()=>wte.onCreateClient())),r}catch(e){throw n.onError(e),e}}function boe(){let e=!1;const t=GO();return(t.name===xO.CHROME&&Number(t.version)>=58&&(!XO()||function(){const e=GO();if(YO()){if(e.os===VO.MAC_OS)return!0;if(e.os===VO.IOS){const e=BO.os.version&&BO.os.version.split(".");if(e&&14===Number(e[0])&&e[1]&&Number(e[1])>=3)return!0;if(e&&Number(e[0])>14)return!0}}return!1}())||t.name===xO.FIREFOX&&Number(t.version)>=56||t.name===xO.OPERA&&Number(t.version)>=45||t.name===xO.SAFARI&&Number(t.version)>=11||"WebKit"===t.name&&(eN()||EN())&&t.osVersion&&Number(t.osVersion.split(".")[0])>=11||mN()||GO().name===xO.QQ)&&(e=!0),e}class Ioe{constructor(e,t){zA(this,"id",0),zA(this,"element",void 0),zA(this,"peerPair",void 0),zA(this,"context",void 0),zA(this,"audioPlayerElement",void 0),zA(this,"audioTrack",void 0),Ioe.count+=1,this.id=Ioe.count,this.element=e,this.context=t}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const t=document.createElement("audio");t.srcObject=new MediaStream([e.track]),t.play(),this.audioPlayerElement=t}}async switchSdp(){if(!this.peerPair)return;const e=async(e,t)=>{const n="offer"===t?await e.createOffer():await e.createAnswer();return await e.setLocalDescription(n),"complete"===e.iceGatheringState?e.localDescription:new cp((t=>{e.onicegatheringstatechange=()=>{"complete"===e.iceGatheringState&&t(e.localDescription)}}))},t=async(e,t)=>await e.setRemoteDescription(t);try{const n=await e(this.peerPair[0],"offer");await t(this.peerPair[1],n);const i=await e(this.peerPair[1],"answer");await t(this.peerPair[0],i)}catch(e){throw new YL(wN.LOCAL_AEC_ERROR,e.toString()).print()}}async getTracksFromMediaElement(e){if(this.audioTrack)return this.audioTrack;let t;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),t=this.context.createMediaStreamDestination();this.context.createMediaElementSource(e).connect(t)}catch(e){throw new YL(wN.LOCAL_AEC_ERROR,e.toString()).print()}if(!t){throw new YL(wN.LOCAL_AEC_ERROR,"no dest node when local aec").print()}const n=t.stream.getAudioTracks()[0];return this.audioTrack=n,n}getElement(){return this.element}async startEchoCancellation(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,t=await this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(t),await this.switchSdp()}close(){SL.debug("close echo cancellation unit, id is",this.id),this.audioPlayerElement&&this.audioPlayerElement.pause(),this.peerPair&&this.peerPair.forEach((e=>{e.close()})),this.peerPair=void 0,this.audioPlayerElement=void 0}}var Aoe,woe;zA(Ioe,"count",0);const Ooe=window.AudioContext||window.webkitAudioContext;const Noe=new(Aoe=KL({report:HL}),Zx((woe=class{constructor(){zA(this,"units",[]),zA(this,"context",void 0)}processExternalMediaAEC(e){if(!this._doesEnvironmentNeedAEC())return SL.debug("the system does not need to process local aec"),-1;this.context||(this.context=new Ooe);let t=this.units.find((t=>t&&t.getElement()===e));return t||(t=new Ioe(e,this.context),this.units.push(t)),t.startEchoCancellation(),SL.debug("start processing local audio echo cancellation, id is",t.id),t.id}_doesEnvironmentNeedAEC(){return GO().name!==xO.SAFARI}}).prototype,"processExternalMediaAEC",[Aoe],Object.getOwnPropertyDescriptor(woe.prototype,"processExternalMediaAEC"),woe.prototype),woe);function Doe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Poe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Doe(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Doe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const Loe=window||document;function koe(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!Loe)return;const n=jae._cspEventHandlerPointer;if(n&&t)return void console.error(n,t);const i=e=>{if(!(e&&e.blockedURI&&(jae.onSecurityPolicyViolation||jae.getListeners(JF.SECURITY_POLICY_VIOLATION).length>0)))return;const t=e.blockedURI;xP("CSP_DETECTED_HOSTNAME_LIST").some((e=>Ui(t).call(t,e)))&&(jae.onSecurityPolicyViolation&&"function"==typeof jae.onSecurityPolicyViolation&&jae.onSecurityPolicyViolation(e),jae.getListeners(JF.SECURITY_POLICY_VIOLATION).length>0&&jae.safeEmit(JF.SECURITY_POLICY_VIOLATION,e))};n&&Loe.removeEventListener("securitypolicyviolation",n),(t||e&&"function"==typeof e||jae.getListeners(JF.SECURITY_POLICY_VIOLATION).length>0)&&Loe.addEventListener("securitypolicyviolation",i),jae._cspEventHandlerPointer=i}var Moe=function(e){return e[e.ONE_BYTE=0]="ONE_BYTE",e[e.TWO_BYTE=1]="TWO_BYTE",e}(Moe||{});class Uoe{constructor(){zA(this,"_sequence",0),zA(this,"_startTime",Date.now()),zA(this,"isUseOneByte",!0)}get startTime(){const e=Date.now()-this._startTime;return e<Math.pow(2,16)?e:(this._startTime+=Math.pow(2,16),this.startTime)}get sequence(){return this._sequence<Math.pow(2,32)?this._sequence++:(this._sequence-=Math.pow(2,32),this.sequence)}serialize(e){const t={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const n=new Uint8Array(4);n.set([1,0,0,0]);const i={id:0,length:4,data:n.buffer},r={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[i]};t.commonPacketHeader.extension=1,t.extension=r,t.payload=this.compress(e),t.commonPacketHeader.length=8+(t.extension.length+2)+t.payload.byteLength}else t.commonPacketHeader.length=8+t.payload.byteLength;xP("SHOW_DATASTREAM2_LOG")&&SL.debug("send data header: ".concat(JSON.stringify(t.commonPacketHeader)));const n=new ArrayBuffer(t.commonPacketHeader.length),i=new Uint8Array(n),r=new DataView(n);let o=0;if(r.setUint16(o,t.commonPacketHeader.extension<<15|t.commonPacketHeader.reserved<<14|t.commonPacketHeader.length,!0),o+=2,r.setUint32(o,t.commonPacketHeader.sequence,!0),o+=4,r.setUint16(o,t.commonStreamHeader,!0),o+=2,t.extension){const e=this.serializeExtension(t.extension);i.set(new Uint8Array(e),o),o+=e.byteLength}if(i.set(new Uint8Array(t.payload),o),o+=t.payload.byteLength,o!==t.commonPacketHeader.length)throw Error("serialize error!");return n}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const t=new DataView(e);let n=0;const i=t.getUint16(n,!0);n+=2;const r={length:16383&i,reserved:(16384&i)>>14,extension:(32768&i)>>15,sequence:t.getUint16(n+2,!0)<<16|t.getUint16(n,!0)};let o,s;if(n+=4,xP("SHOW_DATASTREAM2_LOG")&&SL.debug("receive data header: ".concat(JSON.stringify(r))),t.getUint16(n,!0),n+=2,r.extension){s=this.deserializeExtension(e.slice(n)),n+=2+s.length,o=e.slice(n);let t=!1;if(s.datas.length>0){const e=s.datas.find((e=>0===e.id));if(e){t=1==(1&new DataView(e.data).getUint32(0,!0))}}o=t?this.decompress(o):o}else o=e.slice(8);return o}serializeExtension(e){const t=e.profile,n=e.length,i=e.datas,r=new ArrayBuffer(n+2),o=new Uint8Array(r),s=new DataView(r);let a=0;if(s.setUint8(a++,t),s.setUint8(a++,n),i.forEach((e=>{t?(s.setUint8(a++,e.id),s.setUint8(a++,e.length),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength):(s.setUint8(a++,e.id|e.length<<4),o.set(new Uint8Array(e.data),a),a+=e.data.byteLength)})),a!==n+2)throw Error("serialize extension error, is ".concat(a,"!==").concat(n+2));return r}deserializeExtension(e){const t=new DataView(e);let n=0;const i=t.getUint8(n);n++;const r=t.getUint8(n);n++;const o=i===Moe.TWO_BYTE,s=[],a=new DataView(e,2);let c=0;for(;c<r;){let e=0,t=0,n=new ArrayBuffer(0);o?(e=a.getUint8(c),c++,t=a.getUint8(c),c++):(e=15&a.getUint8(c),t=a.getUint8(c)>>4,c++),t>0&&(n=a.buffer.slice(c+2,c+2+t),c+=n.byteLength),s.push({id:e,length:t,data:n})}if(c!==r)throw Error("parse error");return{profile:i,length:r,datas:s}}decompress(e){return KW(new Uint8Array(e))}compress(e){return GW(new Uint8Array(e))}}const Voe={name:"DataStream",create:(e,t)=>{const n=t?new GV(e):new WV(e);return n.useDataStream(new Uoe),n}};class xoe extends YN{constructor(e,t,n){super(),zA(this,"ws",void 0),zA(this,"requestId",1),zA(this,"heartBeatTimer",void 0),zA(this,"joinInfo",void 0),zA(this,"clientId",void 0),zA(this,"onOpen",(()=>{this.emit("open"),this.startHeartBeatCheck()})),zA(this,"onClose",(e=>{this.emit("close"),this.dispose()})),zA(this,"onMessage",(e=>{const t=JSON.parse(e.data);if(!t||"serverResponse"!==t.command||!t.requestId)return t&&"serverStatus"===t.command&&t.serverStatus&&t.serverStatus.command?(this.emit("status",t.serverStatus),void this.emit(t.serverStatus.command,t.serverStatus)):void 0;this.emit("req_".concat(t.requestId),t)})),this.joinInfo=e,this.clientId=t,this.ws=new gB("cross-channel-".concat(this.clientId),n),this.ws.on(cF.RECONNECTING,(()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")})),this.ws.on(cF.CONNECTED,this.onOpen),this.ws.on(cF.ON_MESSAGE,this.onMessage),this.ws.on(cF.CLOSED,this.onClose)}isConnect(){return"connected"===this.ws.state}sendMessage(e){const t=this.requestId++;return e.requestId=t,e.seq=t,this.ws.sendMessage(e),t}waitStatus(e){return new cp(((t,n)=>{const i=window.setTimeout((()=>{n(new YL(wN.TIMEOUT,"wait status timeout, status: ".concat(e)))}),5e3);this.once(e,(r=>{window.clearTimeout(i),r.state&&0!==r.state?n(new YL(wN.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):t(void 0)})),this.once("dispose",(()=>{window.clearTimeout(i),n(new YL(wN.WS_ABORT))}))}))}async request(e){if("closed"===this.ws.state)throw new YL(wN.WS_DISCONNECT);const t=()=>new cp(((e,t)=>{this.ws.once(cF.CLOSED,(()=>t(new YL(wN.WS_ABORT)))),this.ws.once(cF.CONNECTED,e)}));"connected"!==this.ws.state&&await t();const n=this.sendMessage(e),i=new cp(((e,t)=>{const i=()=>{t(new YL(wN.WS_ABORT))};this.ws.once(cF.RECONNECTING,i),this.ws.once(cF.CLOSED,i),this.once("req_".concat(n),e),LD(3e3).then((()=>{this.removeAllListeners("req_".concat(n)),this.ws.off(cF.RECONNECTING,i),this.ws.off(cF.CLOSED,i),t(new YL(wN.TIMEOUT,"cross channel ws request timeout"))}))})),r=await i;if(!r||200!==r.code)throw new YL(wN.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(r)));return r}async connect(e){this.ws.removeAllListeners(cF.REQUEST_NEW_URLS),this.ws.on(cF.REQUEST_NEW_URLS,(t=>{t(e)})),await this.ws.init(e)}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const t=this.requestId++;return e.requestId=t,this.ws.sendMessage(e),t}startHeartBeatCheck(){this.heartBeatTimer&&window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=window.setInterval((()=>{this.sendPing({command:"ping",appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sid:this.joinInfo.sid,ts:+new Date,requestId:0})}),3e3)}clearHeartBeatCheck(){window.clearInterval(this.heartBeatTimer),this.heartBeatTimer=void 0}}class Foe extends YN{set state(e){e!==this._state&&(e!==vF.RELAY_STATE_FAILURE&&(this.errorCode=yF.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,t,n,i,r){super(),zA(this,"joinInfo",void 0),zA(this,"sid",void 0),zA(this,"clientId",void 0),zA(this,"cancelToken",DO.CancelToken.source()),zA(this,"workerToken",void 0),zA(this,"requestId",0),zA(this,"signal",void 0),zA(this,"prevChannelMediaConfig",void 0),zA(this,"httpRetryConfig",void 0),zA(this,"_resolution",void 0),zA(this,"_state",vF.RELAY_STATE_IDLE),zA(this,"errorCode",yF.RELAY_OK),zA(this,"onStatus",(e=>{SL.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(e))),e&&e.command&&("onAudioPacketReceived"===e.command&&this.emit("event",RF.PACKET_RECEIVED_AUDIO_FROM_SRC),"onVideoPacketReceived"===e.command&&this.emit("event",RF.PACKET_RECEIVED_VIDEO_FROM_SRC),"onSrcTokenPrivilegeDidExpire"===e.command&&(this.errorCode=yF.SRC_TOKEN_EXPIRED,this.state=vF.RELAY_STATE_FAILURE),"onDestTokenPrivilegeDidExpire"===e.command&&(this.errorCode=yF.DEST_TOKEN_EXPIRED,this.state=vF.RELAY_STATE_FAILURE))})),zA(this,"onReconnect",(async()=>{SL.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",RF.NETWORK_DISCONNECTED),this.state=vF.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch((e=>{this.state!==vF.RELAY_STATE_IDLE&&(SL.error("auto restart channel media relay failed",e.toString()),this.errorCode=yF.SERVER_CONNECTION_LOST,this.state=vF.RELAY_STATE_FAILURE)}))})),this.joinInfo=e,this.clientId=t,this.sid=MD(),this.signal=new xoe(this.joinInfo,this.clientId,n),this.httpRetryConfig=i,this._resolution=r}async startChannelMediaRelay(e){if(this.state!==vF.RELAY_STATE_IDLE)throw new YL(wN.INVALID_OPERATION);this.state=vF.RELAY_STATE_CONNECTING,await this.connect(),SL.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{await this.sendStartRelayMessage(e)}catch(e){if(e.data&&e.data.serverResponse&&"SetSourceChannel"===e.data.serverResponse.command)throw new YL(wN.CROSS_CHANNEL_FAILED_JOIN_SRC);if(e.data&&e.data.serverResponse&&"SetDestChannelStatus"===e.serverResponse.command)throw new YL(wN.CROSS_CHANNEL_FAILED_JOIN_DEST);if(e.data&&e.data.serverResponse&&"StartPacketTransfer"===e.serverResponse.command)throw new YL(wN.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST);throw e}this.prevChannelMediaConfig=e}async updateChannelMediaRelay(e){if(this.state!==vF.RELAY_STATE_RUNNING)throw new YL(wN.INVALID_OPERATION);await this.sendUpdateMessage(e),this.prevChannelMediaConfig=e}async setVideoProfile(e){if(this._resolution=e,this.state!==vF.RELAY_STATE_RUNNING)throw new YL(wN.INVALID_OPERATION);const t=this.genMessage(TF.SetVideoProfile);await this.signal.request(t),SL.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))}async stopChannelMediaRelay(){await this.sendStopRelayMessage(),SL.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=vF.RELAY_STATE_IDLE,this.dispose()}dispose(){SL.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=DO.CancelToken.source(),this.state=vF.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}async connect(){const e=await fte(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,await this.signal.connect(e.addressList),this.emit("event",RF.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)}async sendStartRelayMessage(e){const t=this.genMessage(TF.SetSdkProfile,e);await this.signal.request(t),SL.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const n=this.genMessage(TF.SetSourceChannel,e);await this.signal.request(n),await this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",RF.PACKET_JOINED_SRC_CHANNEL),SL.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const i=this.genMessage(TF.SetSourceUserId,e);await this.signal.request(i),SL.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const r=this.genMessage(TF.SetDestChannel,e);await this.signal.request(r),await this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",RF.PACKET_JOINED_DEST_CHANNEL),SL.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const o=this.genMessage(TF.StartPacketTransfer,e);await this.signal.request(o),this.emit("event",RF.PACKET_SENT_TO_DEST_CHANNEL),this.state=vF.RELAY_STATE_RUNNING,SL.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)}async sendUpdateMessage(e){const t=this.genMessage(TF.UpdateDestChannel,e);await this.signal.request(t),this.emit("event",RF.PACKET_UPDATE_DEST_CHANNEL),SL.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))}async sendStopRelayMessage(){const e=this.genMessage(TF.StopPacketTransfer);await this.signal.request(e),SL.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))}genMessage(e,t){const n=[],i=[],r=[];this.requestId+=1;const o={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:wP,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};"4.24.8"===o.sdkVersion&&(o.sdkVersion="0.0.1");let s=null,a=null;switch(e){case TF.SetSdkProfile:return o.clientRequest={command:"SetSdkProfile",type:"multi_channel"},o;case TF.SetSourceChannel:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new YL(wN.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceChannel",uid:"0",channelName:a.channelName,token:a.token||this.joinInfo.appId},o;case TF.SetSourceUserId:if(a=t&&t.getSrcChannelMediaInfo(),!a)throw new YL(wN.UNEXPECTED_ERROR,"can not find source config");return o.clientRequest={command:"SetSourceUserId",uid:a.uid+""},o;case TF.SetDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new YL(wN.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{n.push(e.channelName),i.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"SetDestChannel",channelName:n,uid:i,token:r},o;case TF.StartPacketTransfer:return o.clientRequest={command:"StartPacketTransfer"},o;case TF.Reconnect:return o.clientRequest={command:"Reconnect"},o;case TF.StopPacketTransfer:return o.clientRequest={command:"StopPacketTransfer"},o;case TF.UpdateDestChannel:if(s=t&&t.getDestChannelMediaInfo(),!s)throw new YL(wN.UNEXPECTED_ERROR,"can not find dest config");return s.forEach((e=>{n.push(e.channelName),i.push(e.uid+""),r.push(e.token||this.joinInfo.appId)})),o.clientRequest={command:"UpdateDestChannel",channelName:n,uid:i,token:r},o;case TF.SetVideoProfile:o.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return o}}const Boe={name:"ChannelMediaRelay",create:function(e){return new Foe(e.joinInfo,e.clientId,e.websocketRetryConfig||ZD,e.httpRetryConfig||ZD,e.resolution)}};function joe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Goe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?joe(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):joe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class Woe extends YN{constructor(e,t,n,i){super(),zA(this,"spec",void 0),zA(this,"token",void 0),zA(this,"websocket",void 0),zA(this,"pingpongTimer",void 0),zA(this,"reconnectMode","retry"),zA(this,"serviceMode",void 0),zA(this,"reqId",0),zA(this,"commandReqId",0),zA(this,"handleWebSocketOpen",(()=>{this.reconnectMode="retry",this.startPingPong()})),zA(this,"handleWebSocketMessage",(e=>{if(!e.data)return;const t=JSON.parse(e.data);t.requestId?this.emit("@".concat(t.requestId,"-").concat(t.sid),t):(HL.workerEvent(this.spec.sid,{actionType:"status",serverCode:t.code,workerType:this.serviceMode===uF.TRANSCODE?1:2}),this.emit(mF.PUBLISH_STREAM_STATUS,t))})),this.spec=t,this.token=e,this.serviceMode=i,this.websocket=new gB("live-streaming",n),this.websocket.on(cF.CONNECTED,this.handleWebSocketOpen),this.websocket.on(cF.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(cF.REQUEST_NEW_URLS,((e,t)=>{dD(this,mF.REQUEST_NEW_ADDRESS).then(e).catch(t)})),this.websocket.on(cF.RECONNECTING,(()=>{this.websocket.reconnectMode=this.reconnectMode}))}init(e){return this.websocket.init(e)}async request(e,t,n,i){this.reqId+=1,"request"===e&&(this.commandReqId+=1);const r=this.commandReqId,o=this.reqId;if(!o||!this.websocket)throw new YL(wN.UNEXPECTED_ERROR);const s=Goe({command:e,sdkVersion:"4.24.8"===wP?"0.0.1":wP,seq:o,requestId:o,allocate:n,cname:this.spec.cname,appId:this.spec.appId,sid:this.spec.sid,uid:this.spec.uid.toString(),ts:Math.floor(Date.now()/1e3)},t);if("closed"===this.websocket.state)throw new YL(wN.WS_DISCONNECT);const a=()=>new cp(((e,t)=>{this.websocket.once(cF.CLOSED,(()=>t(new YL(wN.WS_ABORT)))),this.websocket.once(cF.CONNECTED,e)}));"connected"!==this.websocket.state&&await a(),s.clientRequest&&(s.clientRequest.workerToken=this.token);const c=new cp(((e,t)=>{const n=()=>{t(new YL(wN.WS_ABORT))};this.websocket.once(cF.RECONNECTING,n),this.websocket.once(cF.CLOSED,n),this.once("@".concat(o,"-").concat(this.spec.sid),(t=>{e(t)}))}));i&&HL.workerEvent(this.spec.sid,Goe(Goe({},i),{},{requestId:r,actionType:"request",payload:JSON.stringify(t.clientRequest),serverCode:0,code:0}));const d=Date.now();this.websocket.sendMessage(s);let l=null;try{l=await c}catch(i){if("closed"===this.websocket.state)throw i;return await a(),await this.request(e,t,n)}return i&&HL.workerEvent(this.spec.sid,Goe(Goe({},i),{},{requestId:r,actionType:"response",payload:JSON.stringify(l.serverResponse),serverCode:l.code,success:200===l.code,responseTime:Date.now()-d})),200!==l.code&&this.handleResponseError(l),l}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e="4.24.8"===wP?"0.0.1":wP;this.reqId+=1,"connected"===this.websocket.state?(this.websocket.sendMessage({command:"request",appId:this.spec.appId,cname:this.spec.cname,uid:this.spec.uid.toString(),sdkVersion:e,sid:this.spec.sid,seq:this.reqId,ts:Math.floor(Date.now()/1e3),requestId:this.reqId,clientRequest:{command:"DestroyWorker"}}),this.websocket.close(!1,!0)):this.websocket.close(!1),this.pingpongTimer&&(window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0)}handleResponseError(e){switch(e.code){case gF.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void SL.warning("live stream response already exists stream");case gF.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case gF.LIVE_STREAM_RESPONSE_BAD_STREAM:case gF.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new YL(wN.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case gF.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if("UnpublishStream"===e.serverResponse.command)return;throw new YL(wN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case gF.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new YL(wN.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case gF.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const t=new YL(wN.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(mF.WARNING,t,e.serverResponse.url)}case gF.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const t=new YL(wN.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(mF.WARNING,t,e.serverResponse.url)}case gF.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new YL(wN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case gF.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new YL(wN.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case gF.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const t=new YL(wN.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(mF.WARNING,t,e.serverResponse.url)}case gF.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new YL(wN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case gF.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new YL(wN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case gF.LIVE_STREAM_RESPONSE_WORKER_LOST:case gF.LIVE_STREAM_RESPONSE_WORKER_QUIT:if("UnpublishStream"===e.serverResponse.command)return;throw new YL(wN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case gF.ERROR_FAIL_SEND_MESSAGE:if("UnpublishStream"===e.serverResponse.command)return;if("UpdateTranscoding"===e.serverResponse.command||"ControlStream"===e.serverResponse.command)return new YL(wN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new YL(wN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case gF.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case gF.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case gF.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case gF.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new YL(wN.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval((()=>{"connected"===this.websocket.state&&this.request("ping",{}).catch(UD)}),6e3)}}function Koe(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Hoe(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Koe(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Koe(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class Yoe extends YN{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:ZD,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:ZD;super(),zA(this,"onLiveStreamWarning",void 0),zA(this,"onLiveStreamError",void 0),zA(this,"spec",void 0),zA(this,"retryTimeout",1e4),zA(this,"connection",void 0),zA(this,"httpRetryConfig",void 0),zA(this,"wsRetryConfig",void 0),zA(this,"streamingTasks",new Map),zA(this,"isStartingStreamingTask",!1),zA(this,"taskMutex",new JD("live-streaming")),zA(this,"cancelToken",DO.CancelToken.source()),zA(this,"transcodingConfig",void 0),zA(this,"uapResponse",void 0),zA(this,"lastTaskId",1),zA(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=n,this.wsRetryConfig=t}async setTranscodingConfig(e){const t=Hoe(Hoe({},EF),e);66!==t.videoCodecProfile&&77!==t.videoCodecProfile&&100!==t.videoCodecProfile&&(SL.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(t.videoCodecProfile," -> 100")),t.videoCodecProfile=100),t.transcodingUsers||(t.transcodingUsers=t.userConfigs),t.transcodingUsers&&(t.transcodingUsers=t.transcodingUsers.map((e=>Hoe(Hoe(Hoe({},hF),e),{},{zOrder:e.zOrder?e.zOrder+1:1})))),function(e){UN(e.width)||PN(e.width,"config.width",0,1e4),UN(e.height)||PN(e.height,"config.height",0,1e4),UN(e.videoBitrate)||PN(e.videoBitrate,"config.videoBitrate",1,1e6),UN(e.videoFrameRate)||PN(e.videoFrameRate,"config.videoFrameRate"),UN(e.lowLatency)||NN(e.lowLatency,"config.lowLatency"),UN(e.audioSampleRate)||DN(e.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),UN(e.audioBitrate)||PN(e.audioBitrate,"config.audioBitrate",1,128),UN(e.audioChannels)||DN(e.audioChannels,"config.audioChannels",[1,2,3,4,5]),UN(e.videoGop)||PN(e.videoGop,"config.videoGop"),UN(e.videoCodecProfile)||DN(e.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),UN(e.userCount)||PN(e.userCount,"config.userCount",0,17),UN(e.backgroundColor)||PN(e.backgroundColor,"config.backgroundColor",0,16777215),UN(e.userConfigExtraInfo)||kN(e.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),e.transcodingUsers&&!UN(e.transcodingUsers)&&(MN(e.transcodingUsers,"config.transcodingUsers"),e.transcodingUsers.forEach(((e,t)=>{lF(e.uid),UN(e.x)||PN(e.x,"transcodingUser[".concat(t,"].x"),0,1e4),UN(e.y)||PN(e.y,"transcodingUser[".concat(t,"].y"),0,1e4),UN(e.width)||PN(e.width,"transcodingUser[".concat(t,"].width"),0,1e4),UN(e.height)||PN(e.height,"transcodingUser[".concat(t,"].height"),0,1e4),UN(e.zOrder)||PN(e.zOrder-1,"transcodingUser[".concat(t,"].zOrder"),0,100),UN(e.alpha)||PN(e.alpha,"transcodingUser[".concat(t,"].alpha"),0,1,!1)}))),UN(e.watermark)||_F(e.watermark,"watermark"),UN(e.backgroundImage)||_F(e.backgroundImage,"backgroundImage"),e.images&&!UN(e.images)&&(MN(e.images,"config.images"),e.images.forEach(((e,t)=>{_F(e,"images[".concat(t,"]"))})))}(t);const n=[];t.images&&n.push(...t.images.map((e=>Hoe(Hoe(Hoe({},pF),e),{},{zOrder:255})))),t.backgroundImage&&(n.push(Hoe(Hoe(Hoe({},pF),t.backgroundImage),{},{zOrder:0})),delete t.backgroundImage),t.watermark&&(n.push(Hoe(Hoe(Hoe({},pF),t.watermark),{},{zOrder:255})),delete t.watermark),t.images=n,t.transcodingUsers&&(t.userConfigs=t.transcodingUsers.map((e=>Hoe({},e))),t.userCount=t.transcodingUsers.length,delete t.transcodingUsers);const i=(t.userConfigs||[]).map((e=>"number"==typeof e.uid?cp.resolve(e.uid):lte(e.uid,this.spec,this.cancelToken.token,this.httpRetryConfig)));if((await cp.all(i)).forEach(((e,n)=>{t.userConfigs&&t.userConfigs[n]&&(t.userConfigs[n].uid=e)})),this.transcodingConfig=t,this.connection)try{var r;const e=await this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(fp(r=this.streamingTasks).call(r)).map((e=>e.taskId)).join("#")});SL.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(e.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(e){if(!e.data||!e.data.retry)throw e;e.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach((t=>{SL.warning("[".concat(this.spec.clientId,"] live streaming receive error"),e.toString(),"try to republish",t.url),this.startLiveStreamingTask(t.url,t.mode,e).then((()=>{SL.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(t.url," success"))})).catch((e=>{SL.error("[".concat(this.spec.clientId,"] live streaming republish failed"),t.url,e.toString()),this.onLiveStreamError&&this.onLiveStreamError(t.url,e)}))}))}}async startLiveStreamingTask(e,t,n){if(!this.transcodingConfig&&t===uF.TRANSCODE)throw new YL(wN.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const i={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};SL.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(t));const r=await this.taskMutex.lock();if(!this.connection&&n)return void r();if(this.streamingTasks.get(e)&&!n)return r(),new YL(wN.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=await this.connect(t))}catch(e){throw r(),e}switch(t){case uF.TRANSCODE:i.transcodingConfig=Hoe({},this.transcodingConfig);case uF.RAW:}this.uapResponse&&this.uapResponse.vid&&(i.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const o=this.lastTaskId++;try{const s=new cp(((t,i)=>{LD(this.retryTimeout).then((()=>{if(n)return i(n);const t=this.statusError.get(e);return t?(this.statusError.delete(e),i(t)):void 0}))})),a=await cp.race([this.connection.request("request",{clientRequest:i},!0,{url:e,command:"PublishStream",workerType:t===uF.TRANSCODE?1:2,requestByUser:!n,tid:o.toString()}),s]);this.isStartingStreamingTask=!1,SL.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(a.code)),this.streamingTasks.set(e,{clientRequest:i,mode:t,url:e,taskId:o}),r()}catch(i){if(r(),this.isStartingStreamingTask=!1,!i.data||!i.data.retry||n)throw i;return i.data.changeAddress?(this.connection.tryNextAddress(),await this.startLiveStreamingTask(e,t,i)):await this.startLiveStreamingTask(e,t,i)}}stopLiveStreamingTask(e){return new cp(((t,n)=>{const i=this.streamingTasks.get(e);if(!i||!this.connection)return new YL(wN.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const r=i.mode;i.abortTask=()=>{SL.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),t()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:i.url}},!1,{url:e,command:"UnPublishStream",workerType:r===uF.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then((n=>{SL.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(n.code)),this.streamingTasks.delete(e),0===this.streamingTasks.size&&(this.connection&&this.connection.close(),this.connection=void 0),t()})).catch(n)}))}resetAllTask(){var e;const t=Array.from(fp(e=this.streamingTasks).call(e));this.terminate();for(const e of t)this.startLiveStreamingTask(e.url,e.mode).catch((t=>{this.onLiveStreamError&&this.onLiveStreamError(e.url,t)}))}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=DO.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}async connect(e){if(this.connection)throw new YL(wN.UNEXPECTED_ERROR,"live streaming connection has already connected");const t=await dD(this,fF.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=t,this.connection=new Woe(t.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(mF.WARNING,((e,t)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e))),this.connection.on(mF.PUBLISH_STREAM_STATUS,(e=>this.handlePublishStreamServer(e))),this.connection.on(mF.REQUEST_NEW_ADDRESS,((t,n)=>{if(!this.connection)return n(new YL(wN.UNEXPECTED_ERROR,"can not get new live streaming address list"));dD(this,fF.REQUEST_WORKER_MANAGER_LIST,e).then((e=>{this.uapResponse=e,t(e.addressList)})).catch(n)})),await this.connection.init(t.addressList),this.connection}handlePublishStreamServer(e){const t=e.serverStatus&&e.serverStatus.url||"empty_url",n=this.streamingTasks.get(t),i=e.reason;switch(e.code){case gF.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case gF.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case gF.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case gF.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const i=new YL(wN.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(n)return SL.error(i.toString()),this.onLiveStreamError&&this.onLiveStreamError(t,i);if(!this.isStartingStreamingTask)return;this.statusError.set(t,i)}case gF.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const e=new YL(wN.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,i);return this.onLiveStreamWarning&&this.onLiveStreamWarning(t,e)}case gF.LIVE_STREAM_RESPONSE_WORKER_LOST:case gF.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var r;if(!this.connection)return;this.connection.tryNextAddress();const t=Array.from(fp(r=this.streamingTasks).call(r));for(const n of t)n.abortTask?n.abortTask():(SL.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",n.url),this.startLiveStreamingTask(n.url,n.mode,new YL(wN.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then((()=>{SL.debug("[".concat(this.spec.clientId,"] republish live stream success"),n.url)})).catch((e=>{SL.error(e.toString()),this.onLiveStreamError&&this.onLiveStreamError(n.url,e)})));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const Xoe={name:"LiveStreaming",create:function(e){return new Yoe(e.joinInfo,e.websocketRetryConfig||ZD,e.httpRetryConfig||ZD)}};function Joe(e){let t=ose();return function(e,t){let n=e.appId;void 0!==n&&(Sse(t,10),hse(t,n));let i=e.cid;void 0!==i&&(Sse(t,16),Sse(t,i));let r=e.cname;void 0!==r&&(Sse(t,26),hse(t,r));let o=e.deviceId;void 0!==o&&(Sse(t,34),hse(t,o));let s=e.elapse;void 0!==s&&(Sse(t,40),Tse(t,s));let a=e.fileSize;void 0!==a&&(Sse(t,48),Tse(t,ise(a)));let c=e.height;void 0!==c&&(Sse(t,56),Tse(t,ise(c)));let d=e.jpg;void 0!==d&&(Sse(t,66),Sse(t,d.length),function(e,t){let n=dse(e,t.length);e.bytes.set(t,n)}(t,d));let l=e.networkType;void 0!==l&&(Sse(t,72),Tse(t,ise(l)));let u=e.osType;void 0!==u&&(Sse(t,80),Tse(t,ise(u)));let h=e.requestId;void 0!==h&&(Sse(t,90),hse(t,h));let p=e.sdkVersion;void 0!==p&&(Sse(t,98),hse(t,p));let _=e.sequence;void 0!==_&&(Sse(t,104),Tse(t,ise(_)));let E=e.sid;void 0!==E&&(Sse(t,114),hse(t,E));let m=e.timestamp;void 0!==m&&(Sse(t,120),Tse(t,m));let f=e.uid;void 0!==f&&(Sse(t,128),Sse(t,f));let g=e.vid;void 0!==g&&(Sse(t,136),Sse(t,g));let S=e.width;void 0!==S&&(Sse(t,144),Tse(t,ise(S)));let T=e.service;void 0!==T&&(Sse(t,152),Sse(t,T));let R=e.callbackData;void 0!==R&&(Sse(t,162),hse(t,R));let v=e.jpgEncryption;void 0!==v&&(Sse(t,168),Sse(t,v));let y=e.requestType;void 0!==y&&(Sse(t,176),Sse(t,y));let C=e.scorePorn;void 0!==C&&(Sse(t,185),fse(t,C));let b=e.scoreSexy;void 0!==b&&(Sse(t,193),fse(t,b));let I=e.scoreNeutral;void 0!==I&&(Sse(t,201),fse(t,I));let A=e.scene;void 0!==A&&(Sse(t,208),Sse(t,A));let w=e.ossFilePrefix;void 0!==w&&(Sse(t,218),hse(t,w));let O=e.serviceVendor;if(void 0!==O)for(let e of O){Sse(t,226);let n=ose();qoe(e,n),Sse(t,n.limit),pse(t,n),sse(n)}}(e,t),function(e){let t=e.bytes,n=e.limit;return t.length===n?t:t.subarray(0,n)}(t)}function zoe(e){return function(e){let t={};e:for(;!cse(e);){let n=gse(e);switch(n>>>3){case 0:break e;case 1:t.code=gse(e);break;case 2:t.msg=use(e,gse(e));break;case 3:{let n=Qoe(e);t.data=Zoe(e),e.limit=n;break}default:$oe(e,7&n)}}return t}({bytes:t=e,offset:0,limit:t.length});var t}function Zoe(e){let t={};e:for(;!cse(e);){let n=gse(e);switch(n>>>3){case 0:break e;case 1:t.requestId=use(e,gse(e));break;case 2:t.requestType=gse(e)>>>0;break;case 3:t.scorePorn=mse(e);break;case 4:t.scoreSexy=mse(e);break;case 5:t.scoreNeutral=mse(e);break;case 6:t.requestScene=gse(e)>>>0;break;case 7:t.scene=gse(e)>>>0;break;default:$oe(e,7&n)}}return t}function qoe(e,t){let n=e.service;void 0!==n&&(Sse(t,8),Sse(t,n));let i=e.vendor;void 0!==i&&(Sse(t,16),Sse(t,i));let r=e.token;void 0!==r&&(Sse(t,26),hse(t,r));let o=e.callbackUrl;void 0!==o&&(Sse(t,34),hse(t,o))}function Qoe(e){let t=gse(e),n=e.limit;return e.limit=e.offset+t,n}function $oe(e,t){switch(t){case 0:for(;128&_se(e););break;case 2:ase(e,gse(e));break;case 5:ase(e,4);break;case 1:ase(e,8);break;default:throw new Error("Unimplemented type: "+t)}}let ese=new Float32Array(1);new Uint8Array(ese.buffer);let tse=new Float64Array(1),nse=new Uint8Array(tse.buffer);function ise(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}let rse=[];function ose(){const e=rse.pop();return e?(e.offset=e.limit=0,e):{bytes:new Uint8Array(64),offset:0,limit:0}}function sse(e){rse.push(e)}function ase(e,t){if(e.offset+t>e.limit)throw new Error("Skip past limit");e.offset+=t}function cse(e){return e.offset>=e.limit}function dse(e,t){let n=e.bytes,i=e.offset,r=e.limit,o=i+t;if(o>n.length){let t=new Uint8Array(2*o);t.set(n),e.bytes=t}return e.offset=o,o>r&&(e.limit=o),i}function lse(e,t){let n=e.offset;if(n+t>e.limit)throw new Error("Read past limit");return e.offset+=t,n}function use(e,t){let n=lse(e,t),i=String.fromCharCode,r=e.bytes,o="�",s="";for(let e=0;e<t;e++){let a,c,d,l,u=r[e+n];0==(128&u)?s+=i(u):192==(224&u)?e+1>=t?s+=o:(a=r[e+n+1],128!=(192&a)?s+=o:(l=(31&u)<<6|63&a,l<128?s+=o:(s+=i(l),e++))):224==(240&u)?e+2>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],32896!=(49344&(a|c<<8))?s+=o:(l=(15&u)<<12|(63&a)<<6|63&c,l<2048||l>=55296&&l<=57343?s+=o:(s+=i(l),e+=2))):240==(248&u)?e+3>=t?s+=o:(a=r[e+n+1],c=r[e+n+2],d=r[e+n+3],8421504!=(12632256&(a|c<<8|d<<16))?s+=o:(l=(7&u)<<18|(63&a)<<12|(63&c)<<6|63&d,l<65536||l>1114111?s+=o:(l-=65536,s+=i(55296+(l>>10),56320+(1023&l)),e+=3))):s+=o}return s}function hse(e,t){let n=t.length,i=0;for(let e=0;e<n;e++){let r=t.charCodeAt(e);r>=55296&&r<=56319&&e+1<n&&(r=(r<<10)+t.charCodeAt(++e)-56613888),i+=r<128?1:r<2048?2:r<65536?3:4}Sse(e,i);let r=dse(e,i),o=e.bytes;for(let e=0;e<n;e++){let i=t.charCodeAt(e);i>=55296&&i<=56319&&e+1<n&&(i=(i<<10)+t.charCodeAt(++e)-56613888),i<128?o[r++]=i:(i<2048?o[r++]=i>>6&31|192:(i<65536?o[r++]=i>>12&15|224:(o[r++]=i>>18&7|240,o[r++]=i>>12&63|128),o[r++]=i>>6&63|128),o[r++]=63&i|128)}}function pse(e,t){let n=dse(e,t.limit),i=e.bytes,r=t.bytes;for(let e=0,o=t.limit;e<o;e++)i[e+n]=r[e]}function _se(e){return e.bytes[lse(e,1)]}function Ese(e,t){let n=dse(e,1);e.bytes[n]=t}function mse(e){let t=lse(e,8),n=e.bytes;return nse[0]=n[t++],nse[1]=n[t++],nse[2]=n[t++],nse[3]=n[t++],nse[4]=n[t++],nse[5]=n[t++],nse[6]=n[t++],nse[7]=n[t++],tse[0]}function fse(e,t){let n=dse(e,8),i=e.bytes;tse[0]=t,i[n++]=nse[0],i[n++]=nse[1],i[n++]=nse[2],i[n++]=nse[3],i[n++]=nse[4],i[n++]=nse[5],i[n++]=nse[6],i[n++]=nse[7]}function gse(e){let t,n=0,i=0;do{t=_se(e),n<32&&(i|=(127&t)<<n),n+=7}while(128&t);return i}function Sse(e,t){for(t>>>=0;t>=128;)Ese(e,127&t|128),t>>>=7;Ese(e,t)}function Tse(e,t){let n=t.low>>>0,i=(t.low>>>28|t.high<<4)>>>0,r=t.high>>>24,o=0===r?0===i?n<16384?n<128?1:2:n<1<<21?3:4:i<16384?i<128?5:6:i<1<<21?7:8:r<128?9:10,s=dse(e,o),a=e.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=9!==o?128|r:127&r;case 8:a[s+7]=8!==o?i>>>21|128:i>>>21&127;case 7:a[s+6]=7!==o?i>>>14|128:i>>>14&127;case 6:a[s+5]=6!==o?i>>>7|128:i>>>7&127;case 5:a[s+4]=5!==o?128|i:127&i;case 4:a[s+3]=4!==o?n>>>21|128:n>>>21&127;case 3:a[s+2]=3!==o?n>>>14|128:n>>>14&127;case 2:a[s+1]=2!==o?n>>>7|128:n>>>7&127;case 1:a[s]=1!==o?128|n:127&n}}function Rse(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}const vse=new Map([["moderation",1],["supervise",2]]);class yse extends YN{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const t=this._connectionState;this._connectionState=e,this.emit(HF.CONNECTION_STATE_CHANGE,t,e)}get inspectType(){return this._inspectType}set inspectType(e){var t;this._inspectMode=sr(t=e.map((e=>vse.get(e)||0))).call(t,((e,t)=>e+t)),this._inspectType=e}get quality(){return this._quality}set quality(e){this._quality=e>1?1:e<.1?.1:e,this.qualityTimer&&(window.clearTimeout(this.qualityTimer),this.qualityTimer=null),this._quality>=1||(this.qualityTimer=window.setTimeout((()=>{this.quality=this._quality/this.qualityRatio}),6e4))}constructor(e){super(),zA(this,"name","AgoraRTCVideoContentInspect"),zA(this,"_connectionState",WF.CONNECTING),zA(this,"_innerConnectionState",void 0),zA(this,"sequence",0),zA(this,"inspectStartTime",void 0),zA(this,"workerManagerConnection",void 0),zA(this,"workerConnection",void 0),zA(this,"workerMessageLengthLimit",void 0),zA(this,"inspectIntervalMinimum",void 0),zA(this,"qualityRatio",void 0),zA(this,"_connectInfo",void 0),zA(this,"_cancelTokenSource",DO.CancelToken.source()),zA(this,"_retryConfig",void 0),zA(this,"wmSequence",0),zA(this,"inspectInterval",void 0),zA(this,"inspectTimer",null),zA(this,"ossFilePrefix",void 0),zA(this,"extraInfo",void 0),zA(this,"_inspectType",void 0),zA(this,"_inspectMode",void 0),zA(this,"_quality",1),zA(this,"qualityTimer",null),zA(this,"_inspectId",void 0),zA(this,"_needWorkUrlOnly",!1),zA(this,"inspectImage",(()=>{if(this.connectionState!==WF.CONNECTED)throw new YL(wN.OPERATION_ABORTED,"content inspect service connection status is ".concat(this.connectionState));this.inspectTimer&&(window.clearInterval(this.inspectTimer),this.inspectTimer=null),this.inspectTimer=window.setInterval((()=>{this.connectionState===WF.CONNECTED?this.requestToInspectImage():SL.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)}),this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()})),this._inspectId=kD(5,"inspect-"),this.workerMessageLengthLimit=xP("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=xP("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=xP("VIDEO_INSPECT_QUALITY_RATIO"),this.inspectInterval=e.interval,this.ossFilePrefix=e.ossFilePrefix,this.extraInfo=e.extraInfo,this.inspectType=e.inspectType,this.inspectStartTime=Number(Date.now()),this.workerManagerConnection=new gB("worker-manager-"+this._inspectId,ZD),this.on(HF.STATE_CHANGE,((e,t)=>{this._innerConnectionState=e,SL.debug("[".concat(this._inspectId,"] Inspect operation :").concat(KF[e]," ").concat(t||""))})),this.handleWorkerManagerEvents(),this.workerConnection=new gB("worker-"+this._inspectId,ZD),this.handleWorkerEvents()}async init(e,t){this.emit(HF.STATE_CHANGE,KF.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=t,new cp(((i,r)=>{this.on(HF.CONNECTION_STATE_CHANGE,((e,t)=>{t===WF.CONNECTED&&i()})),this.requestAP(e,n,t).then((e=>{this.connectWorkerManager(e)})).catch((e=>{r(e)}))}))}async requestAP(e,t,n){const i=xP("WEBCS_DOMAIN").map((e=>"https://".concat(e,"/api/v1"))),r=await function(e,t,n,i){let r=t.appId,o=t.areaCode,s=t.cname,a=t.sid,c=t.token,d=t.uid;ete++;const l="image_moderation_api",u={service_name:l,json_body:JSON.stringify({appId:r,areaCode:o,cname:s,command:"allocateEdge",requestId:ete,seq:ete,sid:a,token:c,ts:Date.now(),uid:d+""})};let h,p,_=e[0];return QD((async()=>{h=Date.now();const e=await Nee(_,{data:u,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(p=Date.now()-h,0!==e.code){const t=new YL(wN.UNEXPECTED_RESPONSE,"image inspect ap error, code"+e.code,{retry:!0,responseTime:p});throw SL.error(t.toString()),t}const t=JSON.parse(e.json_body);if(200!==t.code){const e=new YL(wN.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(t.code,", reason: ").concat(t.reason),{code:t.code,responseTime:p});throw SL.error(e.toString()),e}if(!t.servers||!Array.isArray(t.servers)||0===t.servers.length){const e=new YL(wN.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:t.code,responseTime:p});throw SL.error(e.toString()),e}const i=xP("VIDEO_INSPECT_WORKER_MANAGER_WSS");if(i)return{addressList:[i],workerToken:t.workerToken,vid:t.vid,responseTime:p};const r=xP("VIDEO_INSPECT_WORKER_MANAGER_HOST"),o=xP("VIDEO_INSPECT_WORKER_MANAGER_PORT"),s=t.servers.map((e=>{let t=e.address,n=e.wss;if(t&&n)return"wss://".concat(t.replace(/\./g,"-"),".").concat(r,":").concat(o||n)})).filter((e=>!!e));return{addressList:s,workerToken:t.workerToken,vid:t.vid,responseTime:p}}),((t,n)=>(HL.apworkerEvent(a,{success:!0,sc:200,serviceName:l,responseDetail:JSON.stringify(t.addressList),firstSuccess:0===n,responseTime:p,serverIp:e[n%e.length]}),!1)),((t,n)=>(HL.apworkerEvent(a,{success:!1,sc:t.data&&t.data.code||200,serviceName:l,responseTime:p,serverIp:e[n%e.length]}),!!(t.code!==wN.OPERATION_ABORTED&&t.code!==wN.UNEXPECTED_RESPONSE||t.data&&t.data.retry)&&(_=e[(n+1)%e.length],!0))),i)}(i,e,t,n);this.emit(HF.STATE_CHANGE,KF.AP_CONNECTED);const o=r.addressList;return this.wmSequence++,o}async connectWorkerManager(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];this._needWorkUrlOnly=t,this.emit(HF.STATE_CHANGE,KF.CONNECT_WORKER_MANAGER),await this.workerManagerConnection.init(e,1e4)}async connectWorker(e){await this.workerConnection.init([e])}handleWorkerManagerEvents(){this.workerManagerConnection.on(cF.CONNECTED,(async()=>{this.emit(HF.STATE_CHANGE,KF.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.24.8",sid:this._connectInfo.sid,seq:this.wmSequence,ts:Number(Date.now()),requestId:Math.floor(1e12*Math.random()),allocate:!0,clientRequest:{command:"join"}},!0)})),this.workerManagerConnection.on(cF.CLOSED,(()=>{this._innerConnectionState<KF.GET_WORKER_MANAGER_RESPONSE&&SL.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))})),this.workerManagerConnection.on(cF.FAILED,(()=>{this._innerConnectionState<KF.GET_WORKER_MANAGER_RESPONSE&&SL.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))})),this.workerManagerConnection.on(cF.RECONNECTING,(()=>{this._innerConnectionState<KF.GET_WORKER_MANAGER_RESPONSE&&SL.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))})),this.workerManagerConnection.on(cF.ON_MESSAGE,(async e=>{this.emit(HF.STATE_CHANGE,KF.GET_WORKER_MANAGER_RESPONSE);const t=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(200!==n.code)throw SL.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new YL(wN.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&t))throw SL.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new YL(wN.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const e=xP("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,i=t.replace(/:\d+\/?$/,":".concat(e));this.emit(HF.STATE_CHANGE,KF.CONNECT_WORKER,i),this._needWorkUrlOnly?this.emit(HF.REQUEST_NEW_WORKER_URL,i):await this.connectWorker(i)}})),this.workerManagerConnection.on(cF.WILL_RECONNECT,((e,t,n)=>{n(e)})),this.workerManagerConnection.on(cF.REQUEST_NEW_URLS,((e,t)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(t)}))}handleWorkerEvents(){this.workerConnection.on(cF.CONNECTED,(async()=>{this.emit(HF.STATE_CHANGE,KF.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=WF.CONNECTED})),this.workerConnection.on(cF.ON_MESSAGE,(async e=>{if(e.data instanceof ArrayBuffer){const n=zoe(new Uint8Array(e.data));if(xP("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&SL.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(n)),200===n.code){if(Array.isArray(this.inspectType)&&1===this.inspectType.length&&"supervise"===this.inspectType[0])return void this.emit(HF.INSPECT_RESULT,void 0,void 0);if(n.data&&n.data.scorePorn&&n.data.scoreSexy&&n.data.scoreNeutral){var t;const e={porn:n.data.scorePorn,sexy:n.data.scoreSexy,neutral:n.data.scoreNeutral},i=sr(t=Object.keys(e)).call(t,((t,n)=>e[t]>e[n]?t:n),"porn"),r=Object.keys(e).find((e=>e===i));this.emit(HF.INSPECT_RESULT,r)}else this.emit(HF.INSPECT_RESULT,void 0,new YL(wN.UNEXPECTED_RESPONSE,n.code+"","There is an unexpected data on message"))}else this.emit(HF.INSPECT_RESULT,void 0,new YL(wN.UNEXPECTED_RESPONSE,n.code+"",n.msg))}else SL.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(HF.INSPECT_RESULT,void 0,new YL(wN.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(cF.CLOSED,(()=>{this.connectionState=WF.CLOSED})),this.workerConnection.on(cF.FAILED,(()=>{this.connectionState=WF.CLOSED})),this.workerConnection.on(cF.RECONNECTING,(()=>{this.connectionState=this.connectionState===WF.CONNECTED?WF.RECONNECTING:WF.CONNECTING})),this.workerConnection.on(cF.WILL_RECONNECT,((e,t,n)=>{"recover"===e&&n(e),n("tryNext")})),this.workerConnection.on(cF.REQUEST_NEW_URLS,((e,t)=>{this.workerManagerConnection.close(),this.once(HF.REQUEST_NEW_WORKER_URL,(t=>{e([t])})),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then((e=>{this.connectWorkerManager(e,!0)})).catch((e=>{t(e)}))}))}async requestToInspectImage(){this.sequence++;const e=uD(this,HF.CLIENT_LOCAL_VIDEO_TRACK),t={appId:this._connectInfo.appId,cname:this._connectInfo.cname,cid:this._connectInfo.cid,sid:this._connectInfo.sid,uid:this._connectInfo.uid,vid:this._connectInfo.vid};if(e){if(!e.isPlaying)return void this.emit(HF.INSPECT_RESULT,void 0,new YL(wN.INVALID_OPERATION,"Only the track being played can be inspected"));const n=await this.generateRequestData(e,t);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(HF.INSPECT_RESULT,void 0,new YL(wN.INVALID_OPERATION,"Only the track being published can be inspected"))}async generateRequestData(e,t){let n=t.appId,i=t.cname,r=t.cid,o=t.vid,s=t.sid,a=t.uid;const c=Date.now(),d=await e.getCurrentFrameImage("image/jpeg",this.quality),l=await VM(d,n,i),u=this.sequence+"-"+r+"-"+a+"-"+c+"-"+kD(12,""),h={appId:n,cid:r,cname:i,deviceId:"",elapse:(p=Number(c-this.inspectStartTime),{low:p|=0,high:p>>31,unsigned:p>=0}),fileSize:l.byteLength,jpgEncryption:2,height:d.height,width:d.width,jpg:l,networkType:6,osType:7,requestId:u,sdkVersion:"4.24.8",sequence:this.sequence,sid:s,timestamp:Are(c),uid:a,vid:o,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var p;void 0===this.extraInfo&&delete h.callbackData,void 0===this.ossFilePrefix&&delete h.ossFilePrefix;const _=Joe(h);if(_.byteLength<this.workerMessageLengthLimit){if(xP("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const e=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Rse(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Rse(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},h);delete e.jpg,SL.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(e))}return _}{const t=this.quality*this.qualityRatio;return this.quality=t,await this.generateRequestData(e,{appId:n,cname:i,cid:r,vid:o,sid:s,uid:a})}}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=DO.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=WF.CLOSED,this.emit(HF.STATE_CHANGE,KF.CLOSED)}}const Cse={name:"ContentInspect",create:function(e){let t=e.config;return function(e){if(!e)throw new YL(wN.INVALID_PARAMS,"inspectConfig is necessary.");if(!e.inspectType||!Array.isArray(e.inspectType))throw new YL(wN.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const t=[...new Set(e.inspectType)];t.forEach((e=>{var t;if(!Ui(t=["supervise","moderation"]).call(t,e))throw new YL(wN.INVALID_PARAMS,"".concat(e," is not a valid inspect type."))})),e.inspectType=t}if(e&&e.extraInfo&&e.extraInfo.length>1024)throw new YL(wN.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(t),new yse(t)}};var bse=n($.Object.getOwnPropertySymbols),Ise=Nn,Ase=Jn.indexOf,wse=Yi,Ose=C([].indexOf),Nse=!!Ose&&1/Ose([1],1,-0)<0;Ise({target:"Array",proto:!0,forced:Nse||!wse("indexOf")},{indexOf:function(e){var t=arguments.length>1?arguments[1]:void 0;return Nse?Ose(this,e,t)||0:Ase(this,e,t)}});var Dse=ni("Array","indexOf"),Pse=l,Lse=Dse,kse=Array.prototype,Mse=function(e){var t=e.indexOf;return e===kse||Pse(kse,e)&&t===kse.indexOf?Lse:t},Use=n(Mse);function Vse(e,t){if(null==e)return{};var n,i,r=function(e,t){if(null==e)return{};var n,i,r={},o=Xx(e);for(i=0;i<o.length;i++)n=o[i],Use(t).call(t,n)>=0||(r[n]=e[n]);return r}(e,t);if(bse){var o=bse(e);for(i=0;i<o.length;i++)n=o[i],Use(t).call(t,n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}let xse=class{get localCapabilities(){return vD(this._localCapabilities)}get rtpCapabilities(){return vD(this._rtpCapabilities)}get candidates(){return vD(this._candidates)}get iceParameters(){return vD(this._iceParameters)}get dtlsParameters(){return vD(this._dtlsParameters)}constructor(e){zA(this,"sessionDesc",void 0),zA(this,"_localCapabilities",void 0),zA(this,"_rtpCapabilities",void 0),zA(this,"_candidates",void 0),zA(this,"_iceParameters",void 0),zA(this,"_dtlsParameters",void 0),zA(this,"setup",void 0),zA(this,"currentMidIndex",void 0),zA(this,"cname","o/i14u9pJrxRKAsu"),zA(this,"firefoxSsrcMidMap",new Map);const t=e=vD(e),n=t.remoteIceParameters,i=t.remoteDtlsParameters,r=t.candidates,o=t.remoteRTPCapabilities,s=t.localCapabilities,a=t.direction,c=t.setup,d=t.videoCodec,l=t.audioCodec;let u;this.setup=c,u=a===aF.RECEIVE_ONLY?zP("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"):zP("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE 0 1\na=msid-semantic: WMS\na=extmap-allow-mixed\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:0\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=recvonly\na=rtcp-mux\na=rtcp-rsize\na=mid:1\n"),this._rtpCapabilities=o,this._candidates=r,this._iceParameters=n,this._dtlsParameters=i,this._localCapabilities=s;const h=a===aF.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,p=a===aF.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,_=a===aF.RECEIVE_ONLY?o.send.videoCodecs:ree(UF.VIDEO,h,p,d),E=a===aF.RECEIVE_ONLY?o.send.audioCodecs:ree(UF.AUDIO,h,p,l);for(const e of u.mediaDescriptions)e.attributes.iceUfrag=n.iceUfrag,e.attributes.icePwd=n.icePwd,e.attributes.fingerprints=i.fingerprints,e.attributes.candidates=r,e.attributes.setup=this.setup,"application"===e.media.mediaType&&(e.attributes.sctpPort="5000"),"video"===e.media.mediaType&&(e.media.fmts=_.map((e=>e.payloadType.toString(10))),e.attributes.payloads=_,e.attributes.extmaps=h.videoExtensions),"audio"===e.media.mediaType&&(e.media.fmts=E.map((e=>e.payloadType.toString(10))),e.attributes.payloads=E,e.attributes.extmaps=h.audioExtensions,iee(e));this.sessionDesc=u,this.currentMidIndex=u.mediaDescriptions.length-1}toString(){return ZP(this.sessionDesc)}hasMid(e){return Array.isArray(e)?e.every((e=>this.hasMid(e))):this.sessionDesc.mediaDescriptions.some((t=>t.attributes.mid===e))}send(e,t,n,i,r){n=n.replace(/ /g,"-");const o=H7(t,this.cname,xP("SYNC_GROUP")?n:void 0),s=o.ssrcs,a=o.ssrcGroups,c=this.findPreloadMediaDesc(s);if(c){if($O()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,c.attributes.mid),r&&(r.twcc||r.remb)){const e=this.sessionDesc.mediaDescriptions.indexOf(c);return this.sessionDesc.mediaDescriptions[e]=this.mungSendMediaDesc(c,r),{mid:c.attributes.mid,needExchangeSDP:!0}}return{mid:c.attributes.mid,needExchangeSDP:!1}}{const t=this.findAvailableMediaIndex(e,s,i);let n;return-1===t?(n=this.createOrRecycleSendMedia(e,s,a,"sendonly",i,r),this.updateBundleMids()):(n=vD(this.sessionDesc.mediaDescriptions[t]),n.attributes.direction="sendonly",n.attributes.ssrcs=s,n.attributes.ssrcGroups=a,this.sessionDesc.mediaDescriptions[t]=this.mungSendMediaDesc(n,r)),$O()&&this.firefoxSsrcMidMap.set(s[0].ssrcId,n.attributes.mid),{needExchangeSDP:!0,mid:n.attributes.mid}}}stopSending(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>t.attributes.mid&&-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");t.forEach((e=>{e.attributes.ssrcs=[]})),this.updateBundleMids()}receive(e,t,n){const i=[];return e.forEach((e=>{const r=e._mediaStreamTrack.kind,o=this.findAvailableRecvMediaIndex(r);let s,a=!1;-1===o?(a=!0,s=this.createOrRecycleRecvMedia(e,[],"recvonly",t,n),this.updateBundleMids()):(s=vD(this.sessionDesc.mediaDescriptions[o]),s.attributes.direction="recvonly"),i.push({mid:s.attributes.mid,needCreateTransceiver:a})})),i}stopReceiving(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>-1!==e.indexOf(t.attributes.mid)));if(t.length!==e.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");t.forEach((e=>{e.media.port="0",e.attributes.direction="inactive"})),this.updateBundleMids()}addRemoteCandidate(e){const t=new RTCIceCandidate(e),n=t.foundation,i=t.protocol,r=t.address,o=t.port,s=t.type,a=t.relatedAddress,c=t.relatedPort,d=t.priority,l={foundation:null!=n?n:"",componentId:"1",transport:null!=i?i:"",priority:d?d+"":"",connectionAddress:null!=r?r:"",port:o?o+"":"",type:s?s+"":"",relAddr:null!=a?a:"",relPort:c?c+"":"",extension:{}};this.candidates.some((e=>e.priority===l.priority&&e.connectionAddress===l.connectionAddress&&e.port===l.port))||(this._candidates.push(l),this.sessionDesc.mediaDescriptions.forEach((e=>{e.attributes.candidates=this.candidates})))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(e,t,n,i,r){const o=e._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=ree(o,s,this.localCapabilities.send,o===UF.AUDIO?r:i),c=o===UF.VIDEO?s.videoExtensions:s.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:n,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(d)}};l=this.mungRecvMediaDsec(l,e);const u=this.findFirstClosedMedia(o);if(u){const e=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[e]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Ui(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="inactive"}))}unmuteRemote(e){const t=this.sessionDesc.mediaDescriptions.filter((t=>Ui(e).call(e,t.attributes.mid||"")));if(t.length!==e.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");t.forEach((e=>{e.attributes.direction="recvonly"}))}findAvailableMediaIndex(e,t,n){return this.sessionDesc.mediaDescriptions.findIndex((i=>{const r=i.media.mediaType===e&&"0"!==i.media.port&&("sendonly"===i.attributes.direction||"sendrecv"===i.attributes.direction)&&0===i.attributes.ssrcs.length;if($O()){if(r){const e=this.firefoxSsrcMidMap.get(t[0].ssrcId);return!(e||"0"!==i.attributes.mid&&"1"!==i.attributes.mid)||!(!e||e!==i.attributes.mid)}return!1}return r&&i.attributes.mid===n}))}findAvailableRecvMediaIndex(e){return this.sessionDesc.mediaDescriptions.findIndex((t=>{const n=t.media.mediaType===e&&"0"!==t.media.port&&("recvonly"===t.attributes.direction||"sendrecv"===t.attributes.direction);return"0"!==t.attributes.mid&&"1"!==t.attributes.mid&&n}))}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}restartICE(e){e=vD(e),this._iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}createOrRecycleSendMedia(e,t,n,i,r,o){const s=this.rtpCapabilities.send,a=e===UF.VIDEO?s.videoCodecs:s.audioCodecs,c=e===UF.VIDEO?s.videoExtensions:s.audioExtensions;$O()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:e,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map((e=>e.payloadType.toString(10)))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:this.iceParameters.iceUfrag,icePwd:this.iceParameters.icePwd,unrecognized:[],candidates:[],extmaps:c,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:t,ssrcGroups:n,rtcpFeedbackWildcards:[],payloads:a,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:i,rtcpMux:!0,rtcpRsize:!0,mid:r}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(e);if(l){const e=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[e]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(e,t,n){const i=vD(e);return X7(i),Y7(i,t),J7(i,t),z7(i),Z7(i,n,this.localCapabilities.send),i}mungSendMediaDesc(e,t){const n=vD(e);return Z7(n,t,this.localCapabilities.recv),iee(n),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter((e=>"0"!==e.media.port)).map((e=>e.attributes.mid))}findPreloadMediaDesc(e){return this.sessionDesc.mediaDescriptions.find((t=>{var n;return(null===(n=t.attributes)||void 0===n||null===(n=n.ssrcs[0])||void 0===n?void 0:n.ssrcId)===e[0].ssrcId}))}findFirstClosedMedia(e){return this.sessionDesc.mediaDescriptions.find((t=>$O()?"0"===t.media.port&&t.media.mediaType===e:"0"===t.media.port))}};const Fse=["sdp"];var Bse;function jse(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Gse(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?jse(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jse(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let Wse=(Bse=class e extends kF{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[]}set isInRestartIce(e){this._isInRestartIce=e}get isInRestartIce(){return this._isInRestartIce}constructor(t,n,i){super(t,n),zA(this,"direction",void 0),zA(this,"name",void 0),zA(this,"store",void 0),zA(this,"spec",void 0),zA(this,"peerConnection",void 0),zA(this,"initialOffer",void 0),zA(this,"transport",void 0),zA(this,"statsFilter",void 0),zA(this,"localCandidateCount",0),zA(this,"_isInRestartIce",!1),zA(this,"mutex",void 0),zA(this,"onLocalCandidate",void 0),zA(this,"remoteSDP",void 0),zA(this,"pendingCandidates",[]),zA(this,"localCapabilities",void 0),zA(this,"isReady",!1),zA(this,"restartCnt",0),zA(this,"curTurnServerIndex",0),this.store=n,this.spec=t,this.mutex=new JD("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t,n.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=null!=i?i:aF.SEND_ONLY,this.name=this.direction===aF.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=bP(this.peerConnection,xP("STATS_UPDATE_INTERVAL"),void 0,$O()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}async establish(e){try{const t=await $7();if(this.localCapabilities=nee(t),e){const t=e.sdp,n=Vse(e,Fse),i=function(){const e={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},t=F7(arguments.length>2?arguments[2]:void 0,arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},"sendonly"),n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(tee(t,e,"videoExtensions",n,i,r),tee(t,e,"videoCodecs",n,i,r),tee(t,e,"audioExtensions",n,i,r),tee(t,e,"audioCodecs",n,i,r),xP("RAISE_H264_BASELINE_PRIORITY")){const e=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"===e.fmtp.parameters["profile-level-id"]));if(-1!==e){const t=r.videoCodecs.findIndex((e=>e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()));if(t<e){SL.debug("raising H264 baseline profile priority");const n=r.videoCodecs[e];r.videoCodecs.splice(e,1),r.videoCodecs.splice(t,0,n)}-1!==t&&xP("FILTER_SEND_H264_BASELINE")&&(n.videoCodecs=n.videoCodecs.filter((e=>!(e.rtpMap&&"h264"===e.rtpMap.encodingName.toLocaleLowerCase()&&e.fmtp&&"42001f"!==e.fmtp.parameters["profile-level-id"]))))}}return{send:n,recv:i,sendrecv:r}}({},{},t);this.remoteSDP=new xse({remoteIceParameters:n.iceParameters,remoteDtlsParameters:n.dtlsParameters,candidates:[],remoteRTPCapabilities:i,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const r=await this.peerConnection.createAnswer();if(!r.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const o=B7(r.sdp);await this.peerConnection.setLocalDescription(r);const s=await eee({},{},r.sdp);this.localCapabilities=nee(s);const a=this.peerConnection.getTransceivers()[0];return null!=a&&a.receiver&&a.receiver.transport&&this.tryBindTransportEvents(a.receiver.transport),Gse(Gse({},o),{},{sdp:r.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const e=await this.peerConnection.createOffer();if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=B7(e.sdp);return this.initialOffer=e,Gse(Gse({},t),{},{sdp:e.sdp})}}catch(e){throw new ON(wN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");await this.peerConnection.setLocalDescription(this.initialOffer);const t=e.sdp,n=e.iceParameters,i=e.dtlsParameters,r=await eee({},{},t);this.remoteSDP=new xse({remoteIceParameters:n,remoteDtlsParameters:i,candidates:[],remoteRTPCapabilities:r,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const o=this.peerConnection.getTransceivers()[0];null!=o&&o.sender&&o.sender.transport&&this.tryBindTransportEvents(o.sender.transport)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async addRemoteCandidate(e){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach((e=>{this.peerConnection.addIceCandidate(e)})),this.pendingCandidates=[])}catch(e){throw new ON(wN.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return Ww((function*(){const r=yield Kw(i.mutex.lock("From P2PConnection.send"));try{if(!i.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=[],s=i.remoteSDP.receive(e,t,n);e.forEach(((e,t)=>{if(s[t].needCreateTransceiver){const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,{direction:"sendonly"});o.push(t),e._updateRtpTransceiver(t)}else{const n=i.peerConnection.getTransceivers().find((e=>e.mid===s[t].mid));if(!n)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(s[t].mid));o.push(n),e._updateRtpTransceiver(n)}})),$O()&&!0===xP("SIMULCAST")&&(yield Kw(i.applySimulcastForFirefox(o,e)));const a=s.map((e=>e.mid)),c=yield Kw(i.peerConnection.createOffer()),d=i.mungSendOfferSDP(c.sdp,e,a),l=zP(d),u=a.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return j7(t,xP("USE_PUB_RTX"))})),h=o.map(((e,t)=>{const n=a[t];return{localSSRC:u[t],id:n}}));yield Kw(i.peerConnection.setLocalDescription({type:"offer",sdp:d}));try{yield h}catch(e){const t=i.remoteSDP.toString();throw yield Kw(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Kw(i.peerConnection.setRemoteDescription({type:"answer",sdp:t})),yield Kw(i.stopSending(a,!0)),e}yield Kw(i.applySimulcastEncodings(o,e)),yield Kw(i.applySendEncodings(o,e));const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return null==_||_(p),yield Kw(i.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=a[t];return{localSSRC:u[t],id:n}}))}catch(e){throw e instanceof ON?e:new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{r()}}))()}async stopSending(e,t){const n=t?void 0:await this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length (".concat(t.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));t.map((e=>{var t;e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,n,i),o=r.mid;if(r.needExchangeSDP){const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer(),r=this.mungReceiveAnswerSDP(i.sdp,o,e);null==n||n(r||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:r}),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else SL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const s=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!s||null===s.mid)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,mid:s.mid,transceiver:s}}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async mockReceive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,n,i),o=r.mid;if(r.needExchangeSDP){const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","receive");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer(),r=this.mungReceiveAnswerSDP(i.sdp,o,e);null==n||n(r||""),await this.peerConnection.setLocalDescription({type:"answer",sdp:r}),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else SL.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async restartICE(t){try{if(this.store.p2pTransport===NP.Auto&&(this.store.p2pTransport=NP.SdRtn,JL().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,JL().supportPCSetConfiguration&&this.peerConnection.setConfiguration(e.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!t){this.restartCnt++,this.isReady=!1;const e=await this.peerConnection.createOffer({iceRestart:!0});if(!e.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const t=B7(e.sdp).iceParameters;return this.store.descriptionStart(),this.direction===aF.SEND_ONLY&&await this.peerConnection.setLocalDescription(e),t}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(t),this.store.descriptionStart(),this.direction===aF.RECEIVE_ONLY){this.restartCnt++,await this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const e=await this.peerConnection.createAnswer();if(!e.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const t=B7(e.sdp).iceParameters;return await this.peerConnection.setLocalDescription(e),t}await this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.transport=void 0,this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?$O()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),n=t.local,i=t.remote;return{local:Gse(Gse({},dP),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:Gse(Gse({},dP),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,t;Ui(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),null===(t=this.onICEConnectionStateChange)||void 0===t||t.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.restartCnt=0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var t;if(e.candidate.candidate)null===(t=this.onLocalCandidate)||void 0===t||t.call(this,e.candidate.toJSON());this.localCandidateCount+=1}else SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount)})}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t,n){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const r={iceServers:[]};var o;t.iceServers?r.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(eD(t.turnServer.servers)?r.iceServers=t.turnServer.servers:(r.iceServers&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers,n,i)),xP("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&t.turnServer.serversFromGateway&&r.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway,n,i)),Ui(o=[NP.Relay,NP.SdRtn]).call(o,n)&&(r.iceTransportPolicy="relay"),xP("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(r.iceTransportPolicy="relay")}))));return xP("ENABLE_ENCODED_TRANSFORM")&&JL().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),SL.debug("P2PConnection p2pTransport is ".concat(n)),r}static turnServerConfigToIceServers(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const i=[],r=e.filter((e=>e.tcpport));SL.debug("P2PConnection turnServers is ".concat(r,", current index is ").concat(n));const o=r.length>n?r[n]:r[0];switch(t){case NP.SdRtn:const t=e.filter((e=>{var t;return Ui(t=e.username).call(t,"glb:")&&e.turnServerURL==e.turnServerURL})),r=t.length>n?t[n]:t[0];r&&(i.push({username:r.username,credential:r.password,credentialType:"password",urls:"turn:".concat(f7(r.turnServerURL),":").concat(r.tcpport,"?transport=udp")}),i.push({username:r.username,credential:r.password,credentialType:"password",urls:"turns:".concat(f7(r.turnServerURL),":").concat(r.tcpport,"?transport=tcp")}));break;case NP.Relay:o&&(i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(f7(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}));break;default:o&&(i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turn:".concat(o.turnServerURL,":").concat(o.tcpport,"?transport=udp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"turns:".concat(f7(o.turnServerURL),":").concat(o.tcpport,"?transport=tcp")}),i.push({username:o.username,credential:o.password,credentialType:"password",urls:"stun:".concat(o.turnServerURL,":").concat(o.tcpport)}))}return i}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var t;null!=e&&e.state&&(null===(t=this.onDTLSTransportStateChange)||void 0===t||t.call(this,e.state))},e.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const t=e.iceTransport;t&&(t.onstatechange=()=>{const t=null==e?void 0:e.iceTransport.state;var n;t&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,t))},t.getSelectedCandidatePair&&(t.onselectedcandidatepairchange=()=>{if(t.getSelectedCandidatePair()){const e=t.getSelectedCandidatePair()||{},n=e.local,i=e.remote;if(n&&i){const e=n.address+":"+n.port,t=i.address+":"+i.port;SL.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(A7(e)),", remote ").concat(JSON.stringify(A7(t))))}}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var n;if(!t){t=this.peerConnection.getSenders().find((t=>t.track===e._mediaStreamTrack))}if(!t)return SL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return SL.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!JL().supportSetRtpSenderParameters)return SL.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const i={},r={};switch(e._optimizationMode){case"motion":i.degradationPreference="maintain-framerate";break;case"detail":i.degradationPreference="maintain-resolution";break;default:i.degradationPreference="balanced"}if(e._encoderConfig){var o;const t=e._encoderConfig,n=t.bitrateMax,i=t.frameRate,s=t.scaleResolutionDownBy;n&&(r.maxBitrate=1e3*n),Ui(o=e._hints).call(o,Rk.LOW_STREAM)&&(i&&(r.maxFramerate=T7(i)),s&&s>=1&&(r.scaleResolutionDownBy=s))}if(xP("DSCP_TYPE")&&SN()){var s;const e=xP("DSCP_TYPE");Ui(s=["very-low","low","medium","high"]).call(s,e)&&(r.networkPriority=e)}const a=t.getParameters(),c=null===(n=a.encodings)||void 0===n?void 0:n[0];$O()&&!c&&(i.encodings=[r]),c&&Object.assign(c,r),Object.assign(a,i),SL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),await t.setParameters(a)}async applySendEncodings(e,t){try{if(!JL().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof TV&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){SL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){const i=zP(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(Y7(o,e),q7(o,e,this.store.codec))})),ZP(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof TV&&!Ui(n=d._hints).call(n,Rk.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!$O()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof TV&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,n,i,r,o;return!!(e instanceof TV&&xP("SIMULCAST")&&"vp8"===this.store.codec&&!Ui(t=e._hints).call(t,Rk.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,n,i){if(xP("SDP_LOGGING"))return SL.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during P2PConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async e=>{e.direction="sendonly"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}async getRemoteSSRC(e,t){var n;if(t=null!=t?t:null===(n=this.currentRemoteDescription)||void 0===n?void 0:n.sdp){var i;const n=null===(i=zP(t).mediaDescriptions.find((t=>t.attributes.mid===e)))||void 0===i?void 0:i.attributes.ssrcs;return null==n?void 0:n[0].ssrcId}}async setRemoteDescription(e){var t;await this.peerConnection.setRemoteDescription(e),Ui(t=["connected","completed"]).call(t,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())}mungReceiveAnswerSDP(e,t,n){const i=zP(e),r=i.mediaDescriptions.find((e=>e.attributes.mid===t));return r&&n===UF.AUDIO&&"audio"===r.media.mediaType&&iee(r),ZP(i)}},Zx(Bse.prototype,"establish",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"establish"),Bse.prototype),Zx(Bse.prototype,"connect",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"connect"),Bse.prototype),Zx(Bse.prototype,"receive",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"receive"),Bse.prototype),Zx(Bse.prototype,"mockReceive",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"mockReceive"),Bse.prototype),Zx(Bse.prototype,"stopReceiving",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"stopReceiving"),Bse.prototype),Zx(Bse.prototype,"restartICE",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"restartICE"),Bse.prototype),Zx(Bse.prototype,"close",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"close"),Bse.prototype),Zx(Bse.prototype,"updateEncoderConfig",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"updateEncoderConfig"),Bse.prototype),Zx(Bse.prototype,"updateSendParameters",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"updateSendParameters"),Bse.prototype),Zx(Bse.prototype,"replaceTrack",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"replaceTrack"),Bse.prototype),Zx(Bse.prototype,"muteLocal",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"muteLocal"),Bse.prototype),Zx(Bse.prototype,"unmuteLocal",[Kse],Object.getOwnPropertyDescriptor(Bse.prototype,"unmuteLocal"),Bse.prototype),Bse);function Kse(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}let Hse=function(e){return e.SEND_ONLY="SEND_ONLY",e.RECEIVE_ONLY="RECEIVE_ONLY",e}({});var Yse,Xse,Jse,zse,Zse,qse,Qse,$se,eae,tae,nae,iae;function rae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function oae(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?rae(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):rae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let sae=(Yse=aae(Hse.SEND_ONLY),Xse=aae(Hse.SEND_ONLY),Jse=aae(),zse=aae(Hse.RECEIVE_ONLY),Zse=aae(Hse.RECEIVE_ONLY),qse=aae(Hse.RECEIVE_ONLY),Qse=aae(Hse.RECEIVE_ONLY),$se=aae(Hse.RECEIVE_ONLY),eae=aae(Hse.RECEIVE_ONLY),tae=aae(),nae=aae(Hse.RECEIVE_ONLY),iae=class extends YN{get state(){return this._state}set state(e){const t=this._state;this._state=e,this.emit(GF.StateChange,t,this._state)}constructor(e,t){super(),zA(this,"isPlanB",!1),zA(this,"store",void 0),zA(this,"statsUploader",void 0),zA(this,"sendConnection",void 0),zA(this,"recvConnection",void 0),zA(this,"localTrackMap",new Map),zA(this,"remoteUserMap",new Map),zA(this,"localDataChannels",[]),zA(this,"pendingLocalTracks",[]),zA(this,"pendingRemoteTracks",[]),zA(this,"statsCollector",void 0),zA(this,"dtlsFailedCount",0),zA(this,"sendMutex",void 0),zA(this,"recvMutex",void 0),zA(this,"_state",jF.Disconnected),zA(this,"_restartStates",["disconnected","failed"]),zA(this,"reconnectInterval",void 0),zA(this,"uploadUnplinkStarted",!1),zA(this,"uploadDownlinkStarted",!1),zA(this,"uplinkStateUploadInterval",void 0),zA(this,"downlinkStatsUploadInterval",void 0),zA(this,"handleMuteLocalTrack",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==jF.Connected)return void n(new ON(wN.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const s=this.filterTobeMutedTracks(e);if(0===s.length)return void t();const a=s.find((e=>"videoLowTrack"===e[0]));if(a){a[1].track._originMediaStreamTrack.stop()}await this.sendConnection.muteLocal(s.map((e=>KC(e,2)[1].id)));let c=!1;var r,o;if("video"===e.trackMediaType)c=!(null===(r=this.localTrackMap.get(BF.LocalAudioTrack))||void 0===r||!r.track._muted);else c=void 0===(null===(o=this.localTrackMap.get(BF.LocalVideoTrack))||void 0===o?void 0:o.id);const d=this.createMuteMessage(s);await lD(this,GF.RequestMuteLocal,d);const l="video"===e.trackMediaType?eB.MUTE_LOCAL_VIDEO:eB.MUTE_LOCAL_AUDIO;await lD(this,GF.RequestP2PMuteLocal,{action:l,message:d,isMuteAll:c}),t()}catch(e){n(e)}finally{i()}})),zA(this,"handleUnmuteLocalTrack",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==jF.Connected)return void n(new ON(wN.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const r=this.filterTobeUnmutedTracks(e);if(0===r.length)return void t();await this.sendConnection.unmuteLocal(r.map((e=>KC(e,2)[1].id)));const o=this.createUnmuteMessage(r),s="video"===e.trackMediaType?eB.UNMUTE_LOCAL_VIDEO:eB.UNMUTE_LOCAL_AUDIO;await lD(this,GF.RequestP2PMuteLocal,{action:s,message:o}),t()}catch(e){n(e)}finally{i()}})),zA(this,"handleUpdateVideoEncoder",(async(e,t,n,i)=>{let r;"boolean"==typeof i&&i||(r=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{const n=this.localTrackMap.get(BF.LocalVideoTrack);if(!this.sendConnection||!n||n.track!==e||this.state!==jF.Connected)return void t();const i=n.id,s=n.track;i&&(await this.sendConnection.updateSendParameters(i,s),await this.sendConnection.updateEncoderConfig(i,s),this.emit(GF.UpdateVideoEncoder,s)),t()}catch(e){n(e)}finally{var o;null===(o=r)||void 0===o||o()}})),zA(this,"handleUpdateVideoSendParameters",(async(e,t,n)=>{const i=await this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const n=this.localTrackMap.get(BF.LocalVideoTrack);if(!this.sendConnection||!n||n.track!==e||this.state!==jF.Connected)return void t();const r=n.id,o=n.track;r&&await this.sendConnection.updateSendParameters(r,o),t()}catch(e){n(e)}finally{i()}})),zA(this,"handleReplaceTrack",(async(e,t,n,i)=>{let r;SL.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(e.getTrackId(),"]")),"boolean"==typeof i&&i||(r=await this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var o;const n=Array.from(this.localTrackMap.entries()).find((t=>{let n=KC(t,2)[1].track;return e===n}));if(!this.sendConnection||!n||void 0===n[1].id||this.state!==jF.Connected)return void t();if(await(null===(o=this.sendConnection)||void 0===o?void 0:o.replaceTrack(e,n[1].id)),n[0]===BF.LocalVideoTrack&&JL().supportDualStreamEncoding){const t=this.localTrackMap.get(BF.LocalVideoLowTrack);if(t){const n=e._mediaStreamTrack.clone();t.track._originMediaStreamTrack.stop(),t.track._mediaStreamTrack=n,t.track._originMediaStreamTrack=n,await new cp(((e,n)=>{this.handleReplaceTrack(t.track,e,n,!0)}))}}t()}catch(e){n(e)}finally{var s;null===(s=r)||void 0===s||s()}})),zA(this,"handleGetLocalVideoStats",(e=>{e(this.statsCollector.getLocalVideoTrackStats())})),zA(this,"handleGetLocalAudioStats",(e=>{e(this.statsCollector.getLocalAudioTrackStats())})),zA(this,"handleGetRemoteVideoStats",(e=>this.statsCollector.getRemoteVideoTrackStats(e.uid)[e.uid])),zA(this,"handleGetRemoteAudioStats",(e=>this.statsCollector.getRemoteAudioTrackStats(e.uid)[e.uid])),this.store=e,this.statsCollector=t,this.statsCollector.addP2PChannel(this),this.statsUploader=new Zne(e),this.bindStatsUploaderEvents(),this.sendMutex=new JD("P2PChannel2-send-mutex",e.clientId),this.recvMutex=new JD("P2PChannel2-recv-mutex",e.clientId),this.reconnectInterval=window.setInterval((()=>{[this.sendConnection,this.recvConnection].forEach((e=>{e&&("disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))}))}),xP("ICE_RESTART_INTERVAL"))}async startP2PConnection(e,t){throw new ON(wN.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")}async connect(e){throw new ON(wN.NOT_SUPPORTED,"p2p mode does not support connect.")}async startP2P(e,t){let n;try{if(t){this.recvConnection&&(SL.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),n=await this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new Wse(e,this.store,aF.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const i=await this.recvConnection.establish(t);return{iceParameters:i.iceParameters,dtlsParameters:i.dtlsParameters,sdp:i.sdp}}{this.state=jF.New,this.sendConnection&&(SL.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),n=await this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new Wse(e,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const t=await this.sendConnection.establish();return{iceParameters:t.iceParameters,dtlsParameters:t.dtlsParameters,sdp:t.sdp}}}finally{n&&n()}}async p2pConnect(e){if(!this.sendConnection)throw new ON(wN.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),await this.sendConnection.connect(e),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=jF.Connected}async addRemoteCandidate(e,t){if(t===aF.RECEIVE_ONLY){if(!this.sendConnection)throw new ON(wN.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.sendConnection.addRemoteCandidate(e)}else{if(!this.recvConnection)throw new ON(wN.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");await this.recvConnection.addRemoteCandidate(e)}}publish(e,t,n){var i=this;return Ww((function*(){const r=yield Kw(i.sendMutex.lock("From P2PChannel.publish"));try{if(!i.sendConnection||i.state!==jF.Connected){i.throwIfTrackTypeNotMatch(e);const t=e.filter((e=>-1===i.pendingLocalTracks.indexOf(e)));return void(i.pendingLocalTracks=i.pendingLocalTracks.concat(t))}i.store.pubId=i.store.pubId+1,Vte.markPublishStart(i.store.clientId,i.store.pubId);const o=i.filterTobePublishedTracks(e,t,n);if(0===o.length)return void(yield Kw(i.tryToUnmuteAudio(e)));o.forEach((e=>{let t=e.track,n=e.type;const r=Date.now();i.store.publish(t.getTrackId(),n===BF.LocalAudioTrack?"audio":"video",r)})),i.bindLocalTrackEvents(o);const s=yield Kw(i.sendConnection.send(o.map((e=>e.track)),i.store.codec,i.store.audioCodec)),a=(yield Kw(s.next())).value,c=i.createGatewayPublishMessage(o,a);try{yield c}catch(e){throw s.throw(e),(null==e?void 0:e.code)===wN.WS_ABORT&&o.forEach((e=>{let t=e.track;-1===i.pendingLocalTracks.indexOf(t)&&i.pendingLocalTracks.push(t)})),i.unbindLocalTrackEvents(o),e}yield Kw(s.next()),o.forEach((e=>{let t=e.type;i.statsCollector.addLocalStats(t)})),i.statsUploader.startUploadOutboundStats(),i.assignLocalTracks(o,a),o.forEach((e=>{let t=e.track,n=e.type;const r=Date.now();i.store.publish(t.getTrackId(),n===BF.LocalAudioTrack?"audio":"video",void 0,r)})),i.startUploadUplinkState()}finally{r()}}))()}async unpublish(e){if(!this.sendConnection||this.state!==jF.Connected)return void(0===e.length?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter((t=>!Ui(e).call(e,t))));const t=this.filterTobeUnpublishedTracks(e);if(0===t.length)return;const n=t.find((e=>"videoLowTrack"===e[0]));if(n){n[1].track.close()}const i=this.createGatewayUnpublishMessage(t);if(await this.sendConnection.stopSending(t.map((e=>KC(e,2)[1].id))),this.withdrawLocalTracks(t),this.unbindLocalTrackEvents(t.map((e=>{let t=KC(e,2);return{type:t[0],track:t[1].track}}))),t.forEach((e=>{let t=KC(e,1)[0];this.statsCollector.removeLocalStats(t)})),0===this.localTrackMap.size&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===jF.Connected){if(n){n[1].track.close()}return i}e.forEach((e=>{const t=this.pendingLocalTracks.indexOf(e);-1!==t&&this.pendingLocalTracks.splice(t,1)}))}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const e=()=>{const e=[],t=[];Array.from(this.localTrackMap.entries()).forEach((n=>{let i=KC(n,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs;const c={stream_type:vne(s,r),ssrcs:a};s._muted||!s._enabled?e.push(c):t.push(c)})),e.length>0&&e.forEach((e=>{lD(this,GF.RequestMuteLocal,[e])})),t.length>0&&t.forEach((e=>{lD(this,GF.RequestUnmuteLocal,[e])}))};e(),this.uplinkStateUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(e){return Ww((function*(){throw new ON(wN.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")}))()}async republish(){this.pendingLocalTracks.length>0&&(SL.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),await dD(this,GF.RequestRePublish,this.pendingLocalTracks),this.emit(GF.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])}async unpublishLowStream(){throw new ON(wN.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")}async subscribe(e,t,n,i){var r;if(!this.recvConnection)throw new ON(wN.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if(null!==(r=this.remoteUserMap.get(e))&&void 0!==r&&r.has(t))return;const o=await this.recvConnection.receive(t,[{ssrcId:n}],String(e.uid),i),s=o.track,a=o.mid,c=o.transceiver;t===UF.AUDIO?(e._audioTrack?e._audioTrack._updateOriginMediaStreamTrack(s):(e._audioTrack=new FV(s,e.uid,e._uintid,this.store),SL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(e._audioTrack.getTrackId()))),c&&e._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._audioTrack)):(e._videoSSRC=n,e._videoTrack?e._videoTrack._updateOriginMediaStreamTrack(s):(e._videoTrack=new xV(s,e.uid,e._uintid,this.store),SL.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(e._videoTrack.getTrackId()))),c&&e._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(e,e._videoTrack));const d=this.remoteUserMap.get(e);d?d.set(t,a):this.remoteUserMap.set(e,new Map([[t,a]])),this.statsCollector.addRemoteStats(e.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const l=this.pendingRemoteTracks.findIndex((n=>{let i=n.user,r=n.kind;return i.uid===e.uid&&t===r}));-1!==l&&(this.pendingRemoteTracks.splice(l,1),this.emit(GF.MediaReconnectEnd,e.uid))}async mockSubscribe(e,t,n,i){if(!this.recvConnection)throw new ON(wN.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");await this.recvConnection.mockReceive(t,[{ssrcId:n}],String(e.uid),i)}async unsubscribe(e,t,n){const i=this.pendingRemoteTracks.filter((n=>{let i=n.user,r=n.kind;return void 0!==t?i.uid===e.uid&&t===r:i.uid===e.uid}));if(i.forEach((e=>{const t=this.pendingRemoteTracks.indexOf(e);this.pendingRemoteTracks.splice(t,1)})),this.recvConnection||n||i.forEach((t=>{let n=t.kind;var i;if(n===UF.AUDIO)null===(i=e._audioTrack)||void 0===i||i._destroy(),e._audioTrack=void 0;else if(n===UF.VIDEO){var r;null===(r=e._videoTrack)||void 0===r||r._destroy(),e._videoTrack=void 0}})),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(e,t);0!==r.length&&(await this.recvConnection.stopReceiving(r.map((e=>KC(e,2)[1].id))),this.withdrawRemoteTracks(r),0===this.remoteUserMap.size&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach((e=>{let t=KC(e,2),i=t[0],r=t[1].kind;var o,s;r===UF.VIDEO&&i._videoSSRC&&(null===(o=this.recvConnection)||void 0===o||o.setStatsRemoteVideoIsReady(i._videoSSRC,!1));if(r===UF.VIDEO)this.unbindRemoteTrackEvents(i._videoTrack),n||(null===(s=i._videoTrack)||void 0===s||s._destroy(),i._videoTrack=void 0);else if(r===UF.AUDIO){var a;if(this.unbindRemoteTrackEvents(i._audioTrack),!n)null===(a=i._audioTrack)||void 0===a||a._destroy(),i._audioTrack=void 0}})),r.forEach((e=>{let t=KC(e,2)[1].kind;lD(this,GF.RequestP2PMuteRemote,t)})))}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const e=()=>Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=KC(e,2)[1];[UF.VIDEO,UF.AUDIO].forEach((e=>{t.has(e)?lD(this,GF.RequestP2PUnmuteRemote,e):lD(this,GF.RequestP2PMuteRemote,e)}))}));e(),this.downlinkStatsUploadInterval=window.setInterval((()=>{e()}),3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}async massSubscribe(e){throw new ON(wN.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")}async massSubscribeNoLock(e){throw new ON(wN.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")}async massUnsubscribe(e){throw new ON(wN.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")}async massUnsubscribeNoLock(e){throw new ON(wN.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")}async muteRemote(e,t){if(!this.recvConnection)return;const n=this.remoteUserMap.get(e);if(!n)return void SL.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid,"."));if(!n.get(t))return void SL.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."));const i=t===UF.VIDEO?e._videoSSRC:e._audioSSRC;void 0!==i&&this.recvConnection.setStatsRemoteVideoIsReady(i,!1)}async unmuteRemote(e,t){return this.unmuteRemoteNoLock(e,t)}async unmuteRemoteNoLock(e,t){if(!this.recvConnection)return;const n=this.remoteUserMap.get(e);if(!n)return void SL.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid,"."));n.get(t)||SL.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(e.uid," media type ").concat(t,"."))}getAllTracks(e){const t=this.localTrackMap.get(BF.LocalAudioTrack);if((null==t?void 0:t.track)instanceof OU){const n=t.track;return Array.from(this.localTrackMap.entries()).filter((e=>KC(e,1)[0]!==BF.LocalAudioTrack)).filter((t=>{let n=KC(t,1)[0];return!(e&&n===BF.LocalVideoLowTrack)})).map((e=>KC(e,2)[1].track)).concat(n.trackList)}return Array.from(this.localTrackMap.entries()).filter((t=>{let n=KC(t,1)[0];return!(e&&n===BF.LocalVideoLowTrack)})).map((e=>KC(e,2)[1].track))}reportPublishEvent(e,t,n,i,r){if(e){const n=this.localTrackMap.get(BF.LocalAudioTrack),o=i?this.localTrackMap.get(BF.LocalVideoLowTrack):this.localTrackMap.get(BF.LocalVideoTrack);HL.publish(this.store.sessionId,{eventElapse:Vte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==n?void 0:n.track.getTrackLabel(),videoName:null==o?void 0:o.track.getTrackLabel(),screenshare:-1!==(null==o?void 0:o.track._hints.indexOf(Rk.SCREEN_TRACK)),audio:!!n,video:!!o,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;n||(n=[]);const s=n.find((e=>e instanceof IU)),a=i?null===(o=this.localTrackMap.get(BF.LocalVideoTrack))||void 0===o?void 0:o.track:n.find((e=>e instanceof TV));HL.publish(this.store.sessionId,{eventElapse:Vte.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:e,ec:t,audioName:null==s?void 0:s.getTrackLabel(),videoName:null==a?void 0:a.getTrackLabel(),screenshare:-1!==(null==a?void 0:a._hints.indexOf(Rk.SCREEN_TRACK)),audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(e,t,n,i){const r=i===UF.VIDEO?n._videoSSRC:n._audioSSRC;r&&HL.subscribe(this.store.sessionId,{succ:e,ec:t,video:i===UF.VIDEO,audio:i===UF.AUDIO,peerid:n.uid,subscribeRequestid:i===UF.VIDEO?n._videoSSRC:n._audioSSRC,p2pid:this.store.p2pId,eventElapse:Vte.measureFromSubscribeStart(this.store.clientId,r)})}reset(){SL.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new JD("P2PChannel2-send-mutex",this.store.clientId),this.sendMutex=new JD("P2PChannel2-recv-mutex",this.store.clientId),this.sendConnection&&(this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0),this.recvConnection&&(this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const e=this.localTrackMap.get(BF.LocalAudioTrack);if((null==e?void 0:e.track)instanceof OU){if(e.track.trackList.length>0){const t=e.track;e.track.trackList.forEach((e=>{t.removeAudioTrack(e)}))}e.track.close()}this.localTrackMap.clear(),this.remoteUserMap.clear(),this.statsCollector.removeRemoteStats(),this.statsCollector.removeLocalStats(),this.dtlsFailedCount=0,this.pendingLocalTracks=[],this.pendingRemoteTracks=[],this.reconnectInterval&&(window.clearInterval(this.reconnectInterval),this.reconnectInterval=void 0),this.state=jF.Disconnected}getStats(e){var t,n;return e?null===(n=this.recvConnection)||void 0===n?void 0:n.getStats():null===(t=this.sendConnection)||void 0===t?void 0:t.getStats()}getRemoteVideoIsReady(e){var t;return(null===(t=this.recvConnection)||void 0===t?void 0:t.getRemoteVideoIsReady(e))||!1}getLocalAudioVolume(){const e=this.localTrackMap.get(BF.LocalAudioTrack);if(e)return e.track.getVolumeLevel()}getLocalVideoSize(){const e=this.localTrackMap.get(BF.LocalVideoTrack);if(e)return{width:e.track.videoWidth||0,height:e.track.videoHeight||0}}getEncoderConfig(e){const t=this.localTrackMap.get(e);return t&&t.track instanceof TV||t&&t.track instanceof IU?t.track._encoderConfig:void 0}getLocalMedia(e){return this.localTrackMap.get(e)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}async hasRemoteMediaWithLock(e,t){if(!e)return this.remoteUserMap.size>0;const n=this.remoteUserMap.get(e);return!!n&&(!t||n.has(t))}getRemoteMedia(e){var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t.uid===e));return n?{audioTrack:n.audioTrack,audioSSRC:n._audioSSRC,videoTrack:n.videoTrack,videoSSRC:n._videoSSRC}:{}}getAudioLevels(){let e=Array.from(this.remoteUserMap.entries()).map((e=>{let t=KC(e,1)[0];return{uid:t.uid,level:t.audioTrack?100*t.audioTrack._source.getAccurateVolumeLevel():0}}));const t=this.localTrackMap.get(BF.LocalAudioTrack);return t&&e.push({level:100*t.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),e=t_(e).call(e,((e,t)=>e.level-t.level)),e}async disconnectForReconnect(){this.sendConnection&&this.recvConnection&&(SL.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=jF.Reconnecting,xP("KEEP_LAST_FRAME")&&0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=KC(e,1)[0];var n;t._videoTrack&&t._videoTrack._player&&(null===(n=t._videoTrack._player.getVideoElement())||void 0===n||n.pause(),t._videoTrack._player.isKeepLastFrame=!0,t._videoTrack._originMediaStreamTrack.stop())})),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection),this.sendConnection=void 0,this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection),this.recvConnection=void 0,0!==this.localTrackMap.size&&(Array.from(this.localTrackMap.entries()).forEach((e=>{var t;let n=KC(e,2),i=n[0],r=n[1].track;switch(i){case BF.LocalVideoTrack:Ui(t=r._hints).call(t,Rk.LOW_STREAM)?r.close():this.pendingLocalTracks.push(r);break;case BF.LocalAudioTrack:r instanceof OU?this.pendingLocalTracks=this.pendingLocalTracks.concat(r.trackList):this.pendingLocalTracks.push(r);case BF.LocalVideoLowTrack:}})),this.emit(GF.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),0!==this.remoteUserMap.size&&Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1];Array.from(oL(i).call(i)).forEach((e=>{this.setPendingRemoteMedia(n,e)})),this.emit(GF.MediaReconnectStart,n.uid)})),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),SL.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))}hasPendingRemoteMedia(e,t){for(const n of this.pendingRemoteTracks){const i=n.user,r=n.kind;if((e instanceof Wte?e.uid:e)===i.uid&&t===r)return!0}return!1}setPendingRemoteMedia(e,t){this.hasPendingRemoteMedia(e,t)||this.pendingRemoteTracks.push({user:e,kind:t})}async restartICE(e,t){let n,i;if(e===aF.SEND_ONLY){if(!this.sendConnection)throw new ON(wN.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");n=await this.sendMutex.lock("From P2PChannel.restartICE"),i=this.sendConnection}else{if(!this.recvConnection)throw new ON(wN.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");n=await this.recvMutex.lock("From P2PChannel.restartICE"),i=this.recvConnection}try{if(t){const e=await i.restartICE(t);return i.isInRestartIce=!1,e}{const e=await i.restartICE();if(e){const t=await dD(this,GF.RequestP2PRestartICE,{direction:aF.RECEIVE_ONLY,iceParameter:e});await i.restartICE(t),i.isInRestartIce=!1}}}finally{n()}}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const e=this.sendConnection.getStats(),t=this.localTrackMap.get(BF.LocalVideoTrack),n=this.localTrackMap.get(BF.LocalAudioTrack),i=e.videoSend.find((e=>{var n;return e.ssrc===(null==t||null===(n=t.ssrcs)||void 0===n?void 0:n[0].ssrcId)})),r=e.audioSend.find((e=>{var t;return e.ssrc===(null==n||null===(t=n.ssrcs)||void 0===t?void 0:t[0].ssrcId)}));if(!i||!r)return 1;const o=uD(this,GF.NeedSignalRTT),s=i?i.rttMs:void 0,a=r?r.rttMs:void 0,c=s&&a?(s+a)/2:s||a,d=(c&&o?(c+o)/2:c||o)||0,l=100*e.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=null==t?void 0:t.track;if(h&&h._encoderConfig&&-1===h._hints.indexOf(Rk.SCREEN_TRACK)){const t=h._encoderConfig.bitrateMax,n=e.bitrate.actualEncoded;if(t&&n){const e=(1e3*t-n)/(1e3*t);return Ox[e<.15?0:e<.3?1:e<.45?2:e<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const e=this.recvConnection.getStats();let t=0;return Array.from(this.remoteUserMap.entries()).forEach((n=>{let i=KC(n,1)[0];const r=i._audioSSRC,o=i._videoSSRC,s=e.audioRecv.find((e=>e.ssrc===r)),a=e.videoRecv.find((e=>e.ssrc===o));if(!s&&!a)return void(t+=1);const c=uD(this,GF.NeedSignalRTT),d=e.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=e.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400);t+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5})),this.remoteUserMap.size>0?Math.round(t/this.remoteUserMap.size):t}async muteLocalTrack(e){return new cp(((t,n)=>{this.handleMuteLocalTrack(e,t,n)}))}filterTobePublishedTracks(e,t,n){const i=[],r=JL(),o=this.getAllTracks();e=TD(e=e.filter((e=>-1===o.indexOf(e))));let s=!1,a=!1;for(const o of e){if(o instanceof TV&&(this.localTrackMap.has(BF.LocalVideoTrack)||s?new ON(wN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(i.push({track:o,type:BF.LocalVideoTrack}),s=!0),t)){const e=this.getLowVideoTrack(o,n);i.push({track:e,type:BF.LocalVideoLowTrack})}if(o instanceof IU){const e=this.localTrackMap.get(BF.LocalAudioTrack);if(e){if(!(e.track instanceof OU))throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o),this.bindLocalAudioTrackEvents(o,!0)}else if(a){const e=i.find((e=>e.type===BF.LocalAudioTrack));if(!(e.track instanceof OU))throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(o._bypassWebAudio)throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");e.track.addAudioTrack(o)}else{if(!r.webAudioMediaStreamDest||o instanceof OU||o._bypassWebAudio)i.push({track:o,type:BF.LocalAudioTrack});else{const e=new OU;e.addAudioTrack(o),i.push({track:e,type:BF.LocalAudioTrack})}a=!0}}}return i}filterTobeUnpublishedTracks(e){const t=[],n=this.getAllTracks();e=TD(e=e.filter((e=>-1!==n.indexOf(e))));for(const n of e){if(n instanceof IU){const e=this.localTrackMap.get(BF.LocalAudioTrack);if(!e)continue;e.track instanceof OU?(e.track.removeAudioTrack(n),this.unbindLocalAudioTrackEvents(n),0===e.track.trackList.length&&(t.push([BF.LocalAudioTrack,e]),e.track.close())):t.push([BF.LocalAudioTrack,e])}if(n instanceof TV){const e=this.localTrackMap.get(BF.LocalVideoTrack);if(!e)continue;t.push([BF.LocalVideoTrack,e]);const n=this.localTrackMap.get(BF.LocalVideoLowTrack);n&&t.push([BF.LocalVideoLowTrack,n])}}return t}bindLocalTrackEvents(e){e.forEach((e=>{let t=e.track;switch(e.type){case BF.LocalVideoTrack:t.addListener(Tk.GET_STATS,this.handleGetLocalVideoStats),t.addListener(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(Tk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.addListener(Tk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.addListener(Tk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case BF.LocalAudioTrack:this.bindLocalAudioTrackEvents(t);case BF.LocalVideoLowTrack:}}))}bindLocalAudioTrackEvents(e,t){e instanceof OU?e.trackList.forEach((e=>{e.addListener(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Tk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.addListener(Tk.GET_STATS,this.handleGetLocalAudioStats),e.addListener(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.addListener(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.addListener(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.addListener(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),t||e.addListener(Tk.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(e){e||(e=Array.from(this.localTrackMap.entries()).map((e=>{let t=KC(e,2),n=t[0];return{track:t[1].track,type:n}}))),e.forEach((e=>{let t=e.track;switch(e.type){case BF.LocalVideoTrack:t.off(Tk.GET_STATS,this.handleGetLocalVideoStats),t.off(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(Tk.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),t.off(Tk.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),t.off(Tk.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case BF.LocalAudioTrack:this.unbindLocalAudioTrackEvents(t);case BF.LocalVideoLowTrack:}}))}unbindLocalAudioTrackEvents(e){e instanceof OU?e.trackList.forEach((e=>{e.off(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Tk.GET_STATS,this.handleGetLocalAudioStats),e.off(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)})):(e.off(Tk.GET_STATS,this.handleGetLocalAudioStats),e.off(Tk.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(Tk.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(Tk.NEED_REPLACE_TRACK,this.handleReplaceTrack),e.off(Tk.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(Tk.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(e,t){t instanceof xV&&t.addListener(Tk.GET_STATS,(t=>{t(this.handleGetRemoteVideoStats(e))})),t instanceof FV&&t.addListener(Tk.GET_STATS,(t=>{t(this.handleGetRemoteAudioStats(e))}))}unbindRemoteTrackEvents(e){e&&e.removeAllListeners(Tk.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1];i.has(UF.AUDIO)&&this.unbindRemoteTrackEvents(n._audioTrack),i.has(UF.VIDEO)&&this.unbindRemoteTrackEvents(n._videoTrack)}))}createGatewayPublishMessage(e,t){return e.map(((e,n)=>{var i;let r,o=e.track,s=e.type;switch(s){case BF.LocalAudioTrack:r=CF.Audio;break;case BF.LocalVideoTrack:r=Ui(i=o._hints).call(i,Rk.SCREEN_TRACK)?CF.Screen:CF.High;break;case BF.LocalVideoLowTrack:r=CF.Low}return{kind:s===BF.LocalAudioTrack?UF.AUDIO:UF.VIDEO,stream_type:r,mid:t[n].id,ssrcs:t[n].localSSRC,isMuted:o.muted||!o.enabled}}))}createGatewayUnpublishMessage(e){return e.map((e=>{var t;let n,i=KC(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case BF.LocalVideoTrack:n=Ui(t=s._hints).call(t,Rk.SCREEN_TRACK)?CF.Screen:CF.High;break;case BF.LocalAudioTrack:n=CF.Audio;break;case BF.LocalVideoLowTrack:n=CF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}assignLocalTracks(e,t){e.forEach(((e,n)=>{let i=e.track,r=e.type;this.localTrackMap.set(r,{track:i,id:t[n].id,ssrcs:t[n].localSSRC})}))}withdrawLocalTracks(e){e.forEach((e=>{let t=KC(e,1)[0];this.localTrackMap.delete(t)}))}bindConnectionEvents(e){e.onConnectionStateChange=async t=>{var n;SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(e.name,".onConnectionStateChange(").concat(t,")")),this.emit(GF.PeerConnectionStateChange,t),"connected"!==t||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),"connected"===t&&(e.isInRestartIce=!1),Ui(n=this._restartStates).call(n,t)&&!e.isInRestartIce&&("disconnected"===t&&await LD(800),"disconnected"!==e.iceConnectionState&&"failed"!==e.iceConnectionState||this.handleDisconnect(e.direction))},e.onICEConnectionStateChange=e=>{"connected"!==e||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),HL.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:ZN.TRACER}).onSuccess(),this.emit(GF.IceConnectionStateChange,e)},e.onICETransportStateChange=e=>{SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},e.onDTLSTransportStateChange=e=>{SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},e.onDTLSTransportError=e=>{SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},e.onFirstAudioDecoded=e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));var i;n&&(this.store.subscribe(n.uid,"audio",void 0,void 0,void 0,Date.now()),null===(i=n.audioTrack)||void 0===i||i.emit(Ak.FIRST_FRAME_DECODED),HL.firstRemoteFrame(this.store.sessionId,bL.FIRST_AUDIO_DECODE,IL.FIRST_AUDIO_DECODE,{peer:n._uintid,subscribeElapse:Vte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},e.onFirstAudioReceived=e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._audioSSRC===e));n&&HL.firstRemoteFrame(this.store.sessionId,bL.FIRST_AUDIO_RECEIVED,IL.FIRST_AUDIO_RECEIVED,{peer:n._uintid,subscribeElapse:Vte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onFirstVideoDecoded=(e,t,n)=>{this.reportVideoFirstFrameDecoded(e,t,n)},e.onFirstVideoReceived=e=>{var t;const n=Array.from(oL(t=this.remoteUserMap).call(t)).find((t=>t._videoSSRC===e));n&&HL.firstRemoteFrame(this.store.sessionId,bL.FIRST_VIDEO_RECEIVED,IL.FIRST_VIDEO_RECEIVED,{peer:n._uintid,subscribeElapse:Vte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},e.onSelectedLocalCandidateChanged=(e,t)=>{const n="relay"===e.candidateType,i="relay"===t.candidateType;"unknown"!==t.candidateType&&n===i||this.emit(GF.ConnectionTypeChange,n),SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(I7(t))," -> ").concat(JSON.stringify(I7(e)),")"))},e.onSelectedRemoteCandidateChanged=(e,t)=>{SL.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(I7(t))," -> ").concat(JSON.stringify(I7(e)),")"))},e.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},e.onLocalCandidate=t=>{this.emit(GF.LocalCandidate,{candidate:t,direction:e.direction})}}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0,e.onLocalCandidate=void 0}async handleDisconnect(e){const t=e===aF.SEND_ONLY?this.sendConnection:this.recvConnection;t&&!t.isInRestartIce&&(t.isInRestartIce=!0,SL.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(t.name,"] start use restartICE")),e===aF.SEND_ONLY?this.restartICE(e):dD(this,GF.RequestP2PRestartICE,{direction:aF.SEND_ONLY}))}filterTobeMutedTracks(e){const t=[];if(-1===this.getAllTracks().indexOf(e))return t;const n=this.localTrackMap.get(BF.LocalAudioTrack);if(e instanceof IU&&(null==n?void 0:n.track)instanceof OU)return n.track.isActive||t.push([BF.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=KC(t,2)[1].track;return e===n}));if(i&&(t.push(i),i[0]===BF.LocalVideoTrack)){const e=this.localTrackMap.get(BF.LocalVideoLowTrack);e&&t.push([BF.LocalVideoLowTrack,e])}return t}filterTobeUnmutedTracks(e){const t=[],n=this.localTrackMap.get(BF.LocalAudioTrack);if(e instanceof IU&&(null==n?void 0:n.track)instanceof OU)return n.track.isActive&&t.push([BF.LocalAudioTrack,n]),t;const i=Array.from(this.localTrackMap.entries()).find((t=>{let n=KC(t,2)[1].track;return e===n}));if(i)if(i[0]===BF.LocalVideoTrack){t.push(i);const e=this.localTrackMap.get(BF.LocalVideoLowTrack);e&&t.push([BF.LocalVideoLowTrack,e])}else t.push(i);return t}createMuteMessage(e){return e.map((e=>{var t;let n,i=KC(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case BF.LocalAudioTrack:n=CF.Audio;break;case BF.LocalVideoTrack:n=Ui(t=s._hints).call(t,Rk.SCREEN_TRACK)?CF.Screen:CF.High;break;case BF.LocalVideoLowTrack:n=CF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}createUnmuteMessage(e){return e.map((e=>{var t;let n,i=KC(e,2),r=i[0],o=i[1],s=o.track,a=o.ssrcs,c=o.id;switch(r){case BF.LocalAudioTrack:n=CF.Audio;break;case BF.LocalVideoTrack:n=Ui(t=s._hints).call(t,Rk.SCREEN_TRACK)?CF.Screen:CF.High;break;case BF.LocalVideoLowTrack:n=CF.Low}return{stream_type:n,ssrcs:a,mid:c}}))}filterTobeUnSubscribedTracks(e,t){const n=[],i=this.remoteUserMap.get(e);if(!i)return n;if(t){const r=i.get(t);if(!r)return n;n.push([e,{kind:t,id:r}])}else Array.from(i.entries()).forEach((t=>{let i=KC(t,2),r=i[0],o=i[1];n.push([e,{kind:r,id:o}])}));return n}createUnsubscribeMessage(e){const t=[];return e.forEach((e=>{let n=KC(e,2),i=n[0],r=n[1],o=r.kind;switch(r.id,o){case UF.VIDEO:return void(i._videoSSRC&&t.push({stream_type:UF.VIDEO,ssrcId:i._videoSSRC}));case UF.AUDIO:return void(i._audioSSRC&&t.push({stream_type:UF.AUDIO,ssrcId:i._audioSSRC}))}})),t}withdrawRemoteTracks(e){e.forEach((e=>{let t=KC(e,2),n=t[0],i=t[1].kind;const r=this.remoteUserMap.get(n);r&&(r.delete(i),0===Array.from(r.entries()).length&&this.remoteUserMap.delete(n))}))}async updateBitrateLimit(e){const t=this.localTrackMap.get(BF.LocalVideoTrack),n=this.localTrackMap.get(BF.LocalVideoLowTrack);t&&(await t.track.setBitrateLimit(e.uplink),await new cp(((e,n)=>{this.handleUpdateVideoEncoder(t.track,e,n,!0)}))),n&&e.low_stream_uplink&&(await n.track.setBitrateLimit({max_bitrate:e.low_stream_uplink.bitrate,min_bitrate:e.low_stream_uplink.bitrate||0}),await new cp(((e,t)=>{this.handleUpdateVideoEncoder(n.track,e,t,!0)})))}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const e=this.sendConnection.peerConnectionState,t=this.recvConnection.peerConnectionState;return"connected"!==e&&"connected"!==t}return!0}async tryToUnmuteAudio(e){for(let t=0;t<e.length;t++)if(e[t]instanceof IU){const n=this.filterTobeUnmutedTracks(e[t]);if(0===n.length)continue;const i=this.createUnmuteMessage(n);return void await lD(this,GF.RequestUnmuteLocal,i)}}bindStatsUploaderEvents(){this.statsUploader.requestStats=e=>this.getStats(e),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter((e=>!!KC(e,2)[1].ssrcs)),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=e=>{var t;return!(null===(t=this.recvConnection)||void 0===t||!t.getRemoteVideoIsReady(e))},this.statsUploader.requestUpload=(e,t)=>this.emit(GF.RequestUpload,e,t),this.statsUploader.requestUploadStats=e=>this.emit(GF.RequestUploadStats,e),this.statsUploader.requestAllTracks=()=>this.getAllTracks()}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}async requestReconnect(){this.dtlsFailedCount+=1,await LD(qD(this.dtlsFailedCount,ZD)),this.emit(GF.RequestReconnect)}async reconnectP2P(){}canPublishLowStream(){return this.localTrackMap.has(BF.LocalVideoTrack)||this.pendingLocalTracks.some((e=>e instanceof TV))}throwIfTrackTypeNotMatch(e){if(e.filter((e=>e instanceof TV)).length>1)throw new ON(wN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e.filter((e=>e instanceof IU)).length>1&&(e.some((e=>e instanceof IU&&e._bypassWebAudio))||!JL().webAudioMediaStreamDest))throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const t of e){if(t instanceof TV&&this.pendingLocalTracks.some((e=>e instanceof TV)))throw new ON(wN.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t instanceof IU&&this.pendingLocalTracks.some((e=>e instanceof IU))&&(!JL().webAudioMediaStreamDest||t._bypassWebAudio||this.pendingLocalTracks.some((e=>e instanceof IU&&e._bypassWebAudio))))throw new ON(wN.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(e,t){const n=!xP("DISABLE_DUAL_STREAM_USE_ENCODING")&&JL().supportDualStreamEncoding,i=oae(oae({},{width:160,height:120,framerate:15,bitrate:50}),t);let r;r=n?e._mediaStreamTrack.clone():kne(e,i);const o=kD(8,"track-low-"),s=new TV(r,oae(oae({},n&&{scaleResolutionDownBy:b7(i,e)}),{},{frameRate:i.framerate,bitrateMax:i.bitrate,bitrateMin:i.bitrate}),void 0,void 0,o);return s.on(bk.TRANSCEIVER_UPDATED,(t=>{e._updateRtpTransceiver(t,vk.LOW_STREAM)})),s._hints.push(Rk.LOW_STREAM),e.addListener(Tk.NEED_CLOSE,(()=>{s.close()})),s}async globalLock(){return this.recvMutex.lock("From P2PChannel2.globalLock")}reportVideoFirstFrameDecoded(e,t,n,i){var r;const o=Array.from(oL(r=this.remoteUserMap).call(r)).find((t=>t._videoSSRC===e));if(o){i||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const r=this.store.keyMetrics,s=r.subscribe.find((e=>e.userId===o.uid&&"video"===e.type));HL.firstRemoteVideoDecode(this.store.sessionId,bL.FIRST_VIDEO_DECODE,IL.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:t,videoheight:n,subscribeElapse:Vte.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId,apEnd:r.requestAPEnd||0,apStart:r.requestAPStart||0,joinGwEnd:r.joinGatewayEnd||0,joinGwStart:r.joinGatewayStart||0,pcEnd:r.peerConnectionEnd||0,pcStart:r.peerConnectionStart||0,subscriberEnd:(null==s?void 0:s.subscribeEnd)||0,subscriberStart:(null==s?void 0:s.subscribeStart)||0,videoAddNotify:(null==s?void 0:s.streamAdded)||0,state:i?1:0})}}async remoteMediaSsrcChanged(e,t,n){if(!this.recvConnection)return!1;const i=this.remoteUserMap.get(e);if(!i)return!1;const r=i.get(t);if(!r)return!1;const o=await this.recvConnection.getRemoteSSRC(r);return void 0!==o&&o!==n}isPreSubScribe(e){return!1}async publishDataChannel(e){throw new ON(wN.NOT_SUPPORTED)}async unpublishDataChannel(e){throw new ON(wN.NOT_SUPPORTED)}async subscribeDataChannel(e,t){throw new ON(wN.NOT_SUPPORTED)}async unsubscribeDataChannel(e,t){throw new ON(wN.NOT_SUPPORTED)}hasPendingRemoteDataChannel(e,t){throw new ON(wN.NOT_SUPPORTED)}setPendingRemoteDataChannel(e,t){throw new ON(wN.NOT_SUPPORTED)}async preConnect(e){throw new ON(wN.NOT_SUPPORTED)}getEstablishParams(){throw new ON(wN.NOT_SUPPORTED)}async reSubscribe(e){throw new ON(wN.NOT_SUPPORTED)}reportVideoFirstFrameRender(e){}async updateVideoStreamParameter(e,t){throw new ON(wN.NOT_SUPPORTED)}unbindRtpTransceiver(){0!==this.localTrackMap.size&&Array.from(this.localTrackMap.entries()).forEach((e=>{let t=KC(e,2),n=t[0],i=t[1].track;n===BF.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,vk.LOW_STREAM):i._updateRtpTransceiver(void 0)}))}},Zx(iae.prototype,"p2pConnect",[Yse],Object.getOwnPropertyDescriptor(iae.prototype,"p2pConnect"),iae.prototype),Zx(iae.prototype,"unpublish",[Xse],Object.getOwnPropertyDescriptor(iae.prototype,"unpublish"),iae.prototype),Zx(iae.prototype,"unpublishLowStream",[Jse],Object.getOwnPropertyDescriptor(iae.prototype,"unpublishLowStream"),iae.prototype),Zx(iae.prototype,"subscribe",[zse],Object.getOwnPropertyDescriptor(iae.prototype,"subscribe"),iae.prototype),Zx(iae.prototype,"mockSubscribe",[Zse],Object.getOwnPropertyDescriptor(iae.prototype,"mockSubscribe"),iae.prototype),Zx(iae.prototype,"unsubscribe",[qse],Object.getOwnPropertyDescriptor(iae.prototype,"unsubscribe"),iae.prototype),Zx(iae.prototype,"muteRemote",[Qse],Object.getOwnPropertyDescriptor(iae.prototype,"muteRemote"),iae.prototype),Zx(iae.prototype,"unmuteRemote",[$se],Object.getOwnPropertyDescriptor(iae.prototype,"unmuteRemote"),iae.prototype),Zx(iae.prototype,"hasRemoteMediaWithLock",[eae],Object.getOwnPropertyDescriptor(iae.prototype,"hasRemoteMediaWithLock"),iae.prototype),Zx(iae.prototype,"disconnectForReconnect",[tae],Object.getOwnPropertyDescriptor(iae.prototype,"disconnectForReconnect"),iae.prototype),Zx(iae.prototype,"remoteMediaSsrcChanged",[nae],Object.getOwnPropertyDescriptor(iae.prototype,"remoteMediaSsrcChanged"),iae.prototype),iae);function aae(e){return function(t,n,i){const r=t[n];if("function"!=typeof r)throw new Error("Cannot use mutex on object property.");return i.value=async function(){for(var t=arguments.length,i=new Array(t),o=0;o<t;o++)i[o]=arguments[o];switch(e){case Hse.SEND_ONLY:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e()}}case Hse.RECEIVE_ONLY:{const e=await this.recvMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e()}}default:{const e=await this.sendMutex.lock("From P2PChannel2.".concat(n)),t=await this.recvMutex.lock("From P2PChannel2.".concat(n));try{return await r.apply(this,i)}finally{e(),t()}}}},i}}class cae extends YN{constructor(e,t){super(),zA(this,"signal",void 0),zA(this,"token",void 0),zA(this,"tokenTimeout",void 0),zA(this,"tokenInterval",void 0),zA(this,"_sequence",0),zA(this,"userMap",new Map),zA(this,"encoder",new TextEncoder),this.signal=e,this.token=t;const n=()=>{this.signal.connectionState===nF.CONNECTED&&this.check(),0===this.userMap.size?this.tokenInterval=window.setTimeout(n,1e3):this.tokenInterval=window.setTimeout(n,3*xP("P2P_TOKEN_INTERVAL"))};n()}async send(e,t,n,i,r){var o;if(0===this.userMap.size)return;const s=Array.from(fp(o=this.userMap).call(o))[0].token;"string"!=typeof t&&(t=JSON.stringify(t)),i=null!=i?i:kD(6,""),r=null!=r?r:this._sequence++;const a={_id:i,_type:e,_seq:r,_message:t,token:"".concat(this.token,"_").concat(s)};xP("SHOW_P2P_LOG")&&SL.debug("send message",a,"noNeedResponse : ".concat(n));this.splitMessage(JSON.stringify(a)).forEach((e=>{this.signal.request(rF.DATA_STREAM,{payload:AD(this.encoder.encode(e))})}));const c=new cp(((t,r)=>{const o=window.setTimeout((()=>{this.off("res-@".concat(i,"_ack"),s),this.off("res-@".concat(i),d),this.off($F.ABORT,c),SL.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(i)),0===this.userMap.size?r(new ON(wN.INVALID_REMOTE_USER)):r(new ON(wN.TIMEOUT))}),xP("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),s=()=>{o&&window.clearTimeout(o),this.off($F.ABORT,c),n&&t()},c=()=>{o&&window.clearTimeout(o),this.off("res-@".concat(i,"_ack"),s),this.off("res-@".concat(i),d),r(new ON(wN.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(i)))};this.once($F.ABORT,c),this.once("res-@".concat(i,"_ack"),s);const d=(n,a)=>{l=!0,o&&window.clearTimeout(o),this.off("res-@".concat(i,"_ack"),s),this.off($F.ABORT,c),"success"===n?t(a):r(new ON(wN.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(i)))};let l=!1;n||(this.once("res-@".concat(i),d),LD(xP("SIGNAL_REQUEST_TIMEOUT")).then((()=>{l||SL.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(i,", ").concat(a))})))}));try{return await c}catch(o){if(o.code===wN.TIMEOUT)return await this.send(e,t,n,i,r);throw o}}onMessage(e){var t;const n=e._uid;let i,r=this.userMap.get(n);if(r)i=r.splitMessageMap;else{if(this.userMap.size>0||!("_type"in e)||e._type!==QF.CHECK)return;const t=e.token;i=new Map,r={uid:n,isStart:!0,token:t,splitMessageMap:i,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(n,r),this.signal.emit(sF.ON_USER_ONLINE,{uid:n}),this.handleUserOnline()}if("id"in e&&"total"in e){var o;const t=e,r=t.id,s=t.total,a=null!==(o=i.get(r))&&void 0!==o?o:[];if(a.push(e),i.has(r)||i.set(r,a),a.length!==s)return;{const t=t_(a).call(a,((e,t)=>e.index-t.index)).map((e=>e.payload)).join("");i.delete(r),(e=JSON.parse(t))._uid=n}}const s=e,a=s._type,c=s.token;if(Ui(t=[QF.ACK,QF.CHECK]).call(t,a))return a===QF.CHECK&&this.handleCheckToken(r,c),void this.receiveMessage(e);c==="".concat(r.token,"_").concat(this.token)?this.handleReceivedMessage(e):SL.debug('Receive unexpected message", '.concat(c,", cur_token: ").concat(r.token,"_").concat(this.token),e)}check(){const e={_id:kD(6,""),token:this.token,_type:QF.CHECK};xP("SHOW_P2P_LOG")&&SL.debug("send message",e),this.signal.request(rF.DATA_STREAM,{payload:AD(this.encoder.encode(JSON.stringify(e)))})}ack(e){const t={_id:e,_type:QF.ACK,token:this.token};xP("SHOW_P2P_LOG")&&SL.debug("send message",t),this.signal.request(rF.DATA_STREAM,{payload:AD(this.encoder.encode(JSON.stringify(t)))})}response(e,t,n){this.send(QF.RESPONSE,JSON.stringify({success:!n,message:t}),!0,e)}handleReceivedMessage(e){const t=()=>{this.userMap.forEach((e=>{const t=e.receivedMessagesMap,n=e.nextExpectedSequenceNumber;for(;t.has(n);){const i=t.get(n);t.delete(n),this.receiveMessage(i),e.nextExpectedSequenceNumber++}}))};if(!e)return void t();const n=e,i=n._uid,r=n._seq,o=this.userMap.get(i),s=o.receivedMessagesMap,a=o.isStart,c=o.nextExpectedSequenceNumber;if(r<c)return this.ack(e._id),void SL.debug("[external-signal] receive old message, seq: ".concat(r,", ").concat(e._message));s.set(r,e),a&&r===c&&(this.receiveMessage(e),s.delete(c),o.nextExpectedSequenceNumber++,t())}receiveMessage(e){const t=e._id,n=e._type,i=e._message,r=e._uid;if(xP("SHOW_P2P_LOG")&&SL.debug("receive message",e),t){let o;switch(e._type!==QF.ACK&&(i&&(o=JSON.parse(i)),this.ack(e._id)),e._type){case QF.CANDIDATE:case QF.CONTROL:this.signal.emit(n,o,r);break;case QF.PUBLISH:case QF.UNPUBLISH:case QF.RESTART_ICE:case QF.CALL:o.uid=r,dD(this.signal,n,o).then((t=>{this.response(e._id,t)})).catch((()=>{this.response(e._id,void 0,!0)}));break;case QF.ACK:this.getListeners("res-@".concat(t,"_ack")).length>0&&this.emit("res-@".concat(t,"_ack"));break;case QF.RESPONSE:{const e=o,n=e.success,i=e.message;this.emit("res-@".concat(t),n?"success":"failed",i);break}}}}splitMessage(e){if(e.length<cae.MAX_MESSAGE_SIZE)return[e];const t=[],n=JSON.parse(e).remoteToken,i=kD(6,"");let r=0,o=800;const s=Math.ceil(e.length/o);for(;e.length>0;){r++;const a={id:i,index:r,total:s,payload:e.slice(0,o),token:"".concat(this.token,"_").concat(n)};JSON.stringify(a).length>cae.MAX_MESSAGE_SIZE?o-=50:(t.push(a),e=e.slice(o))}return t.map((e=>JSON.stringify(e)))}handleCheckToken(e,t){return e.token!==t?(SL.debug("token changed, from ".concat(e.token," to ").concat(t)),this.reset(e.uid,t),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout((()=>{SL.debug("token timeout, ".concat(t)),this.reset(e.uid)}),xP("MAX_P2P_TIMEOUT")),!0)}async handleUserOnline(){const e=await dD(this.signal,QF.CALL,void 0),t=await this.send(QF.CALL,e);this.signal.emit(iF.P2P_CONNECTION,t,!0)}async reset(e,t){const n=this.userMap.get(e);n&&(this.emit($F.ABORT),this.signal.emit(sF.ON_USER_OFFLINE,{uid:n.uid,reason:tB.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),t||(SL.debug("change local token from ".concat(t," to ").concat(t)),this.token=kD(6,"")))}clear(){this._sequence=0,this.userMap.clear(),this.tokenInterval&&window.clearTimeout(this.tokenInterval),this.tokenInterval=void 0,this.tokenTimeout&&window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0,this.emit($F.ABORT)}}zA(cae,"MAX_SIZE",1),zA(cae,"MAX_MESSAGE_SIZE",1024);class dae extends YN{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===nF.CONNECTED?this.emit(iF.WS_CONNECTED):e===nF.RECONNECTING?this.emit(iF.WS_RECONNECTING,this._websocketReconnectReason):e===nF.CLOSED&&this.emit(iF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get reportUrl(){return this.websocket&&this.websocket.reportUrl||null}get rtt(){return this.rttRolling.mean()}constructor(e,t){super(),zA(this,"__name__","P2PSignal"),zA(this,"_disconnectedReason",void 0),zA(this,"_websocketReconnectReason",void 0),zA(this,"_connectionState",nF.CLOSED),zA(this,"reconnectToken",void 0),zA(this,"p2pToken",void 0),zA(this,"websocket",void 0),zA(this,"openConnectionTime",void 0),zA(this,"clientId",void 0),zA(this,"lastMsgTime",Date.now()),zA(this,"uploadCache",[]),zA(this,"uploadCacheInterval",void 0),zA(this,"rttRolling",new eP(5)),zA(this,"pingpongTimer",void 0),zA(this,"pingpongTimeoutCount",0),zA(this,"joinResponse",void 0),zA(this,"multiIpOption",void 0),zA(this,"initError",void 0),zA(this,"spec",void 0),zA(this,"store",void 0),zA(this,"_external_signal",void 0),zA(this,"onWebsocketMessage",(e=>{if(e.data instanceof ArrayBuffer)return void this.emit(iF.ON_BINARY_DATA,e.data);const t=JSON.parse(e.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else if(Object.prototype.hasOwnProperty.call(t,"_type")){switch(t._type){case sF.ON_DATA_STREAM:return void this.handleDataStream(t._message);case sF.MUTE_AUDIO:case sF.MUTE_VIDEO:case sF.ON_P2P_LOST:case sF.ON_USER_ONLINE:return;case sF.ON_USER_OFFLINE:const e=t._message.uid;return SL.debug("[".concat(this.clientId,"] user-offline uid: ").concat(e)),void this._external_signal.reset(e)}if(this.emit(t._type,t._message),t._type===sF.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===sF.ON_USER_BANNED)switch(t._message.error_code){case 14:this.close($N.UID_BANNED);break;case 15:this.close($N.IP_BANNED);break;case 16:this.close($N.CHANNEL_BANNED)}if(t._type===sF.ON_USER_LICENSE_BANNED)switch(t._message.error_code){case tF.ERR_LICENSE_MISSING:this.close($N.LICENSE_MISSING);break;case tF.ERR_LICENSE_EXPIRED:this.close($N.LICENSE_EXPIRED);break;case tF.ERR_LICENSE_MINUTES_EXCEEDED:this.close($N.LICENSE_MINUTES_EXCEEDED);break;case tF.ERR_LICENSE_PERIOD_INVALID:this.close($N.LICENSE_PERIOD_INVALID);break;case tF.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close($N.LICENSE_MULTIPLE_SDK_SERVICE);break;case tF.ERR_LICENSE_ILLEGAL:this.close($N.LICENSE_ILLEGAL);break;default:this.close()}}})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new fB("gateway-".concat(this.clientId),this.spec.retryConfig,!0,xP("JOIN_GATEWAY_USE_DUAL_DOMAIN"),xP("JOIN_GATEWAY_USE_443PORT_ONLY"),t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===nF.CONNECTED&&this.reconnect("retry",sD.OFFLINE)})),this.p2pToken=kD(6,""),this._external_signal=new cae(this,this.p2pToken)}async request(e,t,n,i){const r=kD(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new cp(((e,t)=>{if(this.connectionState===nF.CONNECTED)return e();const n=()=>{this.off(iF.WS_CLOSED,i),e()},i=()=>{this.off(iF.WS_CONNECTED,n),t(new ON(wN.WS_ABORT))};this.once(iF.WS_CONNECTED,n),this.once(iF.WS_CLOSED,i)}));if(this.connectionState!==nF.CONNECTING&&this.connectionState!==nF.RECONNECTING||e===rF.JOIN||e===rF.REJOIN||await a(),this.websocket.sendMessage(o,!0),i)return;const c=new cp(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(iF.WS_CLOSED,c),this.off(iF.WS_RECONNECTING,c),this.emit(iF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new ON(wN.WS_ABORT,"type: ".concat(e))),this.off(iF.WS_CLOSED,c),this.off(iF.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(iF.WS_CLOSED,c),this.once(iF.WS_RECONNECTING,c),LD(xP("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(SL.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(iF.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===nF.CLOSED||e===rF.LEAVE)throw new ON(wN.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===rF.JOIN||e===rF.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=oB(l),h=new ON(wN.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message,desc:u.desc});return"success"===u.action?d.message:(SL.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===tF.ERR_TOO_MANY_BROADCASTERS?e===rF.JOIN||e===rF.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===tF.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,SL.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",sD.MULTI_IP)):this.reconnect(u.action,sD.SERVER_ERROR),e===rF.JOIN||e===rF.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new cp((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void SL.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(oF.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=xP("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==nF.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),xP("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,t){const n={_type:e,_message:t};this.websocket.sendMessage(n)}async sendExtensionMessage(e,t,n){return await this._external_signal.send(e,t,n)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cp(((t,n)=>{this.once(iF.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(iF.WS_CLOSED,(()=>n(this.initError||new ON(wN.WS_ABORT)))),this.connectionState=nF.CONNECTING,this.websocket.init(e).catch(n)}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this._external_signal.clear(),this._disconnectedReason=e||$N.LEAVE,this.connectionState=nF.CLOSED,SL.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=kD(6,""),this._external_signal.clear(),this._external_signal=new cae(this,this.p2pToken)}async join(){if(!this.joinResponse){this.emit(iF.ABORT_P2P_EXECUTION);const e=await dD(this,iF.REQUEST_JOIN_INFO),t=await this.request(rF.JOIN,e);if(!t)return this.emit(iF.REPORT_JOIN_GATEWAY,wN.TIMEOUT,this.reportUrl||""),!1;this.joinResponse=t,this.emit(iF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=nF.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){return!1}handleDataStream(e){try{var t;const n=ID(e.payload),i=(new TextDecoder).decode(n),r=JSON.parse(i);"total"in r&&"id"in r||Ui(t=Object.values(QF)).call(t,r._type)?(r._uid=e.uid,this._external_signal.onMessage(r)):this.emit(sF.ON_DATA_STREAM,e)}catch(t){this.emit(sF.ON_DATA_STREAM,e)}}handleNotification(e){SL.debug("[".concat(this.clientId,"] receive notification: "),e);const t=oB(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?e.code===tF.ERR_REPEAT_JOIN_CHANNEL&&xP("IGNORE_UID_CHECK")?void this.close($N.UID_CONFLICT):("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close($N.UID_BANNED),void this.close()):void this.reconnect(t.action,sD.SERVER_ERROR);SL.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=xP("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(SL.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>xP("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",sD.TIMEOUT):this.request(rF.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),xP("REPORT_STATS")&&this.send(rF.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleWebsocketEvents(){this.websocket.on(cF.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(iF.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(cF.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(cF.CLOSED,(()=>{this.connectionState=nF.CLOSED})),this.websocket.on(cF.FAILED,(()=>{this._disconnectedReason=$N.NETWORK_ERROR,this.connectionState=nF.CLOSED})),this.websocket.on(cF.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===nF.CONNECTED?this.connectionState=nF.RECONNECTING:this.connectionState=nF.CONNECTING})),this.websocket.on(cF.WILL_RECONNECT,((e,t,n)=>{"retry"!==e?(SL.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):SL.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),n(e)})),this.websocket.on(cF.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.join().catch((e=>{if(this.emit(iF.REPORT_JOIN_GATEWAY,e,this.reportUrl||""),e instanceof ON&&e.code===wN.UNEXPECTED_RESPONSE&&e.data.code===tF.ERR_NO_AUTHORIZED)return SL.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",sD.SERVER_ERROR);SL.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",sD.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(cF.REQUEST_NEW_URLS,((e,t)=>{dD(this,iF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(cF.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(sF.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}))}}const lae={name:"P2PChannel",create:function(e){let t=e.store,n=e.statsCollector;return new sae(t,n)},createSubmodule:function(e){let t=e.store,n=e.spec;return new dae(n,t)}};function uae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function hae(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?uae(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):uae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}class pae{constructor(e){zA(this,"sessionDesc",void 0),zA(this,"localCapabilities",void 0),zA(this,"rtpCapabilities",void 0),zA(this,"candidates",void 0),zA(this,"_originCandidates",void 0),zA(this,"iceParameters",void 0),zA(this,"dtlsParameters",void 0),zA(this,"setup",void 0),zA(this,"currentMidIndex",void 0),zA(this,"cname",void 0);const t=e=vD(e),n=t.iceParameters,i=t.dtlsParameters,r=t.candidates,o=t.rtpCapabilities,s=t.setup,a=t.localCapabilities,c=t.sdkCodec,d=t.cname,l=zP("v=0\no=- 0 0 IN IP4 127.0.0.1\ns=AgoraGateway\nt=0 0\na=group:BUNDLE audio video\na=msid-semantic: WMS\na=ice-lite\nm=audio 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:audio\nm=video 9 UDP/TLS/RTP/SAVPF 0\nc=IN IP4 127.0.0.1\na=rtcp:9 IN IP4 0.0.0.0\na=sendrecv\na=rtcp-mux\na=rtcp-rsize\na=mid:video\n");this.rtpCapabilities=o,this.candidates=r,this._originCandidates=vD(r),this.iceParameters=n,this.dtlsParameters=i,this.setup=s,this.localCapabilities=a,this.cname=d;for(let e=0;e<l.mediaDescriptions.length;e++){const t=l.mediaDescriptions[e];if(t.attributes.iceUfrag=n.iceUfrag,t.attributes.icePwd=n.icePwd,t.attributes.fingerprints=i.fingerprints,t.attributes.candidates=r,t.attributes.setup=s,"video"===t.media.mediaType){t.media.fmts=o.videoCodecs.map((e=>e.payloadType.toString(10)));const e=o.videoCodecs.filter((e=>{var t,n;return null===(t=e.rtpMap)||void 0===t?void 0:Ui(n=t.encodingName.toLowerCase()).call(n,c)})),n=o.videoCodecs.filter((t=>!Ui(e).call(e,t)));t.attributes.payloads=[...e,...n],t.attributes.extmaps=o.videoExtensions}"audio"===t.media.mediaType&&(t.media.fmts=o.audioCodecs.map((e=>e.payloadType.toString(10))),t.attributes.payloads=o.audioCodecs,t.attributes.extmaps=o.audioExtensions),l.mediaDescriptions[e]=this.mungMediaDesc(t)}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return ZP(this.sessionDesc)}send(e,t,n){const i=H7(t,this.cname),r=i.ssrcs,o=i.ssrcGroups,s=this.sessionDesc.mediaDescriptions.find((t=>e===UF.VIDEO?"video"===t.media.mediaType:"audio"===t.media.mediaType)),a=r[0].attributes.label,c=r[0].attributes.mslabel;return s.attributes.ssrcs=s.attributes.ssrcs.concat(r),s.attributes.ssrcGroups=s.attributes.ssrcGroups.concat(o),{id:a,mslabel:c}}batchSend(e){return e.map((e=>{let t=e.kind,n=e.ssrcMsg;return this.send(t,n,void 0)}))}stopSending(e){this.sessionDesc.mediaDescriptions.forEach((t=>{const n=[],i=[],r=[];t.attributes.ssrcs.forEach((t=>{Ui(e).call(e,t.attributes.label||"")?r.push(t):n.push(t)})),t.attributes.ssrcGroups.forEach((e=>{var t;Ui(t=r.map((e=>e.ssrcId))).call(t,e.ssrcIds[0])||i.push(e)})),t.attributes.ssrcs=n,t.attributes.ssrcGroups=i}))}mute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));t.attributes.direction="inactive"}unmute(e){const t=this.sessionDesc.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));t.attributes.direction="sendonly"}receive(e,t,n){e.forEach(((e,t)=>{const n=e._mediaStreamTrack,i=this.sessionDesc.mediaDescriptions.findIndex((e=>e.attributes.mid===n.kind)),r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],e);this.sessionDesc.mediaDescriptions[i]=r}))}stopReceiving(e){}updateCandidates(e){const t=this._originCandidates.filter((e=>"udp"===e.transport)),n=[];if(t.forEach((e=>{n.push(hae(hae({},e),{},{foundation:"tcpcandidate",priority:Number(e.priority)-1+"",transport:"tcp",port:Number(e.port)+90+""}))})),0!==t.length){switch(e){case VF.TCP_RELAY:this.candidates=n;break;case VF.UDP_TCP_RELAY:case VF.RELAY:this.candidates=[...t,...n];break;default:this.candidates=t}for(const e of this.sessionDesc.mediaDescriptions)e.attributes.candidates=this.candidates}}restartICE(e){e=vD(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach((t=>{t.attributes.iceUfrag=e.iceUfrag,t.attributes.icePwd=e.icePwd}))}predictReceivingMids(e){const t=[];for(let n=0;n<e;n++)t.push((this.currentMidIndex+n+1).toString(10));return t}mungRecvMediaDsec(e,t){const n=vD(e);return Y7(n,t),J7(n,t),n}updateRecvMedia(e,t){const n=this.sessionDesc.mediaDescriptions.findIndex((t=>t.attributes.mid===e));if(-1!==n){const e=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],t);this.sessionDesc.mediaDescriptions[n]=e}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,t,n){const i=this.sessionDesc.mediaDescriptions.find((t=>e===UF.VIDEO?"video"===t.attributes.mid:"audio"===t.attributes.mid));if(i){const e=i.attributes.ssrcs.find((e=>e.attributes.label===t));var r;if(e)e.attributes.label=n,null===(r=e.attributes.msid)||void 0===r||r.replace(t,n)}}mungMediaDesc(e){const t=vD(e);return X7(t),function(e){const t=e.attributes.extmaps.find((e=>U7(e.extensionName)));t&&e.attributes.extmaps.splice(e.attributes.extmaps.indexOf(t),1),e.attributes.payloads.forEach((e=>{const t=e.rtcpFeedbacks.findIndex((e=>"transport-cc"===e.type));-1!==t&&e.rtcpFeedbacks.splice(t,1)}))}(t),t}getSSRC(e){for(const t of this.sessionDesc.mediaDescriptions)for(const n of t.attributes.ssrcs)if(n.attributes.label===e)return[n]}}var _ae;function Eae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function mae(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Eae(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Eae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let fae=(_ae=class e extends MF{get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Ui(t=Object.keys(GP)).call(t,e)})))]}constructor(t,n){super(t,n),zA(this,"store",void 0),zA(this,"peerConnection",void 0),zA(this,"remoteSDP",void 0),zA(this,"initialOffer",void 0),zA(this,"statsFilter",void 0),zA(this,"useRTX",!1),zA(this,"localCapabilities",void 0),zA(this,"localCandidateCount",0),zA(this,"allCandidatesReceived",!1),zA(this,"establishPromise",void 0),zA(this,"mutex",void 0),this.store=n,this.mutex=new JD("P2PConnection-mutex",n.clientId),this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.statsFilter=bP(this.peerConnection,xP("STATS_UPDATE_INTERVAL"),void 0,$O()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}async establish(){try{const e=await this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const t=B7(e.sdp),n=F7(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:xP("FILTER_VIDEO_FEC"),filterAudioFec:xP("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=n,this.initialOffer=e,mae(mae({},t),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:n},offerSDP:e.sdp})}catch(e){throw new ON(wN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async updateRemoteConnect(){}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new pae(mae(mae({},e),{},{rtpCapabilities:e.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));const t=this.remoteSDP.toString();await this.peerConnection.setLocalDescription(this.initialOffer),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(e.toString()))}}async updateRemoteRTPCapabilities(e,t){throw new ON(wN.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}getPreMedia(e){}send(e,t){var n=this;return Ww((function*(){const i=yield Kw(n.mutex.lock());try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const r=e.map((e=>n.peerConnection.addTrack(e._mediaStreamTrack))),o=yield Kw(n.peerConnection.createOffer()),s=zP(o.sdp),a=e.map((e=>{const t=e._mediaStreamTrack,i=s.mediaDescriptions.find((e=>e.attributes.mid===t.kind));if(!i)throw new Error("Cannot extract ssrc from mediaDescription.");return function(e,t,n){const i=e.attributes.ssrcs.filter((e=>e.attributes.label===t)),r=e.attributes.ssrcGroups;if(0===i.length)throw new Error("Cannot extract ssrc from plan-b SDP.");if(r&&i.length>1){const e=r.find((e=>-1!==e.ssrcIds.indexOf(i[0].ssrcId)));return e?[{ssrcId:e.ssrcIds[0],rtx:n?e.ssrcIds[1]:void 0}]:[{ssrcId:i[0].ssrcId}]}return[{ssrcId:i[0].ssrcId}]}(i,t.id,n.useRTX)}));let c;try{c=yield a}catch(e){throw r.forEach((e=>{zO()&&e.replaceTrack(null),n.peerConnection.removeTrack(e)})),e}const d=n.mungSendOfferSDP(o.sdp,e);n.remoteSDP.receive(e,t,c);const l=n.remoteSDP.toString();return yield Kw(n.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Kw(n.applySendEncodings(r,e)),yield Kw(n.peerConnection.setRemoteDescription({type:"answer",sdp:l})),e.map(((e,t)=>{const n=e._mediaStreamTrack.id;return{localSSRC:a[t],id:n}}))}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(e.toString()))}finally{i()}}))()}async stopSending(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const t=this.peerConnection.getSenders().filter((t=>{var n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.id)||"")}));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");t.map((e=>{zO()&&e.replaceTrack(null),this.peerConnection.removeTrack(e)}));const n=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(e.toString()))}}async receive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const n=this.remoteSDP.send(e,t,i),r=n.id,o=n.mslabel,s=new cp(((t,n)=>{const i=setTimeout((()=>{n(new Error("Cannot receive track, id: ".concat(r)))}),1e4),s=n=>{const a=GO();if(("Safari"===a.name&&11===Number(a.version)||eN())&&n.track.id!==r&&n.streams[0].id===o){var c;const o=n.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(e,r,n.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(i),void t(o)}if(n.track.id===r)return this.peerConnection.removeEventListener("track",s),clearTimeout(i),void t(n.track)};this.peerConnection.addEventListener("track",s)})),a=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:a});const c=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(c);return{track:await s,id:r}}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const n=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(n)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){}async unmuteRemote(e){}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.id)||"")}));if(t.length!==e.length)throw new Error("sender' length doesn't match mids' length.");t.map((e=>{if(zO()&&e.track)e.track.enabled=!1;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!1)),e.setParameters(t)}}))}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const t=this.peerConnection.getSenders().filter((t=>{var n;return-1!==e.indexOf((null===(n=t.track)||void 0===n?void 0:n.id)||"")}));if(t.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");t.map((async e=>{if(zO()&&e.track)e.track.enabled=!0;else{const t=e.getParameters();t.encodings.forEach((e=>e.active=!0)),await e.setParameters(t)}}));const n=await this.peerConnection.createOffer();await this.peerConnection.setLocalDescription(n);const i=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return Ww((function*(){const n=yield Kw(t.mutex.lock("From P2PConnection.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=JL().supportPCSetConfiguration;if(e===VF.RELAY&&!i)return;if(i){const n=t.peerConnection.getConfiguration(),i=e===VF.RELAY?"relay":"all";n.iceTransportPolicy!==i&&(SL.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(n.iceTransportPolicy,"] to [").concat(i,"]")),n.iceTransportPolicy=i,t.peerConnection.setConfiguration(n))}e!==VF.RELAY&&t.remoteSDP.updateCandidates(e);const r=yield Kw(t.peerConnection.createOffer({iceRestart:!0}));if(!r.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const o=B7(r.sdp),s=(yield o.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(s);const a=t.remoteSDP.toString();yield Kw(t.peerConnection.setLocalDescription(r)),yield Kw(t.peerConnection.setRemoteDescription({type:"answer",sdp:a}))}catch(e){SL.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}close(){var e;this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.statsFilter.destroy()}getStats(){return this.statsFilter.getStats()}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const e=await this.peerConnection.createOffer(),n=this.mungSendOfferSDP(e.sdp,[t]);this.remoteSDP.updateRecvMedia(t._mediaStreamTrack.kind,t);const i=this.remoteSDP.toString();await this.peerConnection.setLocalDescription({type:"offer",sdp:n}),await this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getSenders().filter((t=>{var n;return(null===(n=t.track)||void 0===n?void 0:n.id)===e}));1===n.length&&await this.applySendEncodings(n,[t])}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getSenders().find((e=>{var n;return(null===(n=e.track)||void 0===n?void 0:n.id)===t}));n&&await n.replaceTrack(e._mediaStreamTrack)}createDataChannels(e,t){throw new ON(wN.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new ON(wN.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),xP("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[],sdpSemantics:"plan-b"};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(eD(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),xP("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),n}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}async updateRtpSenderEncodings(e,t){var n;if(!t){t=this.peerConnection.getSenders().find((t=>{var n;return(null===(n=t.track)||void 0===n?void 0:n.id)===e._mediaStreamTrack.id}))}if(!t)return SL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!JL().supportSetRtpSenderParameters)return SL.warn("Browser not support set rtp-sender parameters");const i={},r={};if(e instanceof TV)switch(e._optimizationMode){case"motion":i.degradationPreference="maintain-framerate";break;case"detail":i.degradationPreference="maintain-resolution";break;default:i.degradationPreference="balanced"}if(xP("DSCP_TYPE")&&SN()){var o;const e=xP("DSCP_TYPE");Ui(o=["very-low","low","medium","high"]).call(o,e)&&(r.networkPriority=e)}const s=t.getParameters(),a=null===(n=s.encodings)||void 0===n?void 0:n[0];a&&Object.assign(a,r),Object.assign(s,i),SL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(s.encodings))),await t.setParameters(s)}async applySendEncodings(e,t){try{if(!JL().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];i&&r&&await this.updateRtpSenderEncodings(r,i)}}catch(e){SL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t){const n=zP(e);return t.forEach(((e,t)=>{const i=e._mediaStreamTrack,r=n.mediaDescriptions.find((e=>e.attributes.mid===i.kind));r&&Y7(r,e)})),ZP(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.call(this,e,t)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e).map(((t,n)=>{let i=t.id,r=t.mslabel;const o=e[n].kind;return new cp(((e,t)=>{const n=setTimeout((()=>{t(new Error("Cannot receive track, id: ".concat(i)))}),1e4),s=t=>{const a=GO();if("Safari"===a.name&&11===Number(a.version)&&t.track.id!==i&&t.streams[0].id===r){var c;const r=t.streams[0].getTracks()[0];return null===(c=this.remoteSDP)||void 0===c||c.updateTrackLabel(o,i,t.track.id),this.peerConnection.removeEventListener("track",s),clearTimeout(n),void e({track:r,id:i})}if(t.track.id===i)return this.peerConnection.removeEventListener("track",s),clearTimeout(n),void e({track:t.track,id:i})};this.peerConnection.addEventListener("track",s)}))})),n=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const i=await this.peerConnection.createAnswer();return await this.peerConnection.setLocalDescription(i),await cp.all(t)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(e.toString()))}}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return null==t?void 0:t[0].ssrcId}setConfiguration(t){if(JL().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}}},Zx(_ae.prototype,"connect",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"connect"),_ae.prototype),Zx(_ae.prototype,"stopSending",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"stopSending"),_ae.prototype),Zx(_ae.prototype,"receive",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"receive"),_ae.prototype),Zx(_ae.prototype,"stopReceiving",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"stopReceiving"),_ae.prototype),Zx(_ae.prototype,"muteRemote",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"muteRemote"),_ae.prototype),Zx(_ae.prototype,"unmuteRemote",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"unmuteRemote"),_ae.prototype),Zx(_ae.prototype,"muteLocal",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"muteLocal"),_ae.prototype),Zx(_ae.prototype,"unmuteLocal",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"unmuteLocal"),_ae.prototype),Zx(_ae.prototype,"close",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"close"),_ae.prototype),Zx(_ae.prototype,"updateEncoderConfig",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"updateEncoderConfig"),_ae.prototype),Zx(_ae.prototype,"updateSendParameters",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"updateSendParameters"),_ae.prototype),Zx(_ae.prototype,"replaceTrack",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"replaceTrack"),_ae.prototype),Zx(_ae.prototype,"getRemoteSSRC",[gae],Object.getOwnPropertyDescriptor(_ae.prototype,"getRemoteSSRC"),_ae.prototype),_ae);function gae(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("Locking from P2PConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}const Sae={name:"PlanBConnection",create:function(e){let t=e.store,n=e.spec;return new fae(n,t)}},Tae={interceptLocalAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!JL().supportWebRTCEncodedTransform)return void SL.warning("browser not support audio encoded transform");if(QV.has(e))return;if(!e.track)return;const n={track:e.track};if(JO()){if(!e.createEncodedStreams)return void SL.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void SL.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){n.controller||(n.controller=o),e.track&&e.track.id!==n.track.id&&(SL.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const s=t.metadata&&t.metadata();s?function(e,t){const n=t.chunk,i=t.controller,r=ZV.METADATA;n.data=function(e,t,n){const i=n.byteLength,r=i+JV+zV,o=YV+XV+r,s=new ArrayBuffer(e.byteLength+o),a=new DataView(s);a.setUint8(0,HV),a.setUint16(1,r),a.setUint8(3,t),a.setUint16(4,i);for(let e=0;e<i;e++)a.setUint8(6+e,n[e]);const c=new Uint8Array(a.buffer);return c.set(new Uint8Array(e),o),c.buffer}(n.data,r,e),i.enqueue(n)}(s,{sender:e,chunk:r,controller:o}):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(zO()){if("undefined"==typeof RTCRtpScriptTransform)return void SL.warning("browser not support RTCRtpScriptTransform");const r=KV(),o=new MessageChannel;await new cp((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"audio-metadata-tx",port:o.port2},[o.port2]);e.transform=s,await new cp((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=r=>{var s;if(r.data.transformed&&e.track&&(null===(s=e.track)||void 0===s?void 0:s.id)!==n.track.id)SL.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i);else if(r.data.getMetadata){const e=t.metadata&&t.metadata();e&&o.port1.postMessage({metadata:e})}},n.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const t=QV.get(e);if(t){QV.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){SL.warning(e&&e.message)}}}QV.set(e,n),e.track.addEventListener("ended",i)},interceptRemoteAudioFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!JL().supportWebRTCEncodedTransform)return void SL.warning("browser not support audio encoded transform");if(Sx.has(e))return;const n={track:e.track,onMetadata:t.onMetadata,onPts:t.onPts};if(JO()&&!eN()){if(!e.createEncodedStreams)return void SL.warning("browser not support createEncodedStreams() API");iN(xO.CHROME,87,116)||(t.enableTopn=!1);let r=null;try{r=e.createEncodedStreams()}catch(e){return void SL.error("create audio-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){n.controller||(n.controller=o),e.track&&e.track.id!==n.track.id&&(SL.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i)),t.enableTopn?function(e,t,n){var i;const r=qV(new DataView(t.data));if(!r)return n.enqueue(t);const o=e.track.id;Tx.set(o,e.track);const s=null===(i=r.tlv.find((e=>e.tag===ZV.AUDIO_LEVEL)))||void 0===i?void 0:i.value;let a=0;"number"==typeof s&&(a=127-s);const c=function(e,t){let n=dx.get(e);if(n||(n=function(e){const t=new sx;return dx.set(e,t),lx||(lx=new cx(xP("TOPN_SILENCE_THRESHOLD")||500),lx.on("ActiveSpeakerChanged",(e=>{null!=e&&(ux=e)}))),lx.addSpeakers([t]),t}(e)),dx.size<=hx)return{selected:!0,speaker:n};if(!lx)throw new Error("no active speaker detector");return lx.levelChanged(n.id,t),px=lx.loudest.map((e=>e.id)),ux&&!Ui(px).call(px,ux)&&px.length>=hx&&px.pop(),{selected:Ui(px).call(px,n.id)||n.id===ux,speaker:n}}(e,Math.round(Math.pow(10,a/60)-1)),d=c.selected,l=c.speaker,u=function(e,t,n){const i=_x.get(e)||new fx(e,t);return i.score=n,_x.set(e,i),function(e){if(Ex.set(e,!0),!mx)return void(mx=Date.now());const t=Date.now();t-mx>1e3&&(Ex.get(e)?Ex.set(e,!1):(gx(e),Ex.delete(e)),mx=t)}(e),i}(o,e.track,l.energyScore);u.addSample(d),u.active&&(t.data=r.frame.buffer,n.enqueue(t))}(e,r,o):t.enableMetadata||t.enablePts?function(e,t,n,i){const r=new DataView(e.data),o=r.getUint8(0);let s;if(0!=(128&o)&&71!==o){const t=function(e){if(e.byteLength<=0)return[];const t=[];let n=0;for(;n<e.byteLength;){const i=(128&e.getUint8(n))>>7,r=127&e.getUint8(n);if(!(i&&n+4<=e.byteLength)){n++;break}{const i=e.getUint32(n,!1),o=(16776192&i)>>10,s=1023&i;t.push({pt:r,ts_offset:o,length:s,data:new Uint8Array}),n+=4}}let i=e.byteLength-n;for(const r of t){if(r.length>i)return console.warn("Broken red payload"),[];r.length>0&&(r.data=new Uint8Array(e.buffer,e.byteOffset+n,r.length),n+=r.length,i-=r.length)}if(i>0){const r={pt:t.length>0?t[t.length-1].pt:0,ts_offset:0,length:i,data:new Uint8Array(e.buffer,e.byteOffset+n,i)};t.push(r)}return t}(r);if(t.length>0){const n=function(e){let t=0;for(let n=0;n<e.length;n++)t+=n<e.length-1?4:1,t+=e[n].length;const n=new Uint8Array(t);let i=0;for(let t=0;t<e.length;t++)if(t<e.length-1){const r=(2147483648|(127&e[t].pt)<<24|(262143&e[t].ts_offset)<<10|1023&e[t].length)>>>0;n[i++]=r>>24&255,n[i++]=r>>16&255,n[i++]=r>>8&255,n[i++]=255&r}else n[i++]=127&e[t].pt;for(const t of e)n.set(t.data,i),i+=t.length;return n}(t.map((e=>{const t=new Uint8Array(e.length);t.set(e.data);const n=qV(new DataView(t.buffer));return null!=n&&n.frame&&(e.data=null==n?void 0:n.frame),s=n,e})));e.data=n.buffer}}else s=qV(r),s&&(e.data=s.frame.buffer);if(t.enqueue(e),!s)return;const a=s.tlv.find((e=>e.tag===ZV.METADATA));a&&n&&a.value instanceof Uint8Array&&n(a.value);const c=s.tlv.find((e=>e.tag===ZV.AUDIO_64_BIT_PTS));c&&i&&c.value instanceof Uint8Array&&8==c.value.length&&i(new DataView(c.value.buffer).getBigUint64(0,!0))}(r,o,t.onMetadata,t.onPts):o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else{if("undefined"==typeof RTCRtpScriptTransform)return void SL.warning("browser not support RTCRtpScriptTransform");const t=KV(),r=new MessageChannel;await new cp((e=>t.onmessage=t=>{"registered"===t.data&&e(void 0)}));const o=new RTCRtpScriptTransform(t,{name:"audio-metadata-rx",port:r.port2},[r.port2]);e.transform=o,await new cp((e=>t.onmessage=t=>{"started"===t.data&&e(void 0)})),r.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==n.track.id?(SL.debug("audio track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i)):t.data.metadata&&n.onMetadata?n.onMetadata(t.data.metadata):t.data.pts&&n.onPts&&n.onPts(t.data.pts)},n.worker=t}function i(){e.track.removeEventListener("ended",i),function(e){const t=Sx.get(e);if(t){!function(e){const t=dx.get(e);t&&(dx.delete(e),lx&&(lx.removeSpeakers([t]),0===dx.size&&(lx.destroy(),lx=null)))}(e),gx(e.track.id),Sx.delete(e);try{var n,i;null===(n=t.controller)||void 0===n||n.terminate(),null===(i=t.worker)||void 0===i||i.terminate()}catch(e){SL.warning(e&&e.message)}}}(e)}Sx.set(e,n),e.track.addEventListener("ended",i)},interceptLocalVideoFrame:async function(e,t){if(!JL().supportWebRTCEncodedTransform)return void SL.warning("browser not support video encoded transform");if(Ix.has(e))return;if(!e.track)return;const n={track:e.track};if(JO()){if(!e.createEncodedStreams)return void SL.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void SL.error("create video-encoded-streams error",e&&e.message)}const o=[];t.on("sei-to-send",(e=>{o.push(e)}));const s=new TransformStream({transform(t,r){n.controller||(n.controller=r),e.track&&e.track.id!==n.track.id&&(SL.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const s=bx(new Uint8Array(t.data)),a=o.shift();if(a){const e=function(e,t,n){switch(n){case Rx:return function(e,t){const n=Cx(t),i=n.length,r=Math.floor(i/255),o=i%255,s=new Uint8Array(6+r+1+i+1+e.byteLength);s[0]=0,s[1]=0,s[2]=0,s[3]=1,s[4]=6,s[5]=101;let a=0;for(;a<r;)s[6+a]=255,a++;return s[6+a]=o,a++,s.set(n,6+a),a+=i,s[6+a]=128,a++,s.set(new Uint8Array(e),6+a),s.buffer}(e,t);case vx:return function(e,t){const n=Cx(t),i=n.length,r=Math.floor(i/255),o=i%255,s=new Uint8Array(7+r+1+i+1+e.byteLength);s[0]=0,s[1]=0,s[2]=0,s[3]=1,s[4]=78,s[5]=1,s[6]=101;let a=0;for(;a<r;)s[7+a]=255,a++;return s[7+a]=o,a++,s.set(n,7+a),a+=i,s[7+a]=128,a++,s.set(new Uint8Array(e),7+a),s.buffer}(e,t);default:return null}}(t.data,a,s);e&&(t.data=e)}r.enqueue(t)}});r.readable.pipeThrough(s).pipeTo(r.writable)}else{if(!zO())return;{if("undefined"==typeof RTCRtpScriptTransform)return void SL.warning("browser not support RTCRtpScriptTransform");const r=KV(),o=new MessageChannel;await new cp((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"sei-tx",port:o.port2},[o.port2]);e.transform=s,await new cp((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),t.on("sei-to-send",(e=>{o.port1.postMessage({sei:e})})),o.port1.onmessage=t=>{var r;t.data.transformed&&e.track&&(null===(r=e.track)||void 0===r?void 0:r.id)!==n.track.id&&(SL.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i))},n.worker=r}}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}const t=Ix.get(e);if(t){Ix.delete(e);try{var n,r;null===(n=t.controller)||void 0===n||n.terminate(),null===(r=t.worker)||void 0===r||r.terminate()}catch(e){SL.warning(e&&e.message)}}}Ix.set(e,n),e.track.addEventListener("ended",i)},interceptRemoteVideoFrame:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!JL().supportWebRTCEncodedTransform)return void SL.warning("browser not support video encoded transform");if(!e.track)return;if(Ax.has(e)){const n=Ax.get(e);return void(n&&(n.onSei=t.onSei))}const n={track:e.track,onSei:t.onSei};if(JO()){if(!e.createEncodedStreams)return void SL.warning("browser not support createEncodedStreams() API");let r=null;try{r=e.createEncodedStreams()}catch(e){return void SL.error("create video-encoded-streams error",e&&e.message)}const o=new TransformStream({transform(r,o){if(n.controller||(n.controller=o),!n.firstFrameInfo){var s;const e=r.getMetadata()||{};n.firstFrameInfo=Xk({type:r.type,rtpTimestamp:r.timestamp,payloadType:e.payloadType||0,ssrc:e.synchronizationSource||0,length:r.data.byteLength},"mimeType"in e?{mimeType:e.mimeType}:{}),null===(s=t.onFirstFrame)||void 0===s||s.call(t,n.firstFrameInfo)}e.track&&e.track.id!==n.track.id&&(SL.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i));const a=function(e,t){switch(t){case Rx:return function(e){const t=new DataView(e.data);let n=0;for(;n+4<e.data.byteLength;){if(0===t.getUint8(n+0)&&0===t.getUint8(n+1)&&0===t.getUint8(n+2)&&1===t.getUint8(n+3)&&6===t.getUint8(n+4)){let i=n+6,r=0,o=0;for(;255===(o=t.getUint8(i++));)r+=255;r+=o;const s=yx(e.data,i,r);return new Uint8Array(s)}n++}return null}(e);case vx:return function(e){const t=new DataView(e.data);let n=0;for(;n+5<e.data.byteLength;){if(0===t.getUint8(n+0)&&0===t.getUint8(n+1)&&0===t.getUint8(n+2)&&1===t.getUint8(n+3)&&78===t.getUint8(n+4)&&1===t.getUint8(n+5)&&101===t.getUint8(n+6)){let i=n+7,r=0,o=0;for(;255===(o=t.getUint8(i++));)r+=255;r+=o;const s=yx(e.data,i,r);return new Uint8Array(s)}n++}return null}(e);default:return null}}(r,bx(new Uint8Array(r.data)));a&&n.onSei&&n.onSei(a,r.timestamp),o.enqueue(r)}});r.readable.pipeThrough(o).pipeTo(r.writable)}else if(zO()){if("undefined"==typeof RTCRtpScriptTransform)return void SL.warning("browser not support RTCRtpScriptTransform");const r=KV(),o=new MessageChannel;await new cp((e=>r.onmessage=t=>{"registered"===t.data&&e(void 0)}));const s=new RTCRtpScriptTransform(r,{name:"sei-rx",port:o.port2},[o.port2]);e.transform=s,await new cp((e=>r.onmessage=t=>{"started"===t.data&&e(void 0)})),o.port1.onmessage=r=>{var o;if(r.data.transformed&&e.track&&(null===(o=e.track)||void 0===o?void 0:o.id)!==n.track.id)SL.debug("video track changed: ".concat(n.track.id," => ").concat(e.track.id)),n.track.removeEventListener("ended",i),n.track=e.track,n.track.addEventListener("ended",i);else if(r.data.sei&&n.onSei)n.onSei(r.data.sei,r.data.rtpTimestamp);else if(r.data.firstFrameInfo&&t.onFirstFrame){var s;null===(s=t.onFirstFrame)||void 0===s||s.call(t,r.data.firstFrameInfo)}},n.worker=r}function i(){if(e.track){if(this.id!==e.track.id)return;e.track.removeEventListener("ended",i)}!function(e){const t=Ax.get(e);if(t){Ax.delete(e);try{var n,i;null===(n=t.controller)||void 0===n||n.terminate(),null===(i=t.worker)||void 0===i||i.terminate()}catch(e){SL.warning(e&&e.message)}}}(e)}Ax.set(e,n),e.track.addEventListener("ended",i)}},Rae={name:"InterceptFrame",create:()=>Tae};var vae;function yae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function Cae(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?yae(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):yae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let bae=(vae=class e extends MF{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get dtlsTransportState(){var e,t;return null!==(e=null===(t=this.peerConnection.getReceivers()[0])||void 0===t||null===(t=t.transport)||void 0===t?void 0:t.state)&&void 0!==e?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map((e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"")).filter((e=>{var t;return Ui(t=Object.keys(GP)).call(t,e)})))]}constructor(e,t,n){super(e,t),zA(this,"id",kD(5,"connection-")),zA(this,"store",void 0),zA(this,"peerConnection",void 0),zA(this,"forceTurn",!1),zA(this,"remoteSDP",void 0),zA(this,"initialOffer",void 0),zA(this,"transportEventReceiver",void 0),zA(this,"statsFilter",void 0),zA(this,"extension",{useXR:xP("USE_XR")}),zA(this,"localCapabilities",void 0),zA(this,"remoteCodecs",void 0),zA(this,"localCandidateCount",0),zA(this,"allCandidatesReceived",!1),zA(this,"isPreallocation",!1),zA(this,"preMediaMap",new Map),zA(this,"dataStreamChannelMap",new Map),zA(this,"establishPromise",void 0),zA(this,"recoveredDataChannelIds",[]),zA(this,"currentDataChannelId",1),zA(this,"supportAV1RtpSpec",!1),zA(this,"mutex",void 0),zA(this,"qualityLimitationReason",fP.NONE),zA(this,"unsupportedResolutionFloorTrackIds",new Set),zA(this,"isFirstConnected",!1),this.store=t,this.forceTurn=wne(e),this.mutex=new JD("NVConnectionExtension-mutex",t.clientId),this.peerConnection=n,this.isFirstConnected=!1,this.statsFilter=bP(this.peerConnection,xP("STATS_UPDATE_INTERVAL"),void 0,$O()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,e.isPreallocation&&(this.isPreallocation=!0),this.establishPromise=this.establish()}getPreMedia(e){return this.preMediaMap.get(e)}isPreSub(){return this.preMediaMap.size>0}async updateRemoteRTPCapabilities(e,t){if(this.remoteCodecs=t,!this.remoteSDP)return void SL.debug("[NVConnectionExtension] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(t));if(this.remoteSDP.updateRemoteCodec(e,t,this.store.codec)){const e=await this.peerConnection.createOffer(),t=this.logSDPExchange(e.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(e);const n=this.remoteSDP.toString();null==t||t(n),await this.peerConnection.setRemoteDescription({type:"answer",sdp:n})}else SL.debug("[NVConnectionExtension] updateRemoteRTPCapabilities no need to exchange SDP.")}async establish(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const t=await this.peerConnection.createOffer();if(!t.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const n=B7(t.sdp),i=await $7({filterRTX:!xP("USE_PUB_RTX")&&!xP("USE_SUB_RTX"),filterVideoFec:xP("FILTER_VIDEO_FEC"),filterAudioFec:xP("FILTER_AUDIO_FEC"),filterVideoCodec:xP("FILTER_VIDEO_CODEC"),unsupportedVideoUplinkCodec:xP("UNSUPPORTED_VIDEO_UPLINK_CODEC"),unsupportedVideoDownlinkCodec:xP("UNSUPPORTED_VIDEO_DOWNLINK_CODEC")},this.extension);if(this.localCapabilities=nee(i),this.initialOffer=t,xP("ENABLE_SVC")&&"av1"==this.store.codec){const t=await Q7();var e;if(t)this.supportAV1RtpSpec=!0,null===(e=i.send)||void 0===e||e.videoExtensions.push(t)}let r;return t.sdp&&lee(t.sdp)&&(r=vD(i),D7(r)),Cae(Cae({},n),{},{rtpCapabilities:r||i,offerSDP:t.sdp})}catch(e){throw new ON(wN.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}}async connect(e){try{if(!this.initialOffer)throw new Error("Cannot establish NVConnectionExtension without initial offer.");if(this.initialOffer.sdp&&lee(this.initialOffer.sdp)&&P7(e.rtpCapabilities,this.localCapabilities),this.remoteSDP=new Zte(Cae(Cae({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec,!(!xP("ENABLE_PRE_SUB_WITH_PRE_PC")||!xP("PRE_USE_LOCAL_CODECS"))&&QL(this.store),!0),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec),qL()){var t;const e=(null===(t=this.store.preSubOptions)||void 0===t?void 0:t.length)||0,n=xP("PRE_SUB_NUM")||1,i=e>n?e:n,r=this.remoteSDP.preloadRemoteMedia(i),o=r.mids,s=r.preSSRCs,a=aee(this.initialOffer.sdp,this.extension),c=this.logSDPExchange(a||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:a}),null==c||c(a),new Array(i).fill(0).forEach((()=>{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"})}));const d=await this.peerConnection.createOffer(),l=this.logSDPExchange(d.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(d);const u=this.remoteSDP.toString();null==l||l(u),await this.peerConnection.setRemoteDescription({type:"answer",sdp:u}),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media with icc/dtls, add preload ssrcs ").concat(s)),this.presetMedia(o,s);const h=this.peerConnection.getTransceivers()[0];null!=h&&h.receiver&&this.tryBindTransportEvents(h.receiver)}else{const t=this.remoteSDP.toString(),i=aee(this.initialOffer.sdp,this.extension),r=this.logSDPExchange(i||"","offer","local","connect");this.store.descriptionStart(),await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==r||r(t),await this.peerConnection.setRemoteDescription({type:"answer",sdp:t});const o=this.peerConnection.getTransceivers()[0];if(null!=o&&o.receiver&&this.tryBindTransportEvents(o.receiver),QL(this.store))if(e.preallocation&&xP("ENABLE_PRE_SUB_WITH_PRE_PC")){var n;const e=(null===(n=this.store.preSubOptions)||void 0===n?void 0:n.length)||0,t=xP("PRE_SUB_NUM")||1,i=e>t?e:t,r=this.remoteSDP.preloadRemoteMedia(i),o=r.mids,s=r.preSSRCs;await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[".concat(this.store.clientId,"] [P2PConnection] preload media, in pre pc,add preload ssrcs ").concat(s)),this.presetMedia(o,s)}else{const t=e.preSSRCs,n=void 0===t?[]:t,i=n.map((e=>e.ssrcMsg[0].ssrcId));if(0===n.length)return;const r=this.remoteSDP.batchSend(n.map((e=>Object.assign({},e)))).mids;await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[P2PConnection.connect] preload media, after join, add preload ssrcs ".concat(i)),this.presetMedia(r,i)}}}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.connect failed; ".concat(e.toString()))}}presetMedia(e,t){e.forEach(((e,n)=>{this.peerConnection.getTransceivers().forEach((i=>{if(null!=i.mid&&e===i.mid&&i.receiver.track){const r=i.receiver.track;let o;"video"===r.kind&&xP("ENABLE_PRE_RENDER")&&(o=new MU({trackId:"track-".concat(r.kind,"-unknown-").concat(this.store.clientId,"_").concat(kD(5,""))},!0),o.updateVideoTrack(r),o.onFirstVideoFrameRender=()=>{var e;const i=this.preMediaMap.get(t[n]);i&&(i.firstVideoRender=Date.now()),null===(e=this.onFirstVideoRender)||void 0===e||e.call(this,t[n])},o.onVideoBufferReady=()=>{var e;null===(e=this.onFirstVideoBufferReady)||void 0===e||e.call(this,t[n])},o.play(this.store.sessionId||void 0)),this.preMediaMap.set(t[n],{mid:e,track:r,player:o,transceiver:i})}})),this.store.peerReceiver()}))}checkDtlsParameters(e){return!!this.remoteSDP&&(e.length>0&&this.remoteSDP.updateRemoteDtlsParameters(e))}checkIceParameters(e){if(!this.remoteSDP)return!1;return this.remoteSDP.restartICE(e)}async updateRemoteConnect(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateRemoteConnect before remote SDP created");let t=!1;const n=e.rtpCapabilities;if(t=KC(this.remoteSDP.updateRemoteRTPCapabilities(n),2)[1],Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0){const e=this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);t=t||e}const i=e.preSSRCs,r=void 0===i?[]:i,o=r.map((e=>e.ssrcMsg[0].ssrcId));if(!this.remoteSDP.checkPreloadSsrcs(o)){const e=[],t=[];if(Array.from(this.preMediaMap.entries()).every((n=>{let i=KC(n,2),r=i[0],o=i[1],s=o.mid,a=o.player;o.track;return e.push(s),t.push(r),this.preMediaMap.delete(r),a&&a.destroy(),!0})),e.length>0&&(this.remoteSDP.stopSending(e),await see(this.peerConnection,this.remoteSDP,this.extension),SL.warn("[NVConnectionExtension.updateRemoteConnect] preload media, failed, del preload ssrcs ".concat(t)),HL.reportApiInvoke(this.store.sessionId,{name:zN.PRELOAD_MEDIA_FAILED,options:[r,t],tag:ZN.TRACER}).onSuccess()),r.length>0){const e=this.remoteSDP.batchSend(r.map((e=>Object.assign({},e)))).mids;await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[NVConnectionExtension.updateRemoteConnect] preload media, after join, add preload ssrcs ".concat(o)),this.presetMedia(e,o)}}t?(await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[NVConnectionExtension] updateRemoteConnect by exchanging SDP.")):SL.debug("[NVConnectionExtension] updateRemoteConnect no need to exchange SDP, because no need to update remote codecs (use local codecs)")}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.updateRemoteConnect failed; ".concat(e.toString()))}}send(e,t,n){var i=this;return Ww((function*(){const r=yield Kw(i.mutex.lock("From NVConnectionExtension.send"));try{if(!i.remoteSDP)throw new Error("Cannot call NVConnectionExtension.send before remote SDP created");const o=[],s=O7();e.forEach((e=>{const t=i.peerConnection.addTransceiver(e._mediaStreamTrack,Cae({direction:"sendonly"},"video"===e.trackMediaType&&i.supportAV1RtpSpec&&s?{sendEncodings:[{scalabilityMode:s}]}:{}));o.push(t),e._updateRtpTransceiver(t)})),$O()&&!0===xP("SIMULCAST")&&(yield Kw(i.applySimulcastForFirefox(o,e)));const a=yield Kw(i.peerConnection.createOffer()),c=i.remoteSDP.predictReceivingMids(e.length),d=i.mungSendOfferSDP(a.sdp,e,c),l=zP(d),u=c.map((e=>{const t=l.mediaDescriptions.find((t=>t.attributes.mid===e));if(!t)throw new Error("Cannot extract ssrc from mediaDescription.");return j7(t,xP("USE_PUB_RTX"))}));let h;try{h=yield u}catch(r){h=[],i.remoteSDP.receive(e,t,n,h);const o=i.remoteSDP.toString();throw yield Kw(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Kw(i.peerConnection.setRemoteDescription({type:"answer",sdp:o})),yield Kw(i.stopSending(c,!0)),r}i.remoteSDP.receive(e,t,n,h);const p=i.remoteSDP.toString(),_=i.logSDPExchange(d,"offer","local","send");return yield Kw(i.peerConnection.setLocalDescription({type:"offer",sdp:d})),yield Kw(i.applySimulcastEncodings(o,e)),yield Kw(i.applySendEncodings(o,e)),null==_||_(p),yield Kw(i.peerConnection.setRemoteDescription({type:"answer",sdp:p})),o.map(((e,t)=>{const n=c[t];return{localSSRC:u[t],id:n,transceiver:e}}))}catch(e){throw e instanceof ON?e:new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.send failed; ".concat(e.toString()))}finally{r()}}))()}async createDataChannels(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.createDataChannels before remote SDP created");let n=this.dataStreamChannelMap.get(e);if(n&&"open"===n.readyState)SL.debug("[NVConnectionExtension] Channels are already available and can be reused directly.");else{const t=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if("number"!=typeof t)throw new Error("create DataChannel error, because cannot get dc id");n=this.peerConnection.createDataChannel("datastream-channel",{id:t,negotiated:!0,ordered:!1,maxRetransmits:xP("DATASTREAM_MAX_RETRANSMITS")}),n.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,n)}t.forEach((e=>{e._updateOriginDataChannel(n)}));const i=this.remoteSDP.sendDataChannel();if(i.needExchangeSDP){const e=this.remoteSDP.toString();await this.peerConnection.setRemoteDescription({type:"offer",sdp:e});const t=await this.peerConnection.createAnswer();await this.peerConnection.setLocalDescription(t),SL.debug("[NVConnectionExtension] createDataChannels by exchanging SDP.")}else SL.debug("[NVConnectionExtension] createDataChannels no need to exchange SDP.");return}catch(e){throw e instanceof ON?e:new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.createDataChannels failed; ".concat(e.toString()))}}async stopDataChannels(e){try{const t=this.dataStreamChannelMap.get(e);return t&&(t.id&&this.recoveredDataChannelIds.push(t.id),t.close()),void this.dataStreamChannelMap.delete(e)}catch(e){throw e instanceof ON?e:new ON(wN.DATACHANNEL_FAILED,"NVConnectionExtension.stopDataChannels failed; ".concat(e.toString()))}}async stopSending(e,t){const n=t?void 0:await this.mutex.lock("From NVConnectionExtension.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopSending before remote SDP created");const t=this.peerConnection.getTransceivers().filter((t=>-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call NVConnectionExtension.stopSending.");t.map((e=>{var t;_ne(this.id+e.mid,this),e.direction="inactive",null===(t=e.stop)||void 0===t||t.call(e)}));const i=await this.peerConnection.createOffer(),r=this.logSDPExchange(i.sdp||"","offer","local","stopSending");await this.peerConnection.setLocalDescription(i),this.remoteSDP.stopReceiving(e);const o=this.remoteSDP.toString();null==r||r(o),await this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.stopSending failed; ".concat(e.toString()))}finally{n&&n()}}async receive(e,t,n,i){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.receive ".concat(e," before remoteSDP created."));const r=this.remoteSDP.send(e,t,n,i),o=r.mid;r.needExchangeSDP&&(await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] receive ").concat(e," by exchanging SDP.")));const s=this.peerConnection.getTransceivers().find((e=>e.mid===o));if(!s)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:s.receiver.track,id:o,transceiver:s}}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async batchReceive(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.batchReceive before remoteSDP created.");const t=this.remoteSDP.batchSend(e),n=t.mids;return t.needExchangeSDP&&(await see(this.peerConnection,this.remoteSDP,this.extension),SL.debug("[".concat(this.store.clientId,"] [NVConnectionExtension] batchReceive by exchanging SDP."))),n.map((e=>{const t=this.peerConnection.getTransceivers().find((t=>t.mid===e));if(!t)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:t.receiver.track,id:e,transceiver:t}}))}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.receive failed; ".concat(e.toString()))}}async stopReceiving(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.stopReceiving before remote SDP created.");e.forEach((e=>{Array.from(this.preMediaMap.entries()).some((t=>{let n=KC(t,2),i=n[0],r=n[1],o=r.mid,s=r.player;if(o===e)return this.preMediaMap.delete(i),s&&s.destroy(),!0}))})),this.remoteSDP.stopSending(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","stopReceiving");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension stopReceiving failed; ".concat(e.toString()))}}async muteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","muteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteRemote failed; ".concat(e.toString()))}}async unmuteRemote(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const t=this.remoteSDP.toString(),n=this.logSDPExchange(t,"offer","remote","unmuteRemote");await this.peerConnection.setRemoteDescription({type:"offer",sdp:t});const i=await this.peerConnection.createAnswer();null==n||n(i.sdp||""),await this.peerConnection.setLocalDescription(i)}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteRemote failed; ".concat(e.toString()))}}async muteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.muteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((e=>{e.direction="inactive"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.muteLocal failed; ".concat(e.toString()))}}async unmuteLocal(e){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.unmuteLocal before remote SDP created.");const t=this.peerConnection.getTransceivers().filter((t=>t.mid&&-1!==e.indexOf(t.mid)));if(t.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");t.map((async(e,t)=>{e.direction="sendonly"}));const n=await this.peerConnection.createOffer(),i=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");await this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec(e,this.remoteCodecs,this.store.codec);const r=this.remoteSDP.toString();null==i||i(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,"NVConnectionExtension.unmuteLocal failed; ".concat(e.toString()))}}restartICE(e){var t=this;return Ww((function*(){const n=yield Kw(t.mutex.lock("From NVConnectionExtension.restartICE"));try{if(!t.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const i=JL().supportPCSetConfiguration,r=xP("FORCE_TURN_TCP")||t.forceTurn;if(e===VF.RELAY&&!i)return;if(i&&!r){const n=e===VF.RELAY?"relay":"all",i=t.peerConnection.getConfiguration();i.iceTransportPolicy!==n&&(SL.debug("[".concat(t.store.clientId,"] restartICE change iceTransportPolicy from [").concat(i.iceTransportPolicy,"] to [").concat(n,"]")),i.iceTransportPolicy=n,t.peerConnection.setConfiguration(i))}t.remoteSDP.updateCandidates(e);const o=yield Kw(t.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=B7(o.sdp),a=(yield s.iceParameters).remoteIceParameters;t.remoteSDP.restartICE(a);const c=t.remoteSDP.toString(),d=t.logSDPExchange(o.sdp||"","offer","local","restartICE");t.store.descriptionStart(),yield Kw(t.peerConnection.setLocalDescription(o)),null==d||d(c),yield Kw(t.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(e){SL.warning("[".concat(t.store.clientId,"] restart ICE failed, abort operation"),e)}finally{n()}}))()}async extendCandidate(){if(!this.remoteSDP||this.isFirstConnected)return;const e=await this.mutex.lock("From NVConnectionExtension.extendCandidate");try{this.remoteSDP.updateCandidates(VF.TCP_RELAY),await see(this.peerConnection,this.remoteSDP,this.extension)}catch(e){SL.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),e)}finally{e()}}close(){var e;this.peerConnection.getTransceivers().forEach((e=>{_ne(this.id+e.mid,this)})),this.preMediaMap.forEach((e=>{let t=e.player;t&&t.destroy()})),this.preMediaMap.clear(),this.peerConnection.close(),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,"closed"),this.tryUnbindTransportEvents(),this.unbindPCEvents(),this.unbindStatsEvents(),this.removeAllListeners(),this.transportEventReceiver=void 0,this.statsFilter.destroy(),this.dataStreamChannelMap.clear(),this.recoveredDataChannelIds=[],this.currentDataChannelId=1}getStats(){return Cae(Cae({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}async updateEncoderConfig(e,t){try{if(!this.remoteSDP)throw new Error("Cannot call NVConnectionExtension.updateEncoderConfig before remote SDP created.");const n=await this.peerConnection.createOffer(),i=this.mungSendOfferSDP(n.sdp,[t],[e]);this.remoteSDP.updateRecvMedia(e,t);const r=this.remoteSDP.toString(),o=this.logSDPExchange(i,"offer","local","updateEncoderConfig");await this.peerConnection.setLocalDescription({type:"offer",sdp:i}),null==o||o(r),await this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(e){throw new ON(wN.EXCHANGE_SDP_FAILED,e.toString())}}async updateSendParameters(e,t){const n=this.peerConnection.getTransceivers().filter((t=>t.mid===e));1===n.length&&(this.isVP8Simulcast(t)?$O()||await this.applySimulcastEncodings(n,[t]):await this.applySendEncodings(n,[t]))}setStatsRemoteVideoIsReady(e,t){this.statsFilter.setVideoIsReady2(e,t)}async replaceTrack(e,t){const n=this.peerConnection.getTransceivers().find((e=>e.mid===t));n&&await n.sender.replaceTrack(e._mediaStreamTrack)}async getSelectedCandidatePair(){const e=this.peerConnection.getReceivers();if(e.length>0&&e[0].transport&&e[0].transport.iceTransport&&e[0].transport.iceTransport.getSelectedCandidatePair&&e[0].transport.iceTransport.getSelectedCandidatePair()){const t=e[0].transport.iceTransport.getSelectedCandidatePair(),n=t.local,i=t.remote;return{local:Cae(Cae({},dP),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:Cae(Cae({},dP),{},{candidateType:i.type,protocol:i.protocol,address:i.address,port:i.port})}}return this.statsFilter.getSelectedCandidatePair()}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;null===(e=this.onICEConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;"connected"===this.peerConnection.connectionState&&(this.isFirstConnected=!0),null===(e=this.onConnectionStateChange)||void 0===e||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var t;const n="code: ".concat(e.errorCode,", message: ").concat(e.errorText),i=e.port?"local: ".concat(e.port):"",r=A7(e.url||"");SL.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: NVConnectionExtension.onICECandidateError(").concat(n,"), url: ").concat(r||"",", host_candidate:").concat(i)),null===(t=this.onICECandidateError)||void 0===t||t.call(this,n)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] RTCPeerConnection.onicegatheringstatechange(").concat(e.target.iceGatheringState,")"))},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout((()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,SL.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))}),xP("CANDIDATE_TIMEOUT"))}unbindPCEvents(){this.peerConnection.oniceconnectionstatechange=null,this.peerConnection.onconnectionstatechange=null,this.peerConnection.onsignalingstatechange=null,this.peerConnection.onicecandidateerror=null,this.peerConnection.onicecandidate=null,this.peerConnection.ontrack=null}static resolvePCConfiguration(t){const n={iceServers:[]},i=t.cloudProxyServer||"disabled";return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&(eD(t.turnServer.servers)?n.iceServers=t.turnServer.servers:xP("NEW_TURN_MODE")&&n.iceServers&&"disabled"===i?(xP("USE_TURN_SERVER_OF_GATEWAY")?t.turnServer.serversFromGateway&&n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.serversFromGateway)):n.iceServers.push(...e.newTurnServerConfigToIceServers(t.turnServer.servers)),xP("NEW_FORCE_TURN")&&(n.iceTransportPolicy="relay")):"off"!==t.turnServer.mode&&(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),xP("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),xP("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),xP("ENABLE_ENCODED_TRANSFORM")&&JL().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(f7(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!xP("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}static newTurnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{const n=xP("NEW_TURN_MODE");1===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}):2===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}):3===n?t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(f7(e.turnServerURL),":443?transport=tcp")}):4===n&&(t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=udp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":3478?transport=tcp")}),t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(f7(e.turnServerURL),":443?transport=tcp")}))})),t}tryBindTransportEvents(e){const t=e.transport;if(t){this.transportEventReceiver=e,t.onstatechange=()=>{var e;null!=t&&t.state&&(null===(e=this.onDTLSTransportStateChange)||void 0===e||e.call(this,t.state))},t.onerror=e=>{var t;null===(t=this.onDTLSTransportError)||void 0===t||t.call(this,"error"in e?e.error:e)};const n=t.iceTransport;n&&(n.onstatechange=()=>{const e=null==t?void 0:t.iceTransport.state;var n;e&&(null===(n=this.onICETransportStateChange)||void 0===n||n.call(this,e))},n.getSelectedCandidatePair&&(n.onselectedcandidatepairchange=()=>{if(n.getSelectedCandidatePair()){const e=n.getSelectedCandidatePair()||{},t=e.local,i=e.remote;if(t&&i){const e=t.address+":"+t.port,n=i.address+":"+i.port;SL.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify(A7(e)),", remote ").concat(JSON.stringify(A7(n))))}}}))}}tryUnbindTransportEvents(){this.transportEventReceiver&&this.transportEventReceiver.transport&&(this.transportEventReceiver.transport.onstatechange=null,this.transportEventReceiver.transport.onerror=null,this.transportEventReceiver.transport.iceTransport&&(this.transportEventReceiver.transport.iceTransport.onstatechange=null))}async updateRtpSenderEncodings(e,t){var n,i;if(!t){const n=this.peerConnection.getSenders();t=n.find((t=>t.track===e._mediaStreamTrack))}if(!t)return SL.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return SL.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!JL().supportSetRtpSenderParameters)return SL.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r=UM(e),o=!!r&&Qte(this.store.codec)&&qte(r),s=o&&!this.unsupportedResolutionFloorTrackIds.has(e.getTrackId()),a=!!r&&!(o&&!s)&&une(e,s?r:void 0),c=s&&a,d=s||Ui(n=["vp8","vp9"]).call(n,this.store.codec),l={},u={},h=gne(e,c);h&&(l.degradationPreference=h);const p=w7(this.peerConnection,e._mediaStreamTrack);if(a&&p&&t&&r&&this.getLocalVideoStats&&d){const n=this.id+p.mid,i=fne(e,s);pne(n,r,this,i,(i=>{t&&this.updateAdaptation(e,t,i,n,s)}),this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var _;const t=e._encoderConfig,n=t.bitrateMax,i=t.frameRate,r=t.scaleResolutionDownBy;n&&(u.maxBitrate=1e3*n),(Ui(_=e._hints).call(_,Rk.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(i&&(u.maxFramerate=T7(i)),r&&r>=1&&(u.scaleResolutionDownBy=r))}const E=xP("ENCODER_CONFIG_LIMIT").maxFramerate;if(E&&"number"==typeof E&&(u.maxFramerate=u.maxFramerate?Math.min(u.maxFramerate,E):E),xP("DSCP_TYPE")&&SN()){var m;const e=xP("DSCP_TYPE");Ui(m=["very-low","low","medium","high"]).call(m,e)&&(u.networkPriority=e)}const f=t.getParameters(),g=null===(i=f.encodings)||void 0===i?void 0:i[0];$O()&&!g&&(l.encodings=[u]),g&&Object.assign(g,u),Object.assign(f,l),SL.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(f.encodings))),await t.setParameters(f),await dee(this.store.codec,t,xP("SVC_MODE"))}async updateAdaptation(e,t,n,i,r){var o,s;if(!t)return SL.debug("[updateAdaptation] no rtpSender found");if(!JL().supportSetRtpSenderParameters)return SL.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const a={},c={},d=n.bitrateMax,l=n.frameRate,u=n.scaleResolutionDownBy;d&&(c.maxBitrate=1e3*d),l&&(c.maxFramerate=T7(l));let h=!1;"number"==typeof u&&u>=1&&(r||Ui(o=["vp8","vp9"]).call(o,this.store.codec))&&(c.scaleResolutionDownBy=u,h=u>1);const p=t.getParameters(),_=null===(s=p.encodings)||void 0===s?void 0:s[0];_&&Object.assign(_,c),Object.assign(p,a);try{await t.setParameters(p),SL.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(p.encodings)))}catch(n){if(!("transport"in t)||t.transport&&"connected"===t.transport.state)if("connected"!==this.peerConnectionState)SL.debug("[updateAdaptation] peerConnection not connected}");else if(r&&h){const r=await Rne(t,a,c);"unsupported"===r.classification?(this.unsupportedResolutionFloorTrackIds.add(e.getTrackId()),_ne(i,this),SL.warn("[".concat(e.getTrackId(),"] fallback to browser adaptation because scaleResolutionDownBy adaptation is unsupported"),n,r.retryWithScaleError),this.updateRtpSenderEncodings(e,t).catch((t=>{SL.warn("[".concat(e.getTrackId(),"] failed to re-apply browser adaptation after disabling resolution floor"),t)}))):"transient"===r.classification?SL.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled after transient setParameters failure"),n):SL.debug("[".concat(e.getTrackId(),"] keep resolution floor enabled because setParameters failure is not classified as unsupported"),n,r.retryWithScaleError,r.retryWithoutScaleError)}else SL.debug("[updateAdaptation] updateRtpSenderEncodings failed",n);else SL.debug("[updateAdaptation] rtpSender transport not connected}")}}async applySendEncodings(e,t){try{if(!JL().supportSetRtpSenderParameters)return;if(e.length!==t.length)return;for(let n=0;n<e.length;n++){const i=e[n],r=t[n];r instanceof TV&&!this.isVP8Simulcast(r)&&await this.updateRtpSenderEncodings(r,i.sender)}}catch(e){SL.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}}mungSendOfferSDP(e,t,n){const i=zP(e);return t.forEach(((e,t)=>{const r=n[t],o=i.mediaDescriptions.find((e=>e.attributes.mid===r));o&&(Y7(o,e),q7(o,e,this.store.codec))})),ZP(i)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var t;null===(t=this.onFirstAudioReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var t;null===(t=this.onFirstVideoReceived)||void 0===t||t.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var t;null===(t=this.onFirstAudioDecoded)||void 0===t||t.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,t,n)=>{var i;null===(i=this.onFirstVideoDecoded)||void 0===i||i.call(this,e,t,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedLocalCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,t)=>{var n;null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n||n.call(this,e,t)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var t;null===(t=this.onFirstVideoDecodedTimeout)||void 0===t||t.call(this,e)}}unbindStatsEvents(){this.statsFilter.onFirstAudioReceived=void 0,this.statsFilter.onFirstVideoReceived=void 0,this.statsFilter.onFirstAudioDecoded=void 0,this.statsFilter.onFirstVideoDecoded=void 0,this.statsFilter.onSelectedLocalCandidateChanged=void 0,this.statsFilter.onSelectedRemoteCandidateChanged=void 0,this.statsFilter.onFirstVideoDecodedTimeout=void 0}async applySimulcastForFirefox(e,t){if(e.length===t.length)for(let a=0;a<e.length;a++){var n,i,r,o,s;const c=e[a],d=t[a];if(d instanceof TV&&!Ui(n=d._hints).call(n,Rk.LOW_STREAM)&&null!==(i=d._encoderConfig)&&void 0!==i&&i.bitrateMax&&(null===(r=d._encoderConfig)||void 0===r?void 0:r.bitrateMax)>200&&null!==(o=d._scalabilityMode)&&void 0!==o&&o.numSpatialLayers&&(null===(s=d._scalabilityMode)||void 0===s?void 0:s.numSpatialLayers)>1&&"vp8"===this.store.codec){const e={},t={high:1e3*(d._encoderConfig.bitrateMax-50),medium:5e4};e.encodings=[{rid:"m",active:!0,maxBitrate:t.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:t.high}];const n=c.sender.getParameters();await c.sender.setParameters(Object.assign(n,e))}}}async applySimulcastEncodings(e,t){if(!$O()&&e.length===t.length)for(let n=0;n<e.length;n++){const i=t[n];if(i instanceof TV&&this.isVP8Simulcast(i)){const t=e[n],r={},o={high:1e3*(i._encoderConfig.bitrateMax-50),medium:5e4};r.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:o.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:o.medium,scaleResolutionDownBy:4}];const s=t.sender.getParameters();await t.sender.setParameters(Object.assign(s,r))}}}isVP8Simulcast(e){var t,n,i,r,o;return!!(e instanceof TV&&xP("SIMULCAST")&&"vp8"===this.store.codec&&!Ui(t=e._hints).call(t,Rk.LOW_STREAM)&&null!==(n=e._encoderConfig)&&void 0!==n&&n.bitrateMax&&(null===(i=e._encoderConfig)||void 0===i?void 0:i.bitrateMax)>200&&null!==(r=e._scalabilityMode)&&void 0!==r&&r.numSpatialLayers&&(null===(o=e._scalabilityMode)||void 0===o?void 0:o.numSpatialLayers)>1)}logSDPExchange(e,t,n,i){if(xP("SDP_LOGGING"))return SL.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(t," SDP during NVConnectionExtension.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}async getRemoteSSRC(e){if(!this.remoteSDP)return;const t=this.remoteSDP.getSSRC(e);return t&&0!==t.length?t[0].ssrcId:void 0}setConfiguration(t){if(JL().supportPCSetConfiguration){const n=e.resolvePCConfiguration(t);this.peerConnection.setConfiguration(n)}t.isPreallocation&&(this.isPreallocation=!0)}},Zx(vae.prototype,"updateRemoteRTPCapabilities",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"updateRemoteRTPCapabilities"),vae.prototype),Zx(vae.prototype,"connect",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"connect"),vae.prototype),Zx(vae.prototype,"updateRemoteConnect",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"updateRemoteConnect"),vae.prototype),Zx(vae.prototype,"createDataChannels",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"createDataChannels"),vae.prototype),Zx(vae.prototype,"receive",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"receive"),vae.prototype),Zx(vae.prototype,"batchReceive",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"batchReceive"),vae.prototype),Zx(vae.prototype,"stopReceiving",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"stopReceiving"),vae.prototype),Zx(vae.prototype,"muteRemote",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"muteRemote"),vae.prototype),Zx(vae.prototype,"unmuteRemote",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"unmuteRemote"),vae.prototype),Zx(vae.prototype,"muteLocal",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"muteLocal"),vae.prototype),Zx(vae.prototype,"unmuteLocal",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"unmuteLocal"),vae.prototype),Zx(vae.prototype,"close",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"close"),vae.prototype),Zx(vae.prototype,"updateEncoderConfig",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"updateEncoderConfig"),vae.prototype),Zx(vae.prototype,"updateSendParameters",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"updateSendParameters"),vae.prototype),Zx(vae.prototype,"replaceTrack",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"replaceTrack"),vae.prototype),Zx(vae.prototype,"updateAdaptation",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"updateAdaptation"),vae.prototype),Zx(vae.prototype,"getRemoteSSRC",[Iae],Object.getOwnPropertyDescriptor(vae.prototype,"getRemoteSSRC"),vae.prototype),vae);function Iae(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From NVConnectionExtension.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}var Aae;function wae(e){var t,n,i,r=2;for("undefined"!=typeof Symbol&&(n=Yw,i=Symbol.iterator);r--;){if(n&&null!=(t=e[n]))return t.call(e);if(i&&null!=(t=e[i]))return new Oae(t.call(e));n="@@asyncIterator",i="@@iterator"}throw new TypeError("Object is not async iterable")}function Oae(e){function t(e){if(Object(e)!==e)return cp.reject(new TypeError(e+" is not an object."));var t=e.done;return cp.resolve(e.value).then((function(e){return{value:e,done:t}}))}return Oae=function(e){this.s=e,this.n=e.next},Oae.prototype={s:null,n:null,next:function(){return t(this.n.apply(this.s,arguments))},return:function(e){var n=this.s.return;return void 0===n?cp.resolve({value:e,done:!0}):t(n.apply(this.s,arguments))},throw:function(e){var n=this.s.return;return void 0===n?cp.reject(e):t(n.apply(this.s,arguments))}},new Oae(e)}let Nae=(Aae=class e extends MF{get currentLocalDescription(){return this.peerConnection.currentLocalDescription}get currentRemoteDescription(){return this.peerConnection.currentRemoteDescription}get peerConnectionState(){return this.peerConnection.connectionState}get iceConnectionState(){return this.peerConnection.iceConnectionState}get localCodecs(){return this._p2pConnection.localCodecs}constructor(t,n){super(t,n),zA(this,"name","DataChannelConnection"),zA(this,"store",void 0),zA(this,"peerConnection",void 0),zA(this,"cname",void 0),zA(this,"mutex",new JD("DataChannelConnection-mutex")),zA(this,"dataChannel",void 0),zA(this,"_p2pConnection",void 0),zA(this,"establishPromise",void 0),this.store=n,this.store.dcId=this.store.dcId+1,this.peerConnection=new RTCPeerConnection(e.resolvePCConfiguration(t),{optional:[{googDscp:!0}]}),this.dataChannel=this.peerConnection.createDataChannel("agora-signal",{ordered:!1,maxPacketLifeTime:50}),this.dataChannel.binaryType="arraybuffer",this._p2pConnection=new bae(t,n,this.peerConnection),this.bindPCEvents(),this.establishPromise=this._p2pConnection.establishPromise}getPreMedia(e){var t;return null===(t=this._p2pConnection)||void 0===t?void 0:t.getPreMedia(e)}isPreSub(){var e,t;return null!==(e=null===(t=this._p2pConnection)||void 0===t?void 0:t.isPreSub())&&void 0!==e&&e}async establish(){return await this._p2pConnection.establish()}getP2PConnectionParams(){return this._p2pConnection.establishPromise}updateRtpSenderEncodings(e){return this._p2pConnection.updateRtpSenderEncodings(e)}async connect(e){return this.cname=e.cname,await this._p2pConnection.connect(e),await new cp(((t,n)=>{const i=setTimeout((()=>{this.closeSignal(),n(new YL(wN.DATACHANNEL_CONNECTION_TIMEOUT,"Datachannel connection timed out, candidates: ".concat(JSON.stringify(e.candidates))))}),xP("DC_CONNECTION_TIMEOUT"));this.dataChannel.onopen=()=>{if("open"===this.dataChannel.readyState)return clearTimeout(i),void t()},this.dataChannel.onerror=e=>{this.closeSignal(),n(e)},this.dataChannel.addEventListener("close",(()=>{n(new YL(wN.DATACHANNEL_CONNECTION_TIMEOUT))}))})),{transmitter:this.dataChannel,close:this.closeSignal.bind(this)}}checkDtlsParameters(e){return this._p2pConnection.checkDtlsParameters(e)}checkIceParameters(e){return this._p2pConnection.checkIceParameters(e)}async updateRemoteRTPCapabilities(e,t){return this._p2pConnection.updateRemoteRTPCapabilities(e,t)}send(e,t,n){var i=this;return Ww((function*(){const r=yield Kw(i.mutex.lock("From DataChannelConnection.send"));try{return yield*Hw(wae(i._p2pConnection.send(e,t,n)))}finally{r()}}))()}async stopSending(e,t){return this._p2pConnection.stopSending(e,t)}async createDataChannels(e,t){return this._p2pConnection.createDataChannels(e,t)}async stopDataChannels(e){return this._p2pConnection.stopDataChannels(e)}async receive(e,t,n,i){return SL.debug("[DataChannelConnection] receive ".concat(e," by WebRTC.")),await this._p2pConnection.receive(e,t,n,i)}async batchReceive(e){return[...await this._p2pConnection.batchReceive(e)]}async stopReceiving(e){return await this._p2pConnection.stopReceiving(e)}async muteRemote(e){return await this._p2pConnection.muteRemote(e)}async unmuteRemote(e){return await this._p2pConnection.unmuteRemote(e)}async muteLocal(e){return await this._p2pConnection.muteLocal(e)}async unmuteLocal(e){return await this._p2pConnection.unmuteLocal(e)}restartICE(e){var t=this;return Ww((function*(){return yield*Hw(wae(t._p2pConnection.restartICE(e)))}))()}close(){this._p2pConnection.close(),this.unbindConnectionEvents(this._p2pConnection)}getStats(){return this._p2pConnection.getStats()}getRemoteVideoIsReady(e){return this._p2pConnection.getRemoteVideoIsReady(e)}updateRemoteConnect(e){return this._p2pConnection.updateRemoteConnect(e)}async updateEncoderConfig(e,t){return await this._p2pConnection.updateEncoderConfig(e,t)}async updateSendParameters(e,t){return await this._p2pConnection.updateSendParameters(e,t)}setStatsRemoteVideoIsReady(e,t){this._p2pConnection.setStatsRemoteVideoIsReady(e,t)}async replaceTrack(e,t){return await this._p2pConnection.replaceTrack(e,t)}async getRemoteSSRC(e){return this._p2pConnection.getRemoteSSRC(e)}logSDPExchange(e,t,n,i){if(xP("SDP_LOGGING"))return SL.upload("exchanging ".concat(n," ").concat(t," SDP during DataChannelConnection.").concat(i,"\n"),e),"offer"===t?e=>{this.logSDPExchange(e,"answer","local"===n?"remote":"local",i)}:void 0}static resolvePCConfiguration(t){const n={iceServers:[]};return t.iceServers?n.iceServers=t.iceServers:t.turnServer&&"off"!==t.turnServer.mode&&(eD(t.turnServer.servers)?n.iceServers=t.turnServer.servers:(n.iceServers&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.servers)),xP("USE_TURN_SERVER_OF_GATEWAY")&&n.iceServers&&t.turnServer.serversFromGateway&&n.iceServers.push(...e.turnServerConfigToIceServers(t.turnServer.serversFromGateway)),xP("FORCE_TURN_TCP")?n.iceTransportPolicy="relay":t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).forEach((e=>{e.forceturn&&(n.iceTransportPolicy="relay")})))),xP("ENABLE_ENCODED_TRANSFORM")&&JL().supportWebRTCEncodedTransform&&(n.encodedInsertableStreams=!0),n}static turnServerConfigToIceServers(e){const t=[];return e.forEach((e=>{e.security?e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turns:".concat(f7(e.turnServerURL),":").concat(e.tcpport,"?transport=tcp")}):(e.udpport&&!xP("FORCE_TURN_TCP")&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.udpport,"?transport=udp")}),e.tcpport&&t.push({username:e.username,credential:e.password,credentialType:"password",urls:"turn:".concat(e.turnServerURL,":").concat(e.tcpport,"?transport=tcp")}))})),t}bindPCEvents(){this._p2pConnection.onICEConnectionStateChange=e=>{var t;return null===(t=this.onICEConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onConnectionStateChange=e=>{var t;return null===(t=this.onConnectionStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportStateChange=e=>{var t;return null===(t=this.onDTLSTransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onDTLSTransportError=e=>{var t;return null===(t=this.onDTLSTransportError)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onICETransportStateChange=e=>{var t;return null===(t=this.onICETransportStateChange)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioReceived=e=>{var t;return null===(t=this.onFirstAudioReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoReceived=e=>{var t;return null===(t=this.onFirstVideoReceived)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstAudioDecoded=e=>{var t;return null===(t=this.onFirstAudioDecoded)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoRender=e=>{var t;return null===(t=this.onFirstVideoRender)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoBufferReady=e=>{var t;return null===(t=this.onFirstVideoBufferReady)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onFirstVideoDecoded=(e,t,n)=>{var i;return null===(i=this.onFirstVideoDecoded)||void 0===i?void 0:i.call(this,e,t,n)},this._p2pConnection.onFirstVideoDecodedTimeout=e=>{var t;return null===(t=this.onFirstVideoDecodedTimeout)||void 0===t?void 0:t.call(this,e)},this._p2pConnection.onSelectedLocalCandidateChanged=(e,t)=>{var n;return null===(n=this.onSelectedLocalCandidateChanged)||void 0===n?void 0:n.call(this,e,t)},this._p2pConnection.onSelectedRemoteCandidateChanged=(e,t)=>{var n;return null===(n=this.onSelectedRemoteCandidateChanged)||void 0===n?void 0:n.call(this,e,t)}}closeSignal(){this.dataChannel.close(),this.peerConnection.close()}unbindConnectionEvents(e){e.onConnectionStateChange=void 0,e.onICEConnectionStateChange=void 0,e.onICETransportStateChange=void 0,e.onDTLSTransportStateChange=void 0,e.onDTLSTransportError=void 0,e.onFirstAudioDecoded=void 0,e.onFirstAudioReceived=void 0,e.onFirstVideoDecoded=void 0,e.onFirstVideoReceived=void 0,e.onSelectedLocalCandidateChanged=void 0,e.onSelectedRemoteCandidateChanged=void 0,e.onFirstVideoDecodedTimeout=void 0}setConfiguration(e){this._p2pConnection.setConfiguration(e)}},Zx(Aae.prototype,"connect",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"connect"),Aae.prototype),Zx(Aae.prototype,"updateRemoteRTPCapabilities",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"updateRemoteRTPCapabilities"),Aae.prototype),Zx(Aae.prototype,"createDataChannels",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"createDataChannels"),Aae.prototype),Zx(Aae.prototype,"receive",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"receive"),Aae.prototype),Zx(Aae.prototype,"stopReceiving",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"stopReceiving"),Aae.prototype),Zx(Aae.prototype,"muteRemote",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"muteRemote"),Aae.prototype),Zx(Aae.prototype,"unmuteRemote",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"unmuteRemote"),Aae.prototype),Zx(Aae.prototype,"muteLocal",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"muteLocal"),Aae.prototype),Zx(Aae.prototype,"unmuteLocal",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"unmuteLocal"),Aae.prototype),Zx(Aae.prototype,"close",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"close"),Aae.prototype),Zx(Aae.prototype,"updateEncoderConfig",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"updateEncoderConfig"),Aae.prototype),Zx(Aae.prototype,"updateSendParameters",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"updateSendParameters"),Aae.prototype),Zx(Aae.prototype,"replaceTrack",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"replaceTrack"),Aae.prototype),Zx(Aae.prototype,"getRemoteSSRC",[Dae],Object.getOwnPropertyDescriptor(Aae.prototype,"getRemoteSSRC"),Aae.prototype),Aae);function Dae(e,t,n){const i=e[t];if("function"!=typeof i)throw new Error("Cannot use mutex on object property.");return n.value=async function(){const e=this.mutex,n=await e.lock("From DataChannelConnection.".concat(t));try{for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];return await i.apply(this,o)}finally{n()}},n}function Pae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}class Lae extends YN{get url(){return this._url?this._url:null}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var t;Ui(t=["tryNext","recover"]).call(t,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,"reconnecting"===this._state?this.emit(XF.RECONNECTING,this.reconnectReason):"connected"===this._state?this.emit(XF.CONNECTED):"closed"===this._state?this.emit(XF.CLOSED):"failed"===this._state&&this.emit(XF.FAILED))}constructor(e,t,n,i){super(),zA(this,"connectionID",0),zA(this,"currentURLIndex",0),zA(this,"reconnectReason",void 0),zA(this,"_reconnectMode","tryNext"),zA(this,"_initMutex",void 0),zA(this,"_name",void 0),zA(this,"_state","closed"),zA(this,"_reconnectInterrupter",void 0),zA(this,"_url",void 0),zA(this,"_retryConfig",void 0),zA(this,"_reconnectCount",0),zA(this,"_forceCloseTimeout",5e3),zA(this,"_onlineReconnectListener",void 0),zA(this,"_closeEstablishingTransmitter",(()=>{})),zA(this,"_store",void 0),zA(this,"_joinChannelServiceRecordIndex",void 0),zA(this,"_transmitter",void 0),zA(this,"_useCompress",void 0),zA(this,"_inflateLength",0),zA(this,"_deflateLength",0),this._store=i,this._name=e,this._retryConfig=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?Pae(Object(n),!0).forEach((function(t){zA(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Pae(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({},t),this._useCompress=n}resetReconnectCount(e){SL.debug("".concat(this._name," reset reconnect count, reason: ").concat(e)),this._reconnectCount=0}close(e,t){if(this.currentURLIndex=0,this.resetReconnectCount("close"),this._reconnectInterrupter&&this._reconnectInterrupter(),this._transmitter){this._transmitter.onclose=null,this._transmitter.onopen=null,this._transmitter.onmessage=null;const e=this._transmitter;t?setTimeout((()=>e.close()),500):e.close(),this._transmitter=void 0}this.state=e?"failed":"closed",this._closeEstablishingTransmitter&&this._closeEstablishingTransmitter()}reconnect(e,t){if(!this._transmitter)return void SL.warning("[".concat(this._name,"] can not reconnect, no websocket"));var n;(void 0!==e&&(this.reconnectMode=e),SL.debug("[".concat(this._name,"] reconnect is triggered initiative")),"number"==typeof this._joinChannelServiceRecordIndex)&&(null===(n=this._store)||void 0===n||n.recordJoinChannelService({status:"error",errors:[new Error(t)]},this._joinChannelServiceRecordIndex));const i=this._transmitter.onclose;this._transmitter.onclose=null,this._transmitter.close(),i&&i.bind(this._transmitter)({code:9999,reason:t})}getInflateData(){const e=this._inflateLength,t=this._deflateLength;return this.clearInflateData(),{inflateLength:e,deflateLength:t}}setInflateData(e){this._deflateLength=this._deflateLength+e.originLength,this._inflateLength=this._inflateLength+e.compressedLength}clearInflateData(){this._inflateLength=0,this._deflateLength=0}}let kae=function(e){return e[e.Default=0]="Default",e[e.Ack=1]="Ack",e}({});class Mae{constructor(e,t,n){zA(this,"version",1),zA(this,"initialRTO",void 0),zA(this,"maxBatchAckCount",void 0),zA(this,"maxRTO",void 0),zA(this,"initialRTT",void 0),zA(this,"ID",void 0),zA(this,"rtt",void 0),zA(this,"packetNumber",1),zA(this,"rtoRatioMap",new Map),zA(this,"timeoutMap",new Map),zA(this,"unorderedPacketQueue",[]),zA(this,"batchAckPacketQueue",[]),zA(this,"lastOrderedPacketNumber",0),zA(this,"batchAckTimer",void 0),zA(this,"sendImpl",void 0),zA(this,"receiveImpl",void 0),this.sendImpl=e,this.receiveImpl=t,this.ID=kD(7,"transmitter-"),this.initialRTO=void 0!==(null==n?void 0:n.initialRTO)?n.initialRTO:xP("TRANSMITTER_INITIAL_RTO"),this.initialRTT=void 0!==(null==n?void 0:n.initialRTT)?n.initialRTT:xP("TRANSMITTER_INITIAL_RTT"),this.rtt=void 0!==(null==n?void 0:n.initialRTT)?n.initialRTT:xP("TRANSMITTER_INITIAL_RTT"),this.maxBatchAckCount=void 0!==(null==n?void 0:n.maxBatchAckCount)?n.maxBatchAckCount:xP("TRANSMITTER_MAX_BATCH_ACK_COUNT"),this.maxRTO=void 0!==(null==n?void 0:n.maxRTO)?n.maxRTO:xP("TRANSMITTER_MAX_RTO")}packetize(e,t){return{type:kae.Default,version:this.version,packetNumber:t,payload:e}}serialize(e){switch(e.type){case kae.Default:{let t;if("string"==typeof e.payload){t=(new TextEncoder).encode(e.payload)}else t=e.payload;const n=new ArrayBuffer(t.length+15),i=new DataView(n);i.setUint16(0,e.version),i.setUint8(2,e.type),i.setUint32(3,e.packetNumber),FN(i,7,BigInt(e.sendTs));return new Uint8Array(i.buffer).set(t,15),n}case kae.Ack:{const t=new ArrayBuffer(16),n=new DataView(t);return n.setUint16(0,e.version),n.setUint8(2,e.type),n.setUint32(3,e.maxAckPacketNumber),n.setUint8(7,e.shift),FN(n,8,BigInt(e.ackSendTs)),t}}}deserialize(e){const t=new DataView(e),n=t.getUint16(0),i=t.getUint8(2);switch(i){case kae.Default:{const r=t.getUint32(3),o=xN(t,7),s=e.slice(15),a=new Uint8Array(s);return{version:n,type:i,packetNumber:r,sendTs:Number(o),payload:a}}case kae.Ack:{const e=t.getUint32(3),r=t.getUint8(7),o=xN(t,8);return{version:n,type:i,maxAckPacketNumber:e,shift:r,ackSendTs:Number(o)}}default:throw SL.error("[".concat(this.ID,"] Unrecognized packet type ").concat(i)),new Error("Unrecognized packet type ".concat(i))}}sendMessage(e){xP("DC_DEBUG_LOG")&&"string"==typeof e&&SL.debug("[".concat(this.ID,"] sending message packet"),JSON.parse(e));const t=this.packetize(e,this.packetNumber);this.packetNumber=4294967295===this.packetNumber?1:this.packetNumber+1;const n=this.calculateRTO(t),i=window.setTimeout((()=>{this.resendMessage(t)}),n);this.timeoutMap.set(t.packetNumber,i),this.sendPacket(t)}onData(e){const t=this.deserialize(e);t.type===kae.Default?this.ack(t):t.type===kae.Ack&&(this.updateRTT(t,Math.round(performance.now())),this.clearRTO(t))}close(){this.rtt=this.initialRTT,this.packetNumber=1,Array.from(this.timeoutMap.entries()).forEach((e=>{let t=KC(e,2);t[0];let n=t[1];window.clearTimeout(n)})),this.timeoutMap=new Map,this.rtoRatioMap=new Map,this.unorderedPacketQueue=[],this.batchAckPacketQueue=[],this.lastOrderedPacketNumber=0,void 0!==this.batchAckTimer&&window.clearTimeout(this.batchAckTimer)}resendMessage(e){const t=this.calculateRTO(e),n=window.setTimeout((()=>{xP("DC_DEBUG_LOG")&&"string"==typeof e.payload&&SL.debug("[".concat(this.ID,"] resending message packet"),JSON.parse(e.payload),"timeout: ".concat(t)),this.resendMessage(e)}),t);this.timeoutMap.set(e.packetNumber,n),this.sendPacket(e)}calculateRTO(e){const t=this.rtoRatioMap.get(e.packetNumber);if(void 0===t)return this.rtoRatioMap.set(e.packetNumber,1),this.initialRTO;{const n=9*this.rtt/8*t;return this.rtoRatioMap.set(e.packetNumber,t+1),n>this.maxRTO?this.maxRTO:n}}updateRTT(e,t){const n=e.ackSendTs;this.rtt=this.rtt*(7/8)+(t-n-this.rtt)/8}ack(e){if(e.packetNumber===this.lastOrderedPacketNumber+1)for(this.batchAckPacketQueue.length>=this.maxBatchAckCount&&this.batchAck(),this.batchAckTimer?this.batchAckPacketQueue.push(e):(this.batchAckPacketQueue.push(e),this.batchAckTimer=window.setTimeout((()=>{this.batchAck()}),this.rtt/8)),this.lastOrderedPacketNumber+=1,this.receiveImpl(e.payload);;){const e=this.unorderedPacketQueue[0];if(!e){this.unorderedPacketQueue.shift();break}this.batchAckTimer&&this.batchAck(),this.receiveImpl(e.payload),this.unorderedPacketQueue.shift(),this.lastOrderedPacketNumber+=1}else if(e.packetNumber<=this.lastOrderedPacketNumber){const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:kae.Ack,version:this.version};xP("DC_DEBUG_LOG")&&SL.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}else if(e.packetNumber>this.lastOrderedPacketNumber){this.unorderedPacketQueue[e.packetNumber-this.lastOrderedPacketNumber-2]=e;const t={ackSendTs:e.sendTs,maxAckPacketNumber:e.packetNumber,shift:0,type:kae.Ack,version:this.version};xP("DC_DEBUG_LOG")&&SL.debug("[".concat(this.ID,"] sending ack packet"),t,"packetNumber: ".concat(e.packetNumber)),this.sendPacket(t)}}batchAck(){window.clearTimeout(this.batchAckTimer),this.batchAckTimer=void 0;const e={ackSendTs:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].sendTs,maxAckPacketNumber:this.batchAckPacketQueue[this.batchAckPacketQueue.length-1].packetNumber,shift:this.batchAckPacketQueue.length-1,type:kae.Ack,version:this.version};xP("DC_DEBUG_LOG")&&SL.debug("[".concat(this.ID,"] sending batch ack packet"),e,"shift: ".concat(this.batchAckPacketQueue.length-1)),this.sendPacket(e),this.batchAckPacketQueue=[]}sendPacket(e){e.type===kae.Default&&(e.sendTs=Math.round(performance.now()));const t=this.serialize(e);this.sendImpl(t)}clearRTO(e){for(let t=e.maxAckPacketNumber-e.shift;t<=e.maxAckPacketNumber;t++){const e=this.timeoutMap.get(t);void 0!==e&&window.clearTimeout(e),this.timeoutMap.delete(t),this.rtoRatioMap.delete(t)}}}class Uae extends Lae{constructor(e,t){super(e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2],arguments.length>3?arguments[3]:void 0),zA(this,"_initMutex",void 0),zA(this,"_reconnectInterrupter",void 0),zA(this,"_url",void 0),zA(this,"_transmitter",void 0),zA(this,"_addresses",void 0),zA(this,"_reliableTransmission",void 0),zA(this,"_textEncoder",void 0),zA(this,"_textDecoder",void 0),this._textEncoder=new TextEncoder,this._textDecoder=new TextDecoder,this._initMutex=new JD("datachannel");const n=t.timeout,i=t.timeoutFactor,r=Math.max(300,Math.floor(3*n/5)),o=Math.max(1.2,Math.floor(8*i)/10);aD.ONLINE&&(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o),pD.on(cD.NETWORK_STATE_CHANGE,((e,t)=>{e!==t&&(this.resetReconnectCount("network state change: ".concat(t," -> ").concat(e)),e===aD.ONLINE?(this._retryConfig.timeout=r,this._retryConfig.timeoutFactor=o):(this._retryConfig.timeout=n,this._retryConfig.timeoutFactor=i))}))}getConnection(){if(this._reliableTransmission)return this._reliableTransmission}async init(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;this._forceCloseTimeout=t;const n=(t,n)=>{this._addresses=e,this.currentURLIndex=this._addresses.findIndex((e=>e.fingerprint||xP("FINGERPRINT")));const i=this._addresses[this.currentURLIndex];this.state="connecting",this.createTransmitterConnection(i).then(t).catch(n),this.once(XF.CLOSED,(()=>n(new YL(wN.WS_DISCONNECT)))),this.once(XF.CONNECTED,(()=>t()))};return this._initMutex.lock().then((e=>new cp(((e,t)=>{n(e,t)})).then((()=>{e()})).catch((()=>{e()}))))}async sendMessage(e){let t=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(!this._transmitter||!this._reliableTransmission)throw new YL(wN.WS_ABORT,"datachannel is not ready");try{t||(e=JSON.stringify(e));const n=this._textEncoder.encode(e),i=WW(n,{raw:!0});this._reliableTransmission.sendMessage(i)}catch(e){throw new YL(wN.WS_ERR,"send datachannel signal message error"+e.toString())}}unbindDcCloseEventListener(){this._transmitter&&(this._transmitter.onclose=null)}sendMessageWithJSON(e){const t=JSON.stringify(e);return{compressed:t,compressedLength:t.length,origin:e}}sendMessageWithUint8Array(e){return{compressed:e,compressedLength:e.byteLength,origin:e}}createTransmitterConnection(e){return this.connectionID+=1,this._joinChannelServiceRecordIndex=void 0,this._url="dc://".concat(e.ip,":").concat(e.port),new cp(((t,n)=>{var i;const r=()=>{SL.debug("[".concat(this._name,"] datachannel opened:"),this._url),this.reconnectMode="recover",this.state="connected",this.resetReconnectCount("opened"),t()},o=async e=>{var i;if(null===(i=this._closeEstablishingTransmitter)||void 0===i||i.call(this),SL.debug("[".concat(this._name,"] datachannel close ").concat(this._url,", code: ").concat(e.code,", reason: ").concat(e.reason,", current mode: ").concat(this.reconnectMode)),this._reconnectCount<this._retryConfig.maxRetryCount){"connected"===this.state&&(this.reconnectReason=e.reason,this.state="reconnecting");const i=uD(this,XF.WILL_RECONNECT,this.reconnectMode)||this.reconnectMode,r=await this.reconnectWithAction(i);if("closed"===this.state)return void SL.debug("[".concat(this.connectionID,"] dc is closed, no need to reconnect"));if(!r)return n(new YL(wN.WS_DISCONNECT,"datachannel reconnect failed: ".concat(e.code))),void this.close(!0);t()}else n(new YL(wN.WS_DISCONNECT,"datachannel close: ".concat(e.code))),this.close()},s=async e=>{try{var t;null===(t=this._reliableTransmission)||void 0===t||t.onData(e.data)}catch(e){console.log(e)}};this._transmitter&&(this._transmitter.onclose=null,this._transmitter.close()),this._reliableTransmission&&(this._reliableTransmission.close(),this._reliableTransmission=void 0),SL.debug("[".concat(this._name,"] start connect, address: ").concat(JSON.stringify(e)));const a=null===(i=this._store)||void 0===i?void 0:i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"}),c=Date.now();dD(this,XF.TO_CONNECT_DATACHANNEL).then((e=>{var t,n;if(!e)throw new Error("transmissonInfo not exist yet");const i=e.transmitter,d=e.close;this._transmitter=i,null===(t=this._store)||void 0===t||t.signalChannelOpen();const l=Date.now()-c;SL.debug("[choose dc] dc open cost ".concat(l,"ms"));this._reliableTransmission=new Mae((e=>{var t;this._transmitter&&"open"===this._transmitter.readyState&&(null===(t=this._transmitter)||void 0===t||t.send(e))}),(e=>{if("string"==typeof e)this.emit(XF.ON_MESSAGE,e);else{const t=HW(e,{raw:!0}).buffer,n=this._textDecoder.decode(t);this.emit(XF.ON_MESSAGE,n)}})),this._closeEstablishingTransmitter=()=>{var e;null===(e=this._reliableTransmission)||void 0===e||e.close(),this._reliableTransmission=void 0,d()},r&&r(),i.onclose=o,i.onmessage=s,null===(n=this._store)||void 0===n||n.recordJoinChannelService({endTs:Date.now(),status:"success"},a),this._joinChannelServiceRecordIndex=a})).catch((e=>{var t;if(null===(t=this._store)||void 0===t||t.recordJoinChannelService({endTs:Date.now(),status:e instanceof YL&&e.code===wN.WS_ABORT?"aborted":"error",errors:[e]},a),"closed"!==this.state){if(e instanceof YL&&e.code===wN.WS_ERR){const t=new YL(wN.WS_ERR,"init datachannel failed! Error: ".concat(e.toString()));return SL.error("[".concat(this._name,"]").concat(t)),void n(t)}o&&o(e)}else n(new YL(wN.WS_DISCONNECT,"datachannel is closed: ".concat(e.toString())))}))}))}async reconnectWithAction(e){let t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(this._reconnectCount>=this._retryConfig.maxRetryCount)return!1;if(!this._addresses)return!1;if("closed"===this.state)return!1;this._onlineReconnectListener||pD.networkState!==aD.OFFLINE||(this._onlineReconnectListener=pD.onlineWaiter&&pD.onlineWaiter.then((()=>{this._onlineReconnectListener=void 0})));let n=!0;if(this._reconnectInterrupter=()=>{n=!1},t){const t=qD(this._reconnectCount,this._retryConfig);SL.debug("[".concat(this._name,"] wait ").concat(t,"ms to reconnect datachannel, mode: ").concat(e)),await cp.race([LD(t),this._onlineReconnectListener||new cp((()=>{}))])}if("closed"===this.state||!n)return!1;this._reconnectCount+=1;const i=async(e,t)=>{this.emit(XF.RECONNECT_CREATE_CONNECTION,t),await this.createTransmitterConnection(e)};try{if("retry"===e){const t=this._addresses[this.currentURLIndex];await i(t,e)}else if("tryNext"===e){this.currentURLIndex+=1;for(let e=this.currentURLIndex;e<this._addresses.length;e++){if(this._addresses[e].fingerprint||xP("FINGERPRINT")){this.currentURLIndex=e;break}this.currentURLIndex+=1}if(this.currentURLIndex>=this._addresses.length)return SL.debug("[".concat(this._name,"] the available addresses are exhausted, change to recover")),await this.reconnectWithAction("recover",!1);SL.debug("[".concat(this._name,"] datachannel url length: ").concat(this._addresses.length," current index: ").concat(this.currentURLIndex));const t=this._addresses[this.currentURLIndex];await i(t,e)}else"recover"===e&&(SL.debug("[".concat(this._name,"] start to failback to websocket")),this.resetReconnectCount("recover mode"),this.emit(XF.FAILBACK));return!0}catch(n){var r,o;return SL.error("[".concat(this._name,"] reconnect failed"),n.toString()),null!=n&&null!==(r=n.data)&&void 0!==r&&r.desc&&Array.isArray(n.data.desc)&&n.data.desc.length&&Ui(o=n.data.desc).call(o,"dynamic key expired")?(this.emit(XF.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):await this.reconnectWithAction(e,t)}}}class Vae extends YN{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===nF.CONNECTED?this.emit(iF.WS_CONNECTED):e===nF.RECONNECTING?this.emit(iF.WS_RECONNECTING,this._websocketReconnectReason):e===nF.CLOSED&&this.emit(iF.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket?this.websocket.url:null}get reportUrl(){return this.url}get rtt(){return this.rttRolling.mean()}processPendingNotifications(){0!==this.pendingNotifications.length&&(SL.debug("[".concat(this.clientId,"] processing ").concat(this.pendingNotifications.length," pending notifications")),this.pendingNotifications.forEach((e=>{let t=e.type,n=e.message;this.emit(t,n),t===sF.ON_NOTIFICATION&&this.handleNotification(n),t===sF.ON_USER_BANNED&&this.handleUserBanned(n)})),this.pendingNotifications=[])}handleUserBanned(e){switch(e.error_code){case 14:this.close($N.UID_BANNED);break;case 15:this.close($N.IP_BANNED);break;case 16:this.close($N.CHANNEL_BANNED)}}constructor(e,t){super(),zA(this,"__name__","DataChannelSignal"),zA(this,"_disconnectedReason",void 0),zA(this,"_websocketReconnectReason",void 0),zA(this,"_connectionState",nF.CLOSED),zA(this,"reconnectToken",void 0),zA(this,"websocket",void 0),zA(this,"openConnectionTime",void 0),zA(this,"clientId",void 0),zA(this,"lastMsgTime",Date.now()),zA(this,"uploadCache",[]),zA(this,"uploadCacheInterval",void 0),zA(this,"rttRolling",new eP(5)),zA(this,"pingpongTimer",void 0),zA(this,"inflateDataTimer",void 0),zA(this,"pingpongTimeoutCount",0),zA(this,"ortc",void 0),zA(this,"joinResponse",void 0),zA(this,"multiIpOption",void 0),zA(this,"initError",void 0),zA(this,"spec",void 0),zA(this,"store",void 0),zA(this,"isJoining",!1),zA(this,"pendingNotifications",[]),zA(this,"onWebsocketMessage",(e=>{if(e instanceof ArrayBuffer)return void this.emit(iF.ON_BINARY_DATA,e);const t=JSON.parse(e);if(xP("DC_DEBUG_LOG")&&SL.debug("[datachannel-signal] received packet",t),this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(t,"_id")){const e="res-@".concat(t._id);this.emit(e,t._result,t._message)}else Object.prototype.hasOwnProperty.call(t,"_type")&&(this.isJoining?t._type===sF.ON_NOTIFICATION||t._type===sF.ON_USER_BANNED?(this.emit(t._type,t._message),t._type===sF.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===sF.ON_USER_BANNED&&this.handleUserBanned(t._message)):(this.pendingNotifications.push({type:t._type,message:t._message}),SL.debug("[".concat(this.clientId,"] cached notification during join: ").concat(t._type))):(this.emit(t._type,t._message),t._type===sF.ON_NOTIFICATION&&this.handleNotification(t._message),t._type===sF.ON_USER_BANNED&&this.handleUserBanned(t._message)))})),this.clientId=e.clientId,this.spec=e,this.store=t,this.websocket=new Uae("gateway-".concat(this.clientId),this.spec.retryConfig,!0,t),this.handleWebsocketEvents(),window.addEventListener("offline",(()=>{this.connectionState===nF.CONNECTED&&this.reconnect("retry",YF.OFFLINE)}))}async request(e,t,n,i){const r=kD(6,""),o={_id:r,_type:e,_message:t},s=this.websocket.connectionID,a=()=>new cp(((t,n)=>{if(this.connectionState===nF.CONNECTED)return t();const i=()=>{this.off(iF.WS_CLOSED,r),t()},r=()=>{this.off(iF.WS_CONNECTED,i),n(new YL(wN.WS_ABORT))};this.once(iF.WS_CONNECTED,i),this.once(iF.WS_CLOSED,r),e!==rF.PUBLISH&&e!==rF.SUBSCRIBE&&e!==rF.UNSUBSCRIBE&&e!==rF.UNPUBLISH&&e!==rF.CONTROL&&e!==rF.RESTART_ICE||this.once(iF.DISCONNECT_P2P,(()=>{n(new YL(wN.DISCONNECT_P2P))})),e!==rF.PUBLISH&&e!==rF.RESTART_ICE||this.once(iF.ABORT_P2P_EXECUTION,(()=>{n(new YL(wN.DISCONNECT_P2P))}))}));if(this.connectionState!==nF.CONNECTING&&this.connectionState!==nF.RECONNECTING||e===rF.JOIN||e===rF.REJOIN||await a(),e===rF.LEAVE&&(this.websocket.unbindDcCloseEventListener(),i=!0),xP("DC_DEBUG_LOG")&&SL.debug("[datachannel-signal] sendMessage",o),await this.websocket.sendMessage(o,!0,!1),i)return;const c=new cp(((n,i)=>{let o=!1;const a=(i,r)=>{o=!0,n({isSuccess:"success"===i,message:r||{}}),this.off(iF.WS_CLOSED,c),this.off(iF.WS_RECONNECTING,c),this.emit(iF.REQUEST_SUCCESS,e,t)};this.once("res-@".concat(r),a);const c=()=>{i(new YL(wN.WS_ABORT,"type: ".concat(e))),this.off(iF.WS_CLOSED,c),this.off(iF.WS_RECONNECTING,c),this.off("res-@".concat(r),a)};this.once(iF.WS_CLOSED,c),this.once(iF.WS_RECONNECTING,c),LD(xP("SIGNAL_REQUEST_TIMEOUT")).then((()=>{this.websocket.connectionID!==s||o||(SL.warning("dc request timeout, type: ".concat(e)),this.emit(iF.REQUEST_TIMEOUT,e,t))}))}));let d=null;try{d=await c}catch(i){if(this.connectionState===nF.CLOSED||e===rF.LEAVE)throw new YL(wN.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?i.throw():e===rF.JOIN||e===rF.REJOIN?null:(await a(),await this.request(e,t))}if(d.isSuccess)return d.message;const l=Number(d.message.error_code||d.message.code),u=oB(l),h=new YL(wN.UNEXPECTED_RESPONSE,"".concat(u.desc,": ").concat(d.message.error_str),{code:l,data:d.message});return"success"===u.action?d.message:(SL.warning("[".concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(l,", message: ").concat(u.desc,", action: ").concat(u.action)),l===tF.ERR_TOO_MANY_BROADCASTERS?e===rF.JOIN||e===rF.REJOIN?(this.initError=h,this.close(),h.throw()):h.throw():"failed"===u.action?h.throw():"quit"===u.action?(this.initError=h,this.close(),h.throw()):(l===tF.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=d.message.option,SL.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",YF.MULTI_IP)):this.reconnect(u.action,YF.SERVER_ERROR),e===rF.JOIN||e===rF.REJOIN?null:await this.request(e,t)))}waitMessage(e,t){return new cp((n=>{const i=r=>{(!t||t(r))&&(this.off(e,i),n(r))};this.on(e,i)}))}uploadWRTCStats(e){if(!this.store.sessionId)return void SL.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const t={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(oF.WRTC_STATS,t)}upload(e,t){const n={_type:e,_message:t};try{this.websocket.sendMessage(n)}catch(e){const t=xP("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>t&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval((()=>{if(this.connectionState!==nF.CONNECTED)return;const e=this.uploadCache.splice(0,1)[0];0===this.uploadCache.length&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(e._type,e._message)}),xP("UPLOAD_CACHE_INTERVAL")||2e3))}}async send(e,t){const n={_type:e,_message:t};await this.websocket.sendMessage(n)}init(e){return this.initError=void 0,this.multiIpOption=void 0,this.joinResponse=void 0,this.reconnectToken=void 0,this.openConnectionTime=void 0,new cp(((t,n)=>{this.once(iF.WS_CONNECTED,(()=>t(this.joinResponse))),this.once(iF.WS_CLOSED,(()=>n(this.initError||new YL(wN.WS_ABORT)))),this.connectionState=nF.CONNECTING,this.websocket.init(e).catch(n),this.websocket.once(XF.FAILBACK,(()=>{n(new YL(wN.INIT_DATACHANNEL_TIMEOUT))})),this.inflateDataTimer&&window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=window.setInterval((()=>{this.handleInflateData()}),2e4),setTimeout((()=>{void 0===this.openConnectionTime&&(SL.debug("[".concat(this.clientId,"] init datachannel timeout while join with failback to websocket")),n(new YL(wN.INIT_DATACHANNEL_TIMEOUT)))}),xP("DC_JOIN_WITH_FAILBACK"))}))}close(e){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.inflateDataTimer&&(this.handleInflateData(),window.clearInterval(this.inflateDataTimer),this.inflateDataTimer=void 0),this.reconnectToken=void 0,this.joinResponse=void 0,this.isJoining=!1,this.pendingNotifications=[],this._disconnectedReason=e||$N.LEAVE,this.connectionState=nF.CLOSED,SL.debug("[".concat(this.clientId,"] ")+"will close datachannel in signal"),this.websocket.close(),e===$N.FALLBACK&&(this.websocket.removeAllListeners(),this.websocket=new Uae("gateway-".concat(this.clientId),this.spec.retryConfig,!0,this.store),this.handleWebsocketEvents())}async join(){if(this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),xP("DC_PINGPONG_INTERVAL")),!this.joinResponse){this.emit(iF.ABORT_P2P_EXECUTION),this.store.signalConnected();const e=await dD(this,iF.REQUEST_JOIN_INFO);this.store.joinReq(),this.isJoining=!0,this.pendingNotifications=[];const t=await this.request(rF.JOIN,e);if(this.store.joinRep(),this.ortc=null==e?void 0:e.ortc,!t)return this.emit(iF.REPORT_JOIN_GATEWAY,wN.TIMEOUT,this.reportUrl||""),!1;this.joinResponse=t,this.emit(iF.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=nF.CONNECTED,this.isJoining=!1,this.processPendingNotifications(),!0}async rejoin(){if(!this.reconnectToken)throw new YL(wN.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=hD(this,iF.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const t=await this.request(rF.REJOIN,e);return!!t&&(this.connectionState=nF.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),xP("DC_PINGPONG_INTERVAL")),t.peers&&t.peers.forEach((e=>{this.emit(sF.ON_USER_ONLINE,{uid:e.uid}),e.audio&&this.emit(sF.ON_ADD_AUDIO_STREAM,{uid:e.uid,uint_id:e.uint_id,audio:!0,ssrcId:e.audio_ssrc}),e.video&&this.emit(sF.ON_ADD_VIDEO_STREAM,{uid:e.uid,uint_id:e.uint_id,video:!0,ssrcId:e.video_ssrc}),e.audio_mute?this.emit(sF.MUTE_AUDIO,{uid:e.uid}):this.emit(sF.UNMUTE_AUDIO,{uid:e.uid}),e.video_mute?this.emit(sF.MUTE_VIDEO,{uid:e.uid}):this.emit(sF.UNMUTE_VIDEO,{uid:e.uid}),e.audio_enable_local?this.emit(sF.ENABLE_LOCAL_AUDIO,{uid:e.uid}):this.emit(sF.DISABLE_LOCAL_AUDIO,{uid:e.uid}),e.video_enable_local?this.emit(sF.ENABLE_LOCAL_VIDEO,{uid:e.uid}):this.emit(sF.DISABLE_LOCAL_VIDEO,{uid:e.uid}),e.audio||e.video||this.emit(sF.ON_REMOVE_STREAM,{uid:e.uid,uint_id:e.uint_id})})),!0)}reconnect(e,t){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,t)}async downgradeCodec(e){if(!this.ortc)return!1;const t={downgrade_codec:e,ortc:this.ortc};return!!await this.request(rF.DOWNGRADE_CODEC,t)}handleNotification(e){SL.debug("[".concat(this.clientId,"] receive notification: "),e);const t=oB(e.code);if("success"!==t.action){if("failed"!==t.action)return"quit"===t.action?("ERR_REPEAT_JOIN_CHANNEL"===t.desc&&this.close($N.UID_BANNED),void this.close()):void this.reconnect(t.action,YF.SERVER_ERROR);SL.error("[".concat(this.clientId,"] ignore error: "),t.desc)}}handlePingPong(){if(!this.websocket||"connected"!==this.websocket.state)return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1,xP("DC_DEBUG_LOG")&&console.debug("[datachannel-signal] pingpongTimeoutCount: ".concat(this.pingpongTimeoutCount));const e=xP("PING_PONG_TIME_OUT"),t=Date.now();this.pingpongTimeoutCount>=e&&(SL.warning("[datachannel-signal] PINGPONG Timeout. Last Socket Message: ".concat(t-this.lastMsgTime,"ms")),t-this.lastMsgTime>xP("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("recover",YF.FALLBACK):this.request(rF.PING,void 0,!0).then((()=>{this.pingpongTimeoutCount=0;const e=Date.now()-t;this.rttRolling.add(e),xP("REPORT_STATS")&&this.send(rF.PING_BACK,{pingpongElapse:e})})).catch((e=>{}))}handleInflateData(){const e=this.websocket.getInflateData(),t=e.inflateLength,n=e.deflateLength;0!==t&&0!==n&&this.upload(oF.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:n,ws_inflate_length:t})}handleWebsocketEvents(){this.websocket.on(XF.RECONNECT_CREATE_CONNECTION,(e=>{this.emit(iF.WS_RECONNECT_CREATE_CONNECTION,e)})),this.websocket.on(XF.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(XF.CLOSED,(()=>{this.connectionState=nF.CLOSED})),this.websocket.on(XF.FAILED,(()=>{this._disconnectedReason=$N.NETWORK_ERROR,this.connectionState=nF.CLOSED})),this.websocket.on(XF.RECONNECTING,(e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===nF.CONNECTED?this.connectionState=nF.RECONNECTING:this.connectionState=nF.CONNECTING})),this.websocket.on(XF.WILL_RECONNECT,((e,t)=>{if(hD(this,iF.IS_P2P_DISCONNECTED)&&"retry"===e)return SL.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),this.reconnectToken=void 0,this.emit(iF.NEED_RENEW_SESSION),this.emit(iF.DISCONNECT_P2P),t("tryNext");"retry"!==e&&(SL.debug("".concat(this.clientId," websockt will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0,this.emit(iF.NEED_RENEW_SESSION),this.emit(iF.DISCONNECT_P2P)),t(e)})),this.websocket.on(XF.CONNECTED,(()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch((e=>{SL.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",YF.SERVER_ERROR)})):this.join().catch((e=>{if(this.emit(iF.REPORT_JOIN_GATEWAY,e.message||e.code,this.reportUrl||""),e instanceof YL&&e.code===wN.UNEXPECTED_RESPONSE&&e.data.code===tF.ERR_NO_AUTHORIZED)return SL.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",YF.SERVER_ERROR);SL.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",YF.SERVER_ERROR):(this.initError=e,this.close())}))})),this.websocket.on(XF.REQUEST_NEW_URLS,((e,t)=>{dD(this,iF.REQUEST_RECOVER,this.multiIpOption).then(e).catch(t)})),this.websocket.on(XF.ON_TOKEN_PRIVILEGE_DID_EXPIRE,(()=>{this.emit(sF.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})),this.websocket.on(XF.TO_CONNECT_DATACHANNEL,((e,t)=>{dD(this,iF.PRE_CONNECT_PC).then(e).catch(t)})),this.websocket.on(XF.FAILBACK,(()=>{void 0!==this.openConnectionTime&&this.emit(iF.DATACHANNEL_FAILBACK)}))}}const xae={name:"DataChannelConnection",create:function(e){let t=e.store,n=e.spec;return new Nae(n,t)}};const Fae={name:"DataChannelSignal",create:function(e){let t=e.store,n=e.spec;return new Vae(n,t)}};AP(),VP("PROCESS_ID","process-".concat(kD(8,""),"-").concat(kD(4,""),"-").concat(kD(4,""),"-").concat(kD(4,""),"-").concat(kD(12,""))),function(){let e;try{e=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void SL.error("Error loading sdk config",e.message)}if(e)try{const t=JSON.parse(window.atob(e)),n=Date.now();SL.debug("Loading global parameters from cache",t),Object.keys(t).forEach((e=>{if(Object.prototype.hasOwnProperty.call(UP,e)){const i=t[e],r=i.value,o=i.expires;if(o&&o<=n)return;BP[e]=r,UP[e]=r}}))}catch(t){SL.error("Error loading mutableParamsCache: ".concat(e),t.message)}}(),Array.isArray(BP.AREAS)&&BP.AREAS.length>0&&Fee(BP.AREAS,!0);const Bae=(e,t,n)=>{SL.debug("setParameter key:".concat(e,", value:").concat(JSON.stringify(t))),VP(e,t,n)};Eee(Boe,!1),Eee(Xoe,!1),Eee(Dre,!1),Eee(Cse,!1),Eee(Voe,!1),Eee(lae,!1),Eee(Sae,!1),Eee(Rae,!1),Eee(xae,!1),Eee(Fae,!1);const jae=function(e){const t=new YN,n=e,i={getListeners:t.getListeners.bind(t),on:(e,n)=>(function(e,t){e===JF.SECURITY_POLICY_VIOLATION&&koe(t,!0)}(e,n),t.on.bind(t)(e,n)),addListener:t.addListener.bind(t),once:t.once.bind(t),off:t.off.bind(t),removeAllListeners:t.removeAllListeners.bind(t),emit:t.emit.bind(t),safeEmit:t.safeEmit.bind(t)};return Poe(Poe({},n),i)}({__TRACK_LIST__:gk,VERSION:wP,BUILD:kP,ESM_BUNDLER:!1,ESM:!0,UMD:!1,DEV:!1,setParameter:Bae,getParameter:xP,getSupportedCodec:async function(){let e={audio:[],video:[]};try{let t=new RTCPeerConnection;const n=await async function(e){let t;return JL().supportUnifiedPlan?(e.addTransceiver("video",{direction:"recvonly"}),e.addTransceiver("audio",{direction:"recvonly"}),t=(await e.createOffer()).sdp):t=(await e.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,t}(t);if(!n)return e;t.close(),t=null,e=function(e){const t={video:[],audio:[]};return e.match(/ VP8/i)&&t.video.push("VP8"),e.match(/ VP9/i)&&t.video.push("VP9"),e.match(/ AV1/i)&&t.video.push("AV1"),e.match(/ H264/i)&&t.video.push("H264"),e.match(/ H265/i)&&t.video.push("H265"),e.match(/ opus/i)&&t.audio.push("OPUS"),e.match(/ PCMU/i)&&t.audio.push("PCMU"),e.match(/ PCMA/i)&&t.audio.push("PCMA"),e.match(/ G722/i)&&t.audio.push("G722"),t}(n)}catch(e){throw new YL(wN.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return e},checkSystemRequirements:function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];const t=HL.reportApiInvoke(null,{name:zN.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:ZN.TRACER}),n=function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=!1;try{const n=window.RTCPeerConnection,i=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,r=window.WebSocket;t=!(!n||!r),e&&!i&&(t=!1),t&&TN()&&nN(75)&&(new n).close()}catch(e){SL.error("check system requirement failed: ",e),t=!1}return t}(e),i=boe();SL.debug("checkSystemRequirements, api:",n,"browser",i);const r=n&&i;return t.onSuccess(r),xP("IGNORE_RTC_DEVICE_CHECK")?n:r},getDevices:function(e){return gM.enumerateDevices(!0,!0,e)},getMicrophones:function(e){return gM.getRecordingDevices(e)},getCameras:function(e){return gM.getCamerasDevices(e)},getElectronScreenSources:lM,getPlaybackDevices:function(e){return gM.getSpeakers(e)},createClient:Coe,createCameraVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=xP("CAMERA_CAPTURE_CONFIG"),n=kD(8,"track-cam-"),i=HL.reportApiInvoke(null,{id:n,tag:ZN.TRACER,name:zN.CREATE_CAM_VIDEO_TRACK,options:[Xk({},e),t]});t&&(e.encoderConfig=t);const r=LM(e);let o=null;SL.info("start create camera video track with config",JSON.stringify(e),"trackId",n);try{o=(await _M({video:r},n)).getVideoTracks()[0]||null}catch(e){throw i.onError(e),e}if(!o){const e=new ON(wN.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(e),e.throw(SL)}if(e.optimizationMode&&yV(n,o,e,pk(e.encoderConfig)),xP("USE_STANDARD_BITRATE_DEFAULT")){const t=pk(e.encoderConfig);e.encoderConfig=t,delete t.bitrateMax,delete t.bitrateMin}const s=new RV(o,e,r,e.scalabiltyMode?Ek(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,n);return i.onSuccess(s.getTrackId()),SL.info("create camera video success, trackId:",n),s},createCustomVideoTrack:function(e){const t=kD(8,"track-cus-"),n=HL.reportApiInvoke(null,{id:t,tag:ZN.TRACER,name:zN.CREATE_CUSTOM_VIDEO_TRACK,options:[e]});xP("USE_STANDARD_BITRATE_DEFAULT")&&(delete e.bitrateMax,delete e.bitrateMin);const i=new TV(e.mediaStreamTrack,{width:e.width,height:e.height,frameRate:e.frameRate,bitrateMax:e.bitrateMax,bitrateMin:e.bitrateMin,minDownscaleWidth:e.minDownscaleWidth,minDownscaleHeight:e.minDownscaleHeight},e.scalabiltyMode?Ek(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,t,[Rk.CUSTOM_TRACK]);return n.onSuccess(i.getTrackId()),SL.info("create custom video track success with config",e,"trackId",i.getTrackId()),i},createScreenVideoTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"disable";const n="object"==typeof t?function(e){const t=kM(e);return ik()&&e.suppressLocalAudioPlayback&&(t.suppressLocalAudioPlayback=e.suppressLocalAudioPlayback),rk()&&e.restrictOwnAudio&&(t.restrictOwnAudio=!0),t}(t):void 0;n&&(t="auto");const i=kD(8,"track-scr-v-"),r=HL.reportApiInvoke(null,{id:i,tag:ZN.TRACER,name:zN.CREATE_SCREEN_VIDEO_TRACK,options:[Xk({},e),t]});e.encoderConfig?"string"==typeof e.encoderConfig||e.encoderConfig.width&&e.encoderConfig.height||(e.encoderConfig.width={max:1920},e.encoderConfig.height={max:1080}):e.encoderConfig="1080p_2";const o=function(e){const t={};e.screenSourceType&&(t.mediaSource=e.screenSourceType),e.extensionId&&JO()&&(t.extensionId=e.extensionId);const n=e.displaySurface,i=e.selfBrowserSurface,r=e.surfaceSwitching,o=e.systemAudio,s=e.preferCurrentTab,a=e.windowAudio,c=e.monitorTypeSurfaces;(tN(107)||rN(107)||lN(93))&&(n&&(DN(n,"displaySurface",["browser","window","monitor"]),t.displaySurface=n),i?(DN(i,"selfBrowserSurface",["exclude","include"]),t.selfBrowserSurface=i):t.selfBrowserSurface="include",r&&(DN(r,"surfaceSwitching",["exclude","include"]),t.surfaceSwitching=r)),(tN(105)||rN(105)||lN(91))&&o&&(DN(o,"systemAudio",["exclude","include"]),t.systemAudio=o),(tN(94)||rN(94)||lN(80))&&s&&(t.preferCurrentTab=!0),(tN(141)||rN(141)||lN(125))&&a&&(DN(a,"windowAudio",["exclude","system"]),t.windowAudio=a),(tN(119)||rN(119)||lN(105))&&c&&(DN(c,"monitorTypeSurfaces",["exclude","include"]),t.monitorTypeSurfaces=c),e.electronScreenSourceId&&(t.sourceId=e.electronScreenSourceId);const d=e.encoderConfig?_k(e.encoderConfig):null;return t.mandatory={chromeMediaSource:"desktop",maxWidth:d?d.width:void 0,maxHeight:d?d.height:void 0},d&&(d.frameRate&&("number"==typeof d.frameRate?(t.mandatory.maxFrameRate=d.frameRate,t.mandatory.minFrameRate=d.frameRate):(t.mandatory.maxFrameRate=d.frameRate.max||d.frameRate.ideal||d.frameRate.exact||void 0,t.mandatory.minFrameRate=d.frameRate.min||d.frameRate.ideal||d.frameRate.exact||void 0),t.frameRate=d.frameRate),d.width&&(t.width=d.width),d.height&&(t.height=d.height)),t}(e);let s=null,a=null;const c=JL();if(!c.supportShareAudio&&"enable"===t){const e=new ON(wN.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return r.onError(e),e.throw(SL)}SL.info("start create screen video track with config",e,"withAudio",t,"trackId",i);const d=c.supportShareAudio&&"disable"!==t;try{const e=await _M({screen:o,screenAudio:d?n||!0:void 0},i);s=e.getVideoTracks()[0]||null,a=e.getAudioTracks()[0]||null}catch(e){throw r.onError(e),e}if(!s){const e=new ON(wN.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(e),e.throw(SL)}if(!a&&"enable"===t){s&&s.stop();const e=new ON(wN.SHARE_AUDIO_NOT_ALLOWED);return r.onError(e),e.throw(SL)}e.optimizationMode||(e.optimizationMode="detail"),e.optimizationMode&&(yV(i,s,e,e.encoderConfig&&_k(e.encoderConfig)||void 0),e.encoderConfig&&"string"!=typeof e.encoderConfig&&(e.encoderConfig.bitrateMin=e.encoderConfig.bitrateMax));const l=new TV(s,e.encoderConfig?_k(e.encoderConfig):{},e.scalabiltyMode?Ek(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,i,[Rk.SCREEN_TRACK]);if(!a)return r.onSuccess(l.getTrackId()),SL.info("create screen video track success","video:",l.getTrackId()),l;const u=new IU(a,void 0,kD(8,"track-scr-a-"),!1);return r.onSuccess([l.getTrackId(),u.getTrackId()]),SL.info("create screen video track success","video:",l.getTrackId(),"audio:",u.getTrackId()),[l,u]},createMicrophoneAndCameraTracks:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=xP("CAMERA_CAPTURE_CONFIG"),i=kD(8,"track-mic-"),r=kD(8,"track-cam-"),o=HL.reportApiInvoke(null,{id:"".concat(i,"-").concat(r),tag:ZN.TRACER,name:zN.CREATE_MIC_AND_CAM_TRACKS,options:[e,t,n]});n&&(t.encoderConfig=n);const s=LM(t),a=MM(e);let c=null,d=null;SL.info("start create camera video track(".concat(r,") and microphone audio track(").concat(i,") with config, audio: ").concat(JSON.stringify(e),", video: ").concat(JSON.stringify(t)));try{const e=await _M({audio:a,video:s},"".concat(i,"-").concat(r));c=e.getAudioTracks()[0],d=e.getVideoTracks()[0]}catch(e){throw o.onError(e),e}if(!c||!d){const e=new ON(wN.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(e),e.throw(SL)}if(t.optimizationMode&&yV(r,d,t,pk(t.encoderConfig)),xP("USE_STANDARD_BITRATE_DEFAULT")){const e=pk(t.encoderConfig);t.encoderConfig=e,delete e.bitrateMax,delete e.bitrateMin}const l=new AU(c,e,a,i),u=new RV(d,t,s,t.scalabiltyMode?Ek(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,r);return o.onSuccess([l.getTrackId(),u.getTrackId()]),SL.info("create camera video track(".concat(r,") and microphone audio track(").concat(i,") success")),[l,u]},createMicrophoneAudioTrack:async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=kD(8,"track-mic-"),n=HL.reportApiInvoke(null,{id:t,tag:ZN.TRACER,name:zN.CREATE_MIC_AUDIO_TRACK,options:[e]}),i=MM(e);let r=null;SL.info("start create microphone audio track with config",JSON.stringify(e),"trackId",t);try{r=(await _M({audio:i},t)).getAudioTracks()[0]||null}catch(e){throw n.onError(e),e}if(!r){const e=new ON(wN.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(e),e.throw(SL)}const o=new AU(r,e,i,t);return n.onSuccess(o.getTrackId()),SL.info("create microphone audio track success, trackId:",t),o},createCustomAudioTrack:vV,createBufferSourceAudioTrack:async function(e){var t;const n=e.cacheOnlineFile,i=e.encoderConfig;let r=e.source;const o={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?null!==(t=File.name)&&void 0!==t?t:"File":r,cacheOnlineFile:n,encoderConfig:i},s=kD(8,"track-buf-"),a=HL.reportApiInvoke(null,{id:s,tag:ZN.TRACER,name:zN.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(xP("DISABLE_WEBAUDIO"))throw new ON(wN.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");SL.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",s);const c=r;if(!(r instanceof AudioBuffer))try{r=await async function(e,t){let n=null;if("string"==typeof e){const t=DU.get(e);if(t)return SL.debug("use cached audio resource: ",e),t;try{n=(await QD((()=>DO.get(e,{responseType:"arraybuffer"})),void 0,void 0,{maxRetryCount:3})).data}catch(e){throw new ON(wN.FETCH_AUDIO_FILE_FAILED,e.toString())}}else{const t=new cp(((t,n)=>{const i=new FileReader;i.onload=e=>{e.target?t(e.target.result):n(new ON(wN.READ_LOCAL_AUDIO_FILE_ERROR))},i.onerror=()=>{n(new ON(wN.READ_LOCAL_AUDIO_FILE_ERROR))},i.readAsArrayBuffer(e)}));n=await t}const i=await function(e){const t=tM();return new cp(((n,i)=>{t.decodeAudioData(e,(e=>{n(e)}),(e=>{i(new ON(wN.DECODE_AUDIO_FILE_FAILED,e.toString()))}))}))}(n);return"string"==typeof e&&t&&DU.set(e,i),i}(r,n)}catch(e){return a.onError(e),e.throw(SL)}const d=new NU(r),l=new wU(c,d,i?fk(i):{},s);return SL.info("create buffer source audio track success, trackId:",s),a.onSuccess(l.getTrackId()),l},setAppType:function(e){if(SL.debug("setAppType: ".concat(e)),!(Number.isInteger(e)&&e>=0))throw SL.debug("Invalid appType"),new YL(wN.INVALID_PARAMS,"invalid app type",e);VP("APP_TYPE",Math.floor(e))},setLogLevel:function(e){SL.setLogLevel(e)},enableLogUpload:function(){xP("USE_NEW_LOG")?VP("UPLOAD_LOG",!0):SL.enableLogUpload()},disableLogUpload:function(){xP("USE_NEW_LOG")?VP("UPLOAD_LOG",!1):SL.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new jte},checkAudioTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=HL.reportApiInvoke(null,{tag:ZN.TRACER,name:zN.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof IU||e instanceof FV)){const e=new YL(wN.INVALID_TRACK,"the parameter is not a audio track");return n.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const i=e instanceof IU?e.getTrackLabel():"remote_track",r=e.getVolumeLevel();let o=r,s=r;const a=Date.now();return new cp((r=>{const c=setInterval((()=>{const d=e.getVolumeLevel();o=d>o?d:o,s=d<s?d:s;const l=o-s>1e-4,u=Date.now()-a;if(l||u>t){clearInterval(c);const t=l,s={duration:u,deviceLabel:i,maxVolumeLevel:o,result:t};SL.info("[track-".concat(e.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(s))),n.onSuccess(s),r(t)}}),200)}))},checkVideoTrackIsActive:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5e3;const n=HL.reportApiInvoke(null,{tag:ZN.TRACER,name:zN.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[t]});if(!(e instanceof TV||e instanceof xV)){const e=new YL(wN.INVALID_TRACK,"the parameter is not a video track");return n.onError(e),e.throw()}t&&t<1e3&&(t=1e3);const i=e instanceof TV?e.getTrackLabel():"remote_track",r=e.getMediaStreamTrack(!0),o=document.createElement("video");o.style.width="1px",o.style.height="1px",o.setAttribute("muted",""),o.muted=!0,o.setAttribute("playsinline",""),o.controls=!1,(zO()||YO())&&(o.style.opacity="0.01",o.style.position="fixed",o.style.left="0",o.style.top="0",document.body.appendChild(o)),o.srcObject=new MediaStream([r]),o.play();const s=document.createElement("canvas");s.width=160,s.height=120;let a=0,c=0;try{const e=Date.now();a=await function(e,t,n,i){let r,o=0,s=null;return new cp(((a,c)=>{function d(){o>i&&r&&(r(),a(o));const t=n.getContext("2d");if(!t){const e=new YL(wN.UNEXPECTED_ERROR,"can not get canvas 2d context.");return SL.error(e.toString()),void c(e)}t.drawImage(e,0,0,160,120);const d=t.getImageData(0,0,n.width,n.height),l=Math.floor(d.data.length/3);if(s){for(let e=0;e<l;e+=3)if(d.data[e]!==s[e])return o+=1,void(s=d.data);s=d.data}else s=d.data}setTimeout((()=>{r&&(r(),a(o))}),t),r=rM((()=>{d()}),30)}))}(o,t,s,4),c=Date.now()-e}catch(e){throw n.onError(e),e}bie===xO.SAFARI&&(o.pause(),o.remove()),o.srcObject=null;const d=a>4,l={duration:c,changedPicNum:a,deviceLabel:i,result:d};return SL.info("[track-".concat(e.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(l))),n.onSuccess(l),d},setArea:Fee,audioElementPlayCenter:CM,resumeAudioContext:function(){return CM.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(e){Noe.processExternalMediaAEC(e)},registerExtensions:function(e){const t=xP("PLUGIN_INFO")||[];e.forEach((e=>{"name"in e&&!Ui(t).call(t,e.name)&&t.push(e.name);const n=e;n.__registered__=!0,n.logger.hookLog=SL.extLog,n.reporter.hookApiInvoke=HL.extApiInvoke,n.parameters&&Object.keys(n.parameters).forEach((e=>{n.parameters[e]=xP(e)}))})),Bae("PLUGIN_INFO",t)},ChannelMediaRelayError:yF,ChannelMediaRelayEvent:RF,ChannelMediaRelayState:vF,RemoteStreamFallbackType:Ck,RemoteStreamType:yk,ConnectionDisconnectedReason:$N,AudienceLatencyLevelType:QN,AREAS:wF,preload:async function(e,t,n,i){return jie(e,t,n,i)},startLastmileProbeTest:async function(e,t,n,i){let r={state:"unavailable"};await jie(e,t,n,i);const o=await Gie({appId:e,cname:t,token:n||e,uid:i,cloudProxyServer:"disabled"});if(!o)return r;await Kie(o);const s=Coe({mode:"rtc",codec:"vp8"});let a;try{a=await s.join(e,t,n,i,{networkQualityProbe:!0})}catch(e){return r}const c=new Bie,d=c.createMuteAudioTrack(),l=await vV({mediaStreamTrack:d});await s.publish([l]);const u=KC(await new cp(((e,t)=>{const n=setTimeout((()=>{clearTimeout(n),e([!0,null,"audio"])}),5e3);s.on("user-published",(async(t,i)=>{t.uid===a&&(clearTimeout(n),e([!1,t,i]))}))})),3),h=u[0],p=u[1],_=u[2];if(h||!p)return await s.unpublish([l]),await s.leave(),l.close(),c.close(),r;await s.subscribe(p,_),await new cp(((e,t)=>{const n=setTimeout((()=>{clearTimeout(n),e(null)}),5e3)}));const E=s.getRTCStats(),m=s.getLocalAudioStats(),f=E.RTT,g=m.sendJitterMs,S=m.currentPacketLossRate;return r={state:"complete",rtt:f,packetLossRate:S,jitter:g,networkQuality:((e,t,n)=>{let i=1;if(n>0){let e=Math.log(100*n)/Math.log(2)+1;e=Math.min(5,Math.max(0,e)),i=1-e/5}let r=1;if(e>0){let t=Math.log(e/40)/Math.log(2)+1;t=Math.min(5,Math.max(0,t)),r=1-t/5}let o=1;if(t>0){let e=Math.log(t/10)/Math.log(2.5)+1;e=Math.min(5,Math.max(0,e)),o=1-e/5}const s=.5*i+.3*r+.2*o;let a=0;return a=s>=.8?1:s>=.6?2:s>=.4?3:s>=.2?4:5,a})(f,g,S)},await s.unsubscribe(p),await s.unpublish([l]),await s.leave(),l.close(),c.close(),await Kie(o),r},use:e=>(Eee(e),jae)});Object.defineProperties(jae,{onAudioAutoplayFailed:{get:()=>TM.onAudioAutoplayFailed,set:e=>{TM.onAudioAutoplayFailed=e}},onAutoplayFailed:{get:()=>TM.onAutoplayFailed,set:e=>{TM.onAutoplayFailed=e}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>jae._onSecurityPolicyViolation,set(e){jae._onSecurityPolicyViolation=e,koe(e)}},__CLIENT_LIST__:{get:()=>xP("SHOW_GLOBAL_CLIENT_LIST")?Nx:[]}}),gM.on(xk.CAMERA_DEVICE_CHANGED,(e=>{SL.info("camera device changed",JSON.stringify(e)),jae.onCameraChanged&&jae.onCameraChanged(e),jae.safeEmit(JF.CAMERA_CHANGED,e)})),gM.on(xk.RECORDING_DEVICE_CHANGED,(e=>{SL.info("microphone device changed",JSON.stringify(e)),jae.onMicrophoneChanged&&jae.onMicrophoneChanged(e),jae.safeEmit(JF.MICROPHONE_CHANGED,e)})),gM.on(xk.PLAYOUT_DEVICE_CHANGED,(e=>{SL.debug("playout device changed",JSON.stringify(e)),jae.onPlaybackDeviceChanged&&jae.onPlaybackDeviceChanged(e),jae.safeEmit(JF.PLAYBACK_DEVICE_CHANGED,e)})),CM.onAutoplayFailed=()=>{SL.info("detect audio element autoplay failed"),TM.onAudioAutoplayFailed&&TM.onAudioAutoplayFailed()},eM.on("autoplay-failed",(()=>{SL.info("detect webaudio autoplay failed"),TM.onAudioAutoplayFailed&&TM.onAudioAutoplayFailed(),jae.safeEmit(JF.AUTOPLAY_FAILED)})),eM.on(ok.STATE_CHANGE,((e,t)=>{SL.info("audio context state changed: ".concat(t," => ").concat(e)),jae.onAudioContextStateChanged&&jae.onAudioContextStateChanged(e,t),jae.safeEmit(JF.AUDIO_CONTEXT_STATE_CHANGED,e,t)})),pD.on(cD.NETWORK_STATE_CHANGE,((e,t)=>{SL.info("[network-indicator] network state changed, ".concat(t," => ").concat(e))})),window&&(window.__ARTC__=jae);export{jae as default};