Files
yusheng-admin/dist/static/js/demo-DDf_ewnH.js
2025-10-23 11:07:17 +08:00

160 lines
1.2 MiB
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var H4=Object.getPrototypeOf;var K4=Reflect.get;var Mf=(ai,ce)=>(ce=Symbol[ai])?ce:Symbol.for("Symbol."+ai),Y4=ai=>{throw TypeError(ai)},XN=Math.pow;var Uf=(ai,ce,Ai)=>K4(H4(ai),Ai,ce);var C=(ai,ce,Ai)=>new Promise((Qe,Pt)=>{var Lt=mi=>{try{Ze(Ai.next(mi))}catch(Wi){Pt(Wi)}},bi=mi=>{try{Ze(Ai.throw(mi))}catch(Wi){Pt(Wi)}},Ze=mi=>mi.done?Qe(mi.value):Promise.resolve(mi.value).then(Lt,bi);Ze((Ai=Ai.apply(ai,ce)).next())}),q4=function(ai,ce){this[0]=ai,this[1]=ce};var vd=ai=>{var ce=ai[Mf("asyncIterator")],Ai=!1,Qe,Pt={};return ce==null?(ce=ai[Mf("iterator")](),Qe=Lt=>Pt[Lt]=bi=>ce[Lt](bi)):(ce=ce.call(ai),Qe=Lt=>Pt[Lt]=bi=>{if(Ai){if(Ai=!1,Lt==="throw")throw bi;return bi}return Ai=!0,{done:!1,value:new q4(new Promise(Ze=>{var mi=ce[Lt](bi);mi instanceof Object||Y4("Object expected"),Ze(mi)}),1)}}),Pt[Mf("iterator")]=()=>Pt,Qe("next"),"throw"in ce?Qe("throw"):Pt.throw=Lt=>{throw Lt},"return"in ce&&Qe("return"),Pt};import{fJ as xf,fK as z4,d as X4,n as Rs,t as J4,x as Q4,am as Z4,o as vs,c as Cs,e as Gi,P as $4,Q as tH,T as eH,f as JN,U as iH,_ as nH}from"./index-CRmU-Qpi.js";var Ih={exports:{}},rH=Ih.exports,QN;function oH(){return QN||(QN=1,function(ai,ce){(function(Ai,Qe){ai.exports=Qe()})(rH,function(){function Ai(t,e){return e.forEach(function(i){i&&typeof i!="string"&&!Array.isArray(i)&&Object.keys(i).forEach(function(n){if(n!=="default"&&!(n in t)){var r=Object.getOwnPropertyDescriptor(i,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return i[n]}})}})}),Object.freeze(t)}var Qe=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof xf!="undefined"?xf:typeof self!="undefined"?self:{};function Pt(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Lt=function(t){try{return!!t()}catch(e){return!0}},bi=!Lt(function(){var t=function(){}.bind();return typeof t!="function"||t.hasOwnProperty("prototype")}),Ze=bi,mi=Function.prototype,Wi=mi.call,Gn=Ze&&mi.bind.bind(Wi,Wi),de=Ze?Gn:function(t){return function(){return Wi.apply(t,arguments)}},$e=de({}.isPrototypeOf),Lo=function(t){return t&&t.Math===Math&&t},ie=Lo(typeof globalThis=="object"&&globalThis)||Lo(typeof window=="object"&&window)||Lo(typeof self=="object"&&self)||Lo(typeof Qe=="object"&&Qe)||Lo(typeof Qe=="object"&&Qe)||function(){return this}()||Function("return this")(),Ah=bi,yd=Function.prototype,ci=yd.apply,be=yd.call,fi=typeof Reflect=="object"&&Reflect.apply||(Ah?be.bind(ci):function(){return be.apply(ci,arguments)}),ar=de,Vf=ar({}.toString),Ha=ar("".slice),cr=function(t){return Ha(Vf(t),8,-1)},tD=cr,eD=de,Ka=function(t){if(tD(t)==="Function")return eD(t)},bh=typeof document=="object"&&document.all,Be=bh===void 0&&bh!==void 0?function(t){return typeof t=="function"||t===bh}:function(t){return typeof t=="function"},Id={},wi=!Lt(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),iD=bi,Ad=Function.prototype.call,Ye=iD?Ad.bind(Ad):function(){return Ad.apply(Ad,arguments)},bd={},Ff={}.propertyIsEnumerable,Bf=Object.getOwnPropertyDescriptor,nD=Bf&&!Ff.call({1:2},1);bd.f=nD?function(t){var e=Bf(this,t);return!!e&&e.enumerable}:Ff;var Zr,wd,$r=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},rD=Lt,oD=cr,wh=Object,sD=de("".split),Od=rD(function(){return!wh("z").propertyIsEnumerable(0)})?function(t){return oD(t)==="String"?sD(t,""):wh(t)}:wh,Nd=function(t){return t==null},aD=Nd,cD=TypeError,ko=function(t){if(aD(t))throw new cD("Can't call method on "+t);return t},dD=Od,lD=ko,to=function(t){return dD(lD(t))},uD=Be,gi=function(t){return typeof t=="object"?t!==null:uD(t)},sn={},Oh=sn,Nh=ie,hD=Be,jf=function(t){return hD(t)?t:void 0},Si=function(t,e){return arguments.length<2?jf(Oh[t])||jf(Nh[t]):Oh[t]&&Oh[t][e]||Nh[t]&&Nh[t][e]},Gf=ie.navigator,Wf=Gf&&Gf.userAgent,Pr=Wf?String(Wf):"",Hf=ie,Dh=Pr,Kf=Hf.process,Yf=Hf.Deno,qf=Kf&&Kf.versions||Yf&&Yf.version,zf=qf&&qf.v8;zf&&(wd=(Zr=zf.split("."))[0]>0&&Zr[0]<4?1:+(Zr[0]+Zr[1])),!wd&&Dh&&(!(Zr=Dh.match(/Edge\/(\d+)/))||Zr[1]>=74)&&(Zr=Dh.match(/Chrome\/(\d+)/))&&(wd=+Zr[1]);var Mo=wd,Xf=Mo,pD=Lt,_D=ie.String,Is=!!Object.getOwnPropertySymbols&&!pD(function(){var t=Symbol("symbol detection");return!_D(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Xf&&Xf<41}),Jf=Is&&!Symbol.sham&&typeof Symbol.iterator=="symbol",ED=Si,mD=Be,fD=$e,gD=Object,Ya=Jf?function(t){return typeof t=="symbol"}:function(t){var e=ED("Symbol");return mD(e)&&fD(e.prototype,gD(t))},SD=String,As=function(t){try{return SD(t)}catch(e){return"Object"}},TD=Be,RD=As,vD=TypeError,Hi=function(t){if(TD(t))return t;throw new vD(RD(t)+" is not a function")},CD=Hi,yD=Nd,Dd=function(t,e){var i=t[e];return yD(i)?void 0:CD(i)},Qf=Ye,Zf=Be,$f=gi,ID=TypeError,tg={exports:{}},eg=ie,AD=Object.defineProperty,bD=ie,wD=function(t,e){try{AD(eg,t,{value:e,configurable:!0,writable:!0})}catch(i){eg[t]=e}return e},ig="__core-js_shared__",ng=tg.exports=bD[ig]||wD(ig,{});(ng.versions||(ng.versions=[])).push({version:"3.42.0",mode:"pure",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.42.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Ph=tg.exports,rg=Ph,bs=function(t,e){return rg[t]||(rg[t]=e||{})},OD=ko,ND=Object,dr=function(t){return ND(OD(t))},DD=dr,PD=de({}.hasOwnProperty),ti=Object.hasOwn||function(t,e){return PD(DD(t),e)},LD=de,kD=0,MD=Math.random(),UD=LD(1 .toString),Lh=function(t){return"Symbol("+(t===void 0?"":t)+")_"+UD(++kD+MD,36)},xD=bs,og=ti,VD=Lh,FD=Is,BD=Jf,ws=ie.Symbol,kh=xD("wks"),jD=BD?ws.for||ws:ws&&ws.withoutSetter||VD,Re=function(t){return og(kh,t)||(kh[t]=FD&&og(ws,t)?ws[t]:jD("Symbol."+t)),kh[t]},GD=Ye,sg=gi,ag=Ya,WD=Dd,HD=function(t,e){var i,n;if(Zf(i=t.toString)&&!$f(n=Qf(i,t))||Zf(i=t.valueOf)&&!$f(n=Qf(i,t)))return n;throw new ID("Can't convert object to primitive value")},KD=TypeError,YD=Re("toPrimitive"),qD=function(t,e){if(!sg(t)||ag(t))return t;var i,n=WD(t,YD);if(n){if(i=GD(n,t,e),!sg(i)||ag(i))return i;throw new KD("Can't convert object to primitive value")}return HD(t)},zD=Ya,Mh=function(t){var e=qD(t,"string");return zD(e)?e:e+""},cg=gi,Uh=ie.document,XD=cg(Uh)&&cg(Uh.createElement),xh=function(t){return XD?Uh.createElement(t):{}},JD=xh,dg=!wi&&!Lt(function(){return Object.defineProperty(JD("div"),"a",{get:function(){return 7}}).a!==7}),QD=wi,ZD=Ye,$D=bd,tP=$r,eP=to,iP=Mh,nP=ti,rP=dg,lg=Object.getOwnPropertyDescriptor;Id.f=QD?lg:function(t,e){if(t=eP(t),e=iP(e),rP)try{return lg(t,e)}catch(i){}if(nP(t,e))return tP(!ZD($D.f,t,e),t[e])};var oP=Lt,sP=Be,aP=/#|\.prototype\./,qa=function(t,e){var i=dP[cP(t)];return i===uP||i!==lP&&(sP(e)?oP(e):!!e)},cP=qa.normalize=function(t){return String(t).replace(aP,".").toLowerCase()},dP=qa.data={},lP=qa.NATIVE="N",uP=qa.POLYFILL="P",ug=qa,hP=Hi,pP=bi,_P=Ka(Ka.bind),eo=function(t,e){return hP(t),e===void 0?t:pP?_P(t,e):function(){return t.apply(e,arguments)}},gn={},hg=wi&&Lt(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),EP=gi,mP=String,fP=TypeError,Mi=function(t){if(EP(t))return t;throw new fP(mP(t)+" is not an object")},gP=wi,SP=dg,TP=hg,Pd=Mi,pg=Mh,RP=TypeError,Vh=Object.defineProperty,vP=Object.getOwnPropertyDescriptor,Fh="enumerable",Bh="configurable",jh="writable";gn.f=gP?TP?function(t,e,i){if(Pd(t),e=pg(e),Pd(i),typeof t=="function"&&e==="prototype"&&"value"in i&&jh in i&&!i[jh]){var n=vP(t,e);n&&n[jh]&&(t[e]=i.value,i={configurable:Bh in i?i[Bh]:n[Bh],enumerable:Fh in i?i[Fh]:n[Fh],writable:!1})}return Vh(t,e,i)}:Vh:function(t,e,i){if(Pd(t),e=pg(e),Pd(i),SP)try{return Vh(t,e,i)}catch(n){}if("get"in i||"set"in i)throw new RP("Accessors not supported");return"value"in i&&(t[e]=i.value),t};var CP=gn,yP=$r,Uo=wi?function(t,e,i){return CP.f(t,e,yP(1,i))}:function(t,e,i){return t[e]=i,t},za=ie,IP=fi,AP=Ka,bP=Be,wP=Id.f,OP=ug,Os=sn,NP=eo,Ns=Uo,_g=ti,DP=function(t){var e=function(i,n,r){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,n)}return new t(i,n,r)}return IP(t,this,arguments)};return e.prototype=t.prototype,e},Nt=function(t,e){var i,n,r,o,s,a,c,d,l,u=t.target,h=t.global,p=t.stat,g=t.proto,m=h?za:p?za[u]:za[u]&&za[u].prototype,f=h?Os:Os[u]||Ns(Os,u,{})[u],T=f.prototype;for(o in e)n=!(i=OP(h?o:u+(p?".":"#")+o,t.forced))&&m&&_g(m,o),a=f[o],n&&(c=t.dontCallGetSet?(l=wP(m,o))&&l.value:m[o]),s=n&&c?c:e[o],(i||g||typeof a!=typeof s)&&(d=t.bind&&n?NP(s,za):t.wrap&&n?DP(s):g&&bP(s)?AP(s):s,(t.sham||s&&s.sham||a&&a.sham)&&Ns(d,"sham",!0),Ns(f,o,d),g&&(_g(Os,r=u+"Prototype")||Ns(Os,r,{}),Ns(Os[r],o,s),t.real&&T&&(i||!T[o])&&Ns(T,o,s)))},PP=Math.ceil,LP=Math.floor,kP=Math.trunc||function(t){var e=+t;return(e>0?LP:PP)(e)},MP=kP,Gh=function(t){var e=+t;return e!=e||e===0?0:MP(e)},UP=Gh,xP=Math.max,VP=Math.min,Wh=function(t,e){var i=UP(t);return i<0?xP(i+e,0):VP(i,e)},FP=Gh,BP=Math.min,Eg=function(t){var e=FP(t);return e>0?BP(e,9007199254740991):0},jP=Eg,io=function(t){return jP(t.length)},GP=to,WP=Wh,HP=io,mg=function(t){return function(e,i,n){var r=GP(e),o=HP(r);if(o===0)return!t&&-1;var s,a=WP(n,o);if(t&&i!=i){for(;o>a;)if((s=r[a++])!=s)return!0}else for(;o>a;a++)if((t||a in r)&&r[a]===i)return t||a||0;return!t&&-1}},Hh={includes:mg(!0),indexOf:mg(!1)},KP=Hh.includes;Nt({target:"Array",proto:!0,forced:Lt(function(){return!Array(1).includes()})},{includes:function(t){return KP(this,t,arguments.length>1?arguments[1]:void 0)}});var YP=ie,qP=sn,Sn=function(t,e){var i=qP[t+"Prototype"],n=i&&i[e];if(n)return n;var r=YP[t],o=r&&r.prototype;return o&&o[e]},zP=Sn("Array","includes"),XP=gi,JP=cr,QP=Re("match"),fg=function(t){var e;return XP(t)&&((e=t[QP])!==void 0?!!e:JP(t)==="RegExp")},ZP=fg,$P=TypeError,gg={};gg[Re("toStringTag")]="z";var Kh=String(gg)==="[object z]",tL=Kh,eL=Be,Ld=cr,iL=Re("toStringTag"),nL=Object,rL=Ld(function(){return arguments}())==="Arguments",no=tL?Ld:function(t){var e,i,n;return t===void 0?"Undefined":t===null?"Null":typeof(i=function(r,o){try{return r[o]}catch(s){}}(e=nL(t),iL))=="string"?i:rL?Ld(e):(n=Ld(e))==="Object"&&eL(e.callee)?"Arguments":n},oL=no,sL=String,Ki=function(t){if(oL(t)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return sL(t)},aL=Re("match"),cL=Nt,dL=function(t){if(ZP(t))throw new $P("The method doesn't accept regular expressions");return t},lL=ko,Sg=Ki,uL=function(t){var e=/./;try{"/./"[t](e)}catch(i){try{return e[aL]=!1,"/./"[t](e)}catch(n){}}return!1},hL=de("".indexOf);cL({target:"String",proto:!0,forced:!uL("includes")},{includes:function(t){return!!~hL(Sg(lL(this)),Sg(dL(t)),arguments.length>1?arguments[1]:void 0)}});var pL=Sn("String","includes"),Tg=$e,_L=zP,EL=pL,Yh=Array.prototype,qh=String.prototype,mL=function(t){var e=t.includes;return t===Yh||Tg(Yh,t)&&e===Yh.includes?_L:typeof t=="string"||t===qh||Tg(qh,t)&&e===qh.includes?EL:e},G=Pt(mL),fL=Hi,gL=dr,SL=Od,TL=io,Rg=TypeError,vg="Reduce of empty array with no initial value",Cg=function(t){return function(e,i,n,r){var o=gL(e),s=SL(o),a=TL(o);if(fL(i),a===0&&n<2)throw new Rg(vg);var c=t?a-1:0,d=t?-1:1;if(n<2)for(;;){if(c in s){r=s[c],c+=d;break}if(c+=d,t?c<0:a<=c)throw new Rg(vg)}for(;t?c>=0:a>c;c+=d)c in s&&(r=i(r,s[c],c,o));return r}},RL={left:Cg(!1),right:Cg(!0)},vL=Lt,kd=function(t,e){var i=[][t];return!!i&&vL(function(){i.call(null,e||function(){return 1},1)})},Xa=ie,CL=Pr,yL=cr,Md=function(t){return CL.slice(0,t.length)===t},zh=Md("Bun/")?"BUN":Md("Cloudflare-Workers")?"CLOUDFLARE":Md("Deno/")?"DENO":Md("Node.js/")?"NODE":Xa.Bun&&typeof Bun.version=="string"?"BUN":Xa.Deno&&typeof Deno.version=="object"?"DENO":yL(Xa.process)==="process"?"NODE":Xa.window&&Xa.document?"BROWSER":"REST",Ud=zh==="NODE",IL=RL.left;Nt({target:"Array",proto:!0,forced:!Ud&&Mo>79&&Mo<83||!kd("reduce")},{reduce:function(t){var e=arguments.length;return IL(this,t,e,e>1?arguments[1]:void 0)}});var AL=Sn("Array","reduce"),bL=$e,wL=AL,Xh=Array.prototype,OL=function(t){var e=t.reduce;return t===Xh||bL(Xh,t)&&e===Xh.reduce?wL:e},yg=OL,Tn=Pt(yg),NL=cr,Ja=Array.isArray||function(t){return NL(t)==="Array"},DL=Nt,PL=Ja,LL=de([].reverse),Ig=[1,2];DL({target:"Array",proto:!0,forced:String(Ig)===String(Ig.reverse())},{reverse:function(){return PL(this)&&(this.length=this.length),LL(this)}});var kL=Sn("Array","reverse"),ML=$e,UL=kL,Jh=Array.prototype,xL=function(t){var e=t.reverse;return t===Jh||ML(Jh,t)&&e===Jh.reverse?UL:e},Ag=xL,bg=Pt(Ag),VL=Lh,wg=bs("keys"),xd=function(t){return wg[t]||(wg[t]=VL(t))},FL=!Lt(function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}),BL=ti,jL=Be,GL=dr,WL=FL,Og=xd("IE_PROTO"),Qh=Object,HL=Qh.prototype,Zh=WL?Qh.getPrototypeOf:function(t){var e=GL(t);if(BL(e,Og))return e[Og];var i=e.constructor;return jL(i)&&e instanceof i?i.prototype:e instanceof Qh?HL:null},KL=de,YL=Hi,qL=gi,zL=function(t){return qL(t)||t===null},XL=String,JL=TypeError,QL=function(t,e,i){try{return KL(YL(Object.getOwnPropertyDescriptor(t,e)[i]))}catch(n){}},ZL=gi,$L=ko,tk=function(t){if(zL(t))return t;throw new JL("Can't set "+XL(t)+" as a prototype")},ek=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,i={};try{(t=QL(Object.prototype,"__proto__","set"))(i,[]),e=i instanceof Array}catch(n){}return function(n,r){return $L(n),tk(r),ZL(n)&&(e?t(n,r):n.__proto__=r),n}}():void 0),Vd={},Fd={},$h=ti,ik=to,nk=Hh.indexOf,rk=Fd,Ng=de([].push),Dg=function(t,e){var i,n=ik(t),r=0,o=[];for(i in n)!$h(rk,i)&&$h(n,i)&&Ng(o,i);for(;e.length>r;)$h(n,i=e[r++])&&(~nk(o,i)||Ng(o,i));return o},tp=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ok=Dg,sk=tp.concat("length","prototype");Vd.f=Object.getOwnPropertyNames||function(t){return ok(t,sk)};var Qa={};Qa.f=Object.getOwnPropertySymbols;var ak=Si,ck=Vd,dk=Qa,lk=Mi,uk=de([].concat),hk=ak("Reflect","ownKeys")||function(t){var e=ck.f(lk(t)),i=dk.f;return i?uk(e,i(t)):e},Pg=ti,pk=hk,_k=Id,Ek=gn,ep={},mk=Dg,fk=tp,Bd=Object.keys||function(t){return mk(t,fk)},gk=wi,Sk=hg,Tk=gn,Rk=Mi,vk=to,Ck=Bd;ep.f=gk&&!Sk?Object.defineProperties:function(t,e){Rk(t);for(var i,n=vk(e),r=Ck(e),o=r.length,s=0;o>s;)Tk.f(t,i=r[s++],n[i]);return t};var jd,Lg=Si("document","documentElement"),yk=Mi,Ik=ep,kg=tp,Ak=Fd,bk=Lg,wk=xh,ip="prototype",np="script",Mg=xd("IE_PROTO"),rp=function(){},Ug=function(t){return"<"+np+">"+t+"</"+np+">"},xg=function(t){t.write(Ug("")),t.close();var e=t.parentWindow.Object;return t=null,e},Gd=function(){try{jd=new ActiveXObject("htmlfile")}catch(r){}var t,e,i;Gd=typeof document!="undefined"?document.domain&&jd?xg(jd):(e=wk("iframe"),i="java"+np+":",e.style.display="none",bk.appendChild(e),e.src=String(i),(t=e.contentWindow.document).open(),t.write(Ug("document.F=Object")),t.close(),t.F):xg(jd);for(var n=kg.length;n--;)delete Gd[ip][kg[n]];return Gd()};Ak[Mg]=!0;var Za=Object.create||function(t,e){var i;return t!==null?(rp[ip]=yk(t),i=new rp,rp[ip]=null,i[Mg]=t):i=Gd(),e===void 0?i:Ik.f(i,e)},Ok=gi,Nk=Uo,Vg=Error,Dk=de("".replace),Pk=String(new Vg("zxcasd").stack),Fg=/\n\s*at [^:]*:[^\n]*/,Lk=Fg.test(Pk),kk=$r,Mk=!Lt(function(){var t=new Error("a");return!("stack"in t)||(Object.defineProperty(t,"stack",kk(1,7)),t.stack!==7)}),Uk=Uo,xk=function(t,e){if(Lk&&typeof t=="string"&&!Vg.prepareStackTrace)for(;e--;)t=Dk(t,Fg,"");return t},Vk=Mk,Bg=Error.captureStackTrace,Ds={},Fk=Ds,Bk=Re("iterator"),jk=Array.prototype,jg=function(t){return t!==void 0&&(Fk.Array===t||jk[Bk]===t)},Gk=no,Gg=Dd,Wk=Nd,Hk=Ds,Kk=Re("iterator"),Wd=function(t){if(!Wk(t))return Gg(t,Kk)||Gg(t,"@@iterator")||Hk[Gk(t)]},Yk=Ye,qk=Hi,zk=Mi,Xk=As,Jk=Wd,Qk=TypeError,op=function(t,e){var i=arguments.length<2?Jk(t):e;if(qk(i))return zk(Yk(i,t));throw new Qk(Xk(t)+" is not iterable")},Zk=Ye,Wg=Mi,$k=Dd,Hg=function(t,e,i){var n,r;Wg(t);try{if(!(n=$k(t,"return"))){if(e==="throw")throw i;return i}n=Zk(n,t)}catch(o){r=!0,n=o}if(e==="throw")throw i;if(r)throw n;return Wg(n),i},t1=eo,e1=Ye,i1=Mi,n1=As,r1=jg,o1=io,Kg=$e,s1=op,a1=Wd,Yg=Hg,c1=TypeError,Hd=function(t,e){this.stopped=t,this.result=e},qg=Hd.prototype,$a=function(t,e,i){var n,r,o,s,a,c,d,l=i&&i.that,u=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),g=!(!i||!i.INTERRUPTED),m=t1(e,l),f=function(R){return n&&Yg(n,"normal",R),new Hd(!0,R)},T=function(R){return u?(i1(R),g?m(R[0],R[1],f):m(R[0],R[1])):g?m(R,f):m(R)};if(h)n=t.iterator;else if(p)n=t;else{if(!(r=a1(t)))throw new c1(n1(t)+" is not iterable");if(r1(r)){for(o=0,s=o1(t);s>o;o++)if((a=T(t[o]))&&Kg(qg,a))return a;return new Hd(!1)}n=s1(t,r)}for(c=h?t.next:n.next;!(d=e1(c,n)).done;){try{a=T(d.value)}catch(R){Yg(n,"throw",R)}if(typeof a=="object"&&a&&Kg(qg,a))return a}return new Hd(!1)},d1=Ki,l1=Nt,u1=$e,h1=Zh,Kd=ek,p1=function(t,e,i){for(var n=pk(e),r=Ek.f,o=_k.f,s=0;s<n.length;s++){var a=n[s];Pg(t,a)||i&&Pg(i,a)||r(t,a,o(e,a))}},zg=Za,sp=Uo,ap=$r,_1=function(t,e){Ok(e)&&"cause"in e&&Nk(t,"cause",e.cause)},E1=function(t,e,i,n){Vk&&(Bg?Bg(t,e):Uk(t,"stack",xk(i,n)))},m1=$a,f1=function(t,e){return t===void 0?arguments.length<2?"":e:d1(t)},g1=Re("toStringTag"),Yd=Error,S1=[].push,Ps=function(t,e){var i,n=u1(cp,this);Kd?i=Kd(new Yd,n?h1(this):cp):(i=n?this:zg(cp),sp(i,g1,"Error")),e!==void 0&&sp(i,"message",f1(e)),E1(i,Ps,i.stack,1),arguments.length>2&&_1(i,arguments[2]);var r=[];return m1(t,S1,{that:r}),sp(i,"errors",r),i};Kd?Kd(Ps,Yd):p1(Ps,Yd,{name:!0});var cp=Ps.prototype=zg(Yd.prototype,{constructor:ap(1,Ps),message:ap(1,""),name:ap(1,"AggregateError")});l1({global:!0,constructor:!0,arity:2},{AggregateError:Ps});var qd,tc,zd,T1=Be,Xg=ie.WeakMap,R1=T1(Xg)&&/native code/.test(String(Xg)),Jg=ie,v1=gi,C1=Uo,dp=ti,lp=Ph,y1=xd,I1=Fd,Qg="Object already initialized",up=Jg.TypeError,A1=Jg.WeakMap;if(R1||lp.state){var lr=lp.state||(lp.state=new A1);lr.get=lr.get,lr.has=lr.has,lr.set=lr.set,qd=function(t,e){if(lr.has(t))throw new up(Qg);return e.facade=t,lr.set(t,e),e},tc=function(t){return lr.get(t)||{}},zd=function(t){return lr.has(t)}}else{var Ls=y1("state");I1[Ls]=!0,qd=function(t,e){if(dp(t,Ls))throw new up(Qg);return e.facade=t,C1(t,Ls,e),e},tc=function(t){return dp(t,Ls)?t[Ls]:{}},zd=function(t){return dp(t,Ls)}}var xo,Zg,$g,Vo={set:qd,get:tc,has:zd,enforce:function(t){return zd(t)?tc(t):qd(t,{})},getterFor:function(t){return function(e){var i;if(!v1(e)||(i=tc(e)).type!==t)throw new up("Incompatible receiver, "+t+" required");return i}}},hp=wi,b1=ti,tS=Function.prototype,w1=hp&&Object.getOwnPropertyDescriptor,pp=b1(tS,"name"),eS={EXISTS:pp,PROPER:pp&&function(){}.name==="something",CONFIGURABLE:pp&&(!hp||hp&&w1(tS,"name").configurable)},O1=Uo,ro=function(t,e,i,n){return n&&n.enumerable?t[e]=i:O1(t,e,i),t},N1=Lt,D1=Be,P1=gi,L1=Za,iS=Zh,k1=ro,_p=Re("iterator"),nS=!1;[].keys&&("next"in($g=[].keys())?(Zg=iS(iS($g)))!==Object.prototype&&(xo=Zg):nS=!0);var M1=!P1(xo)||N1(function(){var t={};return xo[_p].call(t)!==t});D1((xo=M1?{}:L1(xo))[_p])||k1(xo,_p,function(){return this});var rS={IteratorPrototype:xo,BUGGY_SAFARI_ITERATORS:nS},U1=no,x1=Kh?{}.toString:function(){return"[object "+U1(this)+"]"},V1=Kh,F1=gn.f,B1=Uo,j1=ti,G1=x1,oS=Re("toStringTag"),Lr=function(t,e,i,n){var r=i?t:t&&t.prototype;r&&(j1(r,oS)||F1(r,oS,{configurable:!0,value:e}),n&&!V1&&B1(r,"toString",G1))},W1=rS.IteratorPrototype,H1=Za,K1=$r,Y1=Lr,q1=Ds,z1=function(){return this},Ep=function(t,e,i,n){var r=e+" Iterator";return t.prototype=H1(W1,{next:K1(+!n,i)}),Y1(t,r,!1,!0),q1[r]=z1,t},X1=Nt,J1=Ye,Q1=eS,Z1=Ep,$1=Zh,tM=Lr,sS=ro,aS=Ds,eM=rS,iM=Q1.PROPER,Xd=eM.BUGGY_SAFARI_ITERATORS,mp=Re("iterator"),cS="keys",Jd="values",dS="entries",nM=function(){return this},lS=function(t,e,i,n,r,o,s){Z1(i,e,n);var a,c,d,l=function(T){if(T===r&&m)return m;if(!Xd&&T&&T in p)return p[T];switch(T){case cS:case Jd:case dS:return function(){return new i(this,T)}}return function(){return new i(this)}},u=e+" Iterator",h=!1,p=t.prototype,g=p[mp]||p["@@iterator"]||r&&p[r],m=!Xd&&g||l(r),f=e==="Array"&&p.entries||g;if(f&&(a=$1(f.call(new t)))!==Object.prototype&&a.next&&(tM(a,u,!0,!0),aS[u]=nM),iM&&r===Jd&&g&&g.name!==Jd&&(h=!0,m=function(){return J1(g,this)}),r)if(c={values:l(Jd),keys:o?m:l(cS),entries:l(dS)},s)for(d in c)(Xd||h||!(d in p))&&sS(p,d,c[d]);else X1({target:e,proto:!0,forced:Xd||h},c);return s&&p[mp]!==m&&sS(p,mp,m,{name:r}),aS[e]=m,c},Qd=function(t,e){return{value:t,done:e}},rM=to,uS=Ds,hS=Vo;gn.f;var oM=lS,Zd=Qd,pS="Array Iterator",sM=hS.set,aM=hS.getterFor(pS);oM(Array,"Array",function(t,e){sM(this,{type:pS,target:rM(t),index:0,kind:e})},function(){var t=aM(this),e=t.target,i=t.index++;if(!e||i>=e.length)return t.target=null,Zd(void 0,!0);switch(t.kind){case"keys":return Zd(i,!1);case"values":return Zd(e[i],!1)}return Zd([i,e[i]],!1)},"values"),uS.Arguments=uS.Array;var cM=gn,$d=function(t,e,i){return cM.f(t,e,i)},dM=Si,lM=$d,uM=wi,_S=Re("species"),hM=$e,pM=TypeError,fp=function(t,e){if(hM(e,t))return t;throw new pM("Incorrect invocation")},_M=Be,gp=Ph,EM=de(Function.toString);_M(gp.inspectSource)||(gp.inspectSource=function(t){return EM(t)});var ES=gp.inspectSource,mM=de,fM=Lt,mS=Be,gM=no,SM=ES,fS=function(){},gS=Si("Reflect","construct"),Sp=/^\s*(?:class|function)\b/,TM=mM(Sp.exec),RM=!Sp.test(fS),ec=function(t){if(!mS(t))return!1;try{return gS(fS,[],t),!0}catch(e){return!1}},SS=function(t){if(!mS(t))return!1;switch(gM(t)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return RM||!!TM(Sp,SM(t))}catch(e){return!0}};SS.sham=!0;var ic,ks,TS,Tp,tl=!gS||fM(function(){var t;return ec(ec.call)||!ec(Object)||!ec(function(){t=!0})||t})?SS:ec,vM=tl,CM=As,yM=TypeError,RS=Mi,IM=function(t){if(vM(t))return t;throw new yM(CM(t)+" is not a constructor")},AM=Nd,bM=Re("species"),Rp=function(t,e){var i,n=RS(t).constructor;return n===void 0||AM(i=RS(n)[bM])?e:IM(i)},oo=de([].slice),wM=TypeError,Fo=function(t,e){if(t<e)throw new wM("Not enough arguments");return t},vS=/(?:ipad|iphone|ipod).*applewebkit/i.test(Pr),an=ie,OM=fi,NM=eo,CS=Be,DM=ti,yS=Lt,IS=Lg,PM=oo,AS=xh,LM=Fo,kM=vS,MM=Ud,vp=an.setImmediate,Cp=an.clearImmediate,UM=an.process,yp=an.Dispatch,xM=an.Function,bS=an.MessageChannel,VM=an.String,Ip=0,nc={},wS="onreadystatechange";yS(function(){ic=an.location});var Ap=function(t){if(DM(nc,t)){var e=nc[t];delete nc[t],e()}},bp=function(t){return function(){Ap(t)}},OS=function(t){Ap(t.data)},NS=function(t){an.postMessage(VM(t),ic.protocol+"//"+ic.host)};vp&&Cp||(vp=function(t){LM(arguments.length,1);var e=CS(t)?t:xM(t),i=PM(arguments,1);return nc[++Ip]=function(){OM(e,void 0,i)},ks(Ip),Ip},Cp=function(t){delete nc[t]},MM?ks=function(t){UM.nextTick(bp(t))}:yp&&yp.now?ks=function(t){yp.now(bp(t))}:bS&&!kM?(Tp=(TS=new bS).port2,TS.port1.onmessage=OS,ks=NM(Tp.postMessage,Tp)):an.addEventListener&&CS(an.postMessage)&&!an.importScripts&&ic&&ic.protocol!=="file:"&&!yS(NS)?(ks=NS,an.addEventListener("message",OS,!1)):ks=wS in AS("script")?function(t){IS.appendChild(AS("script"))[wS]=function(){IS.removeChild(this),Ap(t)}}:function(t){setTimeout(bp(t),0)});var el={set:vp,clear:Cp},DS=ie,FM=wi,BM=Object.getOwnPropertyDescriptor,PS=function(t){if(!FM)return DS[t];var e=BM(DS,t);return e&&e.value},LS=function(){this.head=null,this.tail=null};LS.prototype={add:function(t){var e={item:t,next:null},i=this.tail;i?i.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return(this.head=t.next)===null&&(this.tail=null),t.item}};var Ms,wp,Op,Np,kS,MS=LS,jM=/ipad|iphone|ipod/i.test(Pr)&&typeof Pebble!="undefined",GM=/web0s(?!.*chrome)/i.test(Pr),Us=ie,WM=PS,US=eo,Dp=el.set,HM=MS,KM=vS,YM=jM,qM=GM,Pp=Ud,xS=Us.MutationObserver||Us.WebKitMutationObserver,VS=Us.document,FS=Us.process,il=Us.Promise,Lp=WM("queueMicrotask");if(!Lp){var nl=new HM,rl=function(){var t,e;for(Pp&&(t=FS.domain)&&t.exit();e=nl.get();)try{e()}catch(i){throw nl.head&&Ms(),i}t&&t.enter()};KM||Pp||qM||!xS||!VS?!YM&&il&&il.resolve?((Np=il.resolve(void 0)).constructor=il,kS=US(Np.then,Np),Ms=function(){kS(rl)}):Pp?Ms=function(){FS.nextTick(rl)}:(Dp=US(Dp,Us),Ms=function(){Dp(rl)}):(wp=!0,Op=VS.createTextNode(""),new xS(rl).observe(Op,{characterData:!0}),Ms=function(){Op.data=wp=!wp}),Lp=function(t){nl.head||Ms(),nl.add(t)}}var BS=Lp,xs=function(t){try{return{error:!1,value:t()}}catch(e){return{error:!0,value:e}}},Bo=ie.Promise,zM=ie,rc=Bo,XM=Be,JM=ug,QM=ES,ZM=Re,jS=zh,kp=Mo,GS=rc&&rc.prototype,$M=ZM("species"),WS=!1,HS=XM(zM.PromiseRejectionEvent),tU=JM("Promise",function(){var t=QM(rc),e=t!==String(rc);if(!e&&kp===66||!GS.catch||!GS.finally)return!0;if(!kp||kp<51||!/native code/.test(t)){var i=new rc(function(r){r(1)}),n=function(r){r(function(){},function(){})};if((i.constructor={})[$M]=n,!(WS=i.then(function(){})instanceof n))return!0}return!(e||jS!=="BROWSER"&&jS!=="DENO"||HS)}),oc={CONSTRUCTOR:tU,REJECTION_EVENT:HS,SUBCLASSING:WS},ur={},KS=Hi,eU=TypeError,iU=function(t){var e,i;this.promise=new t(function(n,r){if(e!==void 0||i!==void 0)throw new eU("Bad Promise constructor");e=n,i=r}),this.resolve=KS(e),this.reject=KS(i)};ur.f=function(t){return new iU(t)};var Mp,YS,nU=Nt,ol=Ud,so=ie,sc=Ye,rU=ro,oU=Lr,sU=function(t){var e=dM(t);uM&&e&&!e[_S]&&lM(e,_S,{configurable:!0,get:function(){return this}})},aU=Hi,Up=Be,cU=gi,dU=fp,lU=Rp,qS=el.set,xp=BS,uU=function(t,e){try{arguments.length===1?console.error(t):console.error(t,e)}catch(i){}},hU=xs,pU=MS,zS=Vo,Vp=Bo,XS=oc,JS=ur,sl="Promise",QS=XS.CONSTRUCTOR,_U=XS.REJECTION_EVENT,Fp=zS.getterFor(sl),EU=zS.set,mU=Vp&&Vp.prototype,ac=Vp,Bp=mU,ZS=so.TypeError,jp=so.document,Gp=so.process,Wp=JS.f,fU=Wp,gU=!!(jp&&jp.createEvent&&so.dispatchEvent),$S="unhandledrejection",tT=function(t){var e;return!(!cU(t)||!Up(e=t.then))&&e},eT=function(t,e){var i,n,r,o=e.value,s=e.state===1,a=s?t.ok:t.fail,c=t.resolve,d=t.reject,l=t.domain;try{a?(s||(e.rejection===2&&TU(e),e.rejection=1),a===!0?i=o:(l&&l.enter(),i=a(o),l&&(l.exit(),r=!0)),i===t.promise?d(new ZS("Promise-chain cycle")):(n=tT(i))?sc(n,i,c,d):c(i)):d(o)}catch(u){l&&!r&&l.exit(),d(u)}},iT=function(t,e){t.notified||(t.notified=!0,xp(function(){for(var i,n=t.reactions;i=n.get();)eT(i,t);t.notified=!1,e&&!t.rejection&&SU(t)}))},nT=function(t,e,i){var n,r;gU?((n=jp.createEvent("Event")).promise=e,n.reason=i,n.initEvent(t,!1,!0),so.dispatchEvent(n)):n={promise:e,reason:i},!_U&&(r=so["on"+t])?r(n):t===$S&&uU("Unhandled promise rejection",i)},SU=function(t){sc(qS,so,function(){var e,i=t.facade,n=t.value;if(rT(t)&&(e=hU(function(){ol?Gp.emit("unhandledRejection",n,i):nT($S,i,n)}),t.rejection=ol||rT(t)?2:1,e.error))throw e.value})},rT=function(t){return t.rejection!==1&&!t.parent},TU=function(t){sc(qS,so,function(){var e=t.facade;ol?Gp.emit("rejectionHandled",e):nT("rejectionhandled",e,t.value)})},Vs=function(t,e,i){return function(n){t(e,n,i)}},Fs=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,iT(t,!0))},Hp=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw new ZS("Promise can't be resolved itself");var n=tT(e);n?xp(function(){var r={done:!1};try{sc(n,e,Vs(Hp,r,t),Vs(Fs,r,t))}catch(o){Fs(r,o,t)}}):(t.value=e,t.state=1,iT(t,!1))}catch(r){Fs({done:!1},r,t)}}};QS&&(Bp=(ac=function(t){dU(this,Bp),aU(t),sc(Mp,this);var e=Fp(this);try{t(Vs(Hp,e),Vs(Fs,e))}catch(i){Fs(e,i)}}).prototype,(Mp=function(t){EU(this,{type:sl,done:!1,notified:!1,parent:!1,reactions:new pU,rejection:!1,state:0,value:null})}).prototype=rU(Bp,"then",function(t,e){var i=Fp(this),n=Wp(lU(this,ac));return i.parent=!0,n.ok=!Up(t)||t,n.fail=Up(e)&&e,n.domain=ol?Gp.domain:void 0,i.state===0?i.reactions.add(n):xp(function(){eT(n,i)}),n.promise}),YS=function(){var t=new Mp,e=Fp(t);this.promise=t,this.resolve=Vs(Hp,e),this.reject=Vs(Fs,e)},JS.f=Wp=function(t){return t===ac||t===void 0?new YS(t):fU(t)}),nU({global:!0,constructor:!0,wrap:!0,forced:QS},{Promise:ac}),oU(ac,sl,!1,!0),sU(sl);var oT=Re("iterator"),sT=!1;try{var RU=0,aT={next:function(){return{done:!!RU++}},return:function(){sT=!0}};aT[oT]=function(){return this},Array.from(aT,function(){throw 2})}catch(t){}var vU=Bo,CU=function(t,e){try{if(!e&&!sT)return!1}catch(r){return!1}var i=!1;try{var n={};n[oT]=function(){return{next:function(){return{done:i=!0}}}},t(n)}catch(r){}return i},al=oc.CONSTRUCTOR||!CU(function(t){vU.all(t).then(void 0,function(){})}),yU=Ye,IU=Hi,AU=ur,bU=xs,wU=$a;Nt({target:"Promise",stat:!0,forced:al},{all:function(t){var e=this,i=AU.f(e),n=i.resolve,r=i.reject,o=bU(function(){var s=IU(e.resolve),a=[],c=0,d=1;wU(t,function(l){var u=c++,h=!1;d++,yU(s,e,l).then(function(p){h||(h=!0,a[u]=p,--d||n(a))},r)}),--d||n(a)});return o.error&&r(o.value),i.promise}});var OU=Nt,NU=oc.CONSTRUCTOR;Bo&&Bo.prototype,OU({target:"Promise",proto:!0,forced:NU,real:!0},{catch:function(t){return this.then(void 0,t)}});var DU=Ye,PU=Hi,LU=ur,kU=xs,MU=$a;Nt({target:"Promise",stat:!0,forced:al},{race:function(t){var e=this,i=LU.f(e),n=i.reject,r=kU(function(){var o=PU(e.resolve);MU(t,function(s){DU(o,e,s).then(i.resolve,n)})});return r.error&&n(r.value),i.promise}});var UU=ur;Nt({target:"Promise",stat:!0,forced:oc.CONSTRUCTOR},{reject:function(t){var e=UU.f(this);return(0,e.reject)(t),e.promise}});var xU=Mi,VU=gi,FU=ur,cT=function(t,e){if(xU(t),VU(e)&&e.constructor===t)return e;var i=FU.f(t);return(0,i.resolve)(e),i.promise},BU=Nt,jU=Bo,GU=oc.CONSTRUCTOR,WU=cT,HU=Si("Promise"),KU=!GU;BU({target:"Promise",stat:!0,forced:!0},{resolve:function(t){return WU(KU&&this===HU?jU:this,t)}});var YU=Ye,qU=Hi,zU=ur,XU=xs,JU=$a;Nt({target:"Promise",stat:!0,forced:al},{allSettled:function(t){var e=this,i=zU.f(e),n=i.resolve,r=i.reject,o=XU(function(){var s=qU(e.resolve),a=[],c=0,d=1;JU(t,function(l){var u=c++,h=!1;d++,YU(s,e,l).then(function(p){h||(h=!0,a[u]={status:"fulfilled",value:p},--d||n(a))},function(p){h||(h=!0,a[u]={status:"rejected",reason:p},--d||n(a))})}),--d||n(a)});return o.error&&r(o.value),i.promise}});var QU=Ye,ZU=Hi,$U=Si,t2=ur,e2=xs,i2=$a,dT="No one promise resolved";Nt({target:"Promise",stat:!0,forced:al},{any:function(t){var e=this,i=$U("AggregateError"),n=t2.f(e),r=n.resolve,o=n.reject,s=e2(function(){var a=ZU(e.resolve),c=[],d=0,l=1,u=!1;i2(t,function(h){var p=d++,g=!1;l++,QU(a,e,h).then(function(m){g||u||(u=!0,r(m))},function(m){g||u||(g=!0,c[p]=m,--l||o(new i(c,dT)))})}),--l||o(new i(c,dT))});return s.error&&o(s.value),n.promise}});var n2=Nt,r2=fi,o2=oo,s2=ur,a2=Hi,lT=xs,Kp=ie.Promise,uT=!1;n2({target:"Promise",stat:!0,forced:!Kp||!Kp.try||lT(function(){Kp.try(function(t){uT=t===8},8)}).error||!uT},{try:function(t){var e=arguments.length>1?o2(arguments,1):[],i=s2.f(this),n=lT(function(){return r2(a2(t),void 0,e)});return(n.error?i.reject:i.resolve)(n.value),i.promise}});var c2=ur;Nt({target:"Promise",stat:!0},{withResolvers:function(){var t=c2.f(this);return{promise:t.promise,resolve:t.resolve,reject:t.reject}}});var d2=Nt,Yp=Bo,l2=Lt,u2=Si,h2=Be,p2=Rp,hT=cT,_2=Yp&&Yp.prototype;d2({target:"Promise",proto:!0,real:!0,forced:!!Yp&&l2(function(){_2.finally.call({then:function(){}},function(){})})},{finally:function(t){var e=p2(this,u2("Promise")),i=h2(t);return this.then(i?function(n){return hT(e,t()).then(function(){return n})}:t,i?function(n){return hT(e,t()).then(function(){throw n})}:t)}});var qp=de,E2=Gh,m2=Ki,f2=ko,g2=qp("".charAt),pT=qp("".charCodeAt),S2=qp("".slice),_T=function(t){return function(e,i){var n,r,o=m2(f2(e)),s=E2(i),a=o.length;return s<0||s>=a?t?"":void 0:(n=pT(o,s))<55296||n>56319||s+1===a||(r=pT(o,s+1))<56320||r>57343?t?g2(o,s):n:t?S2(o,s,s+2):r-56320+(n-55296<<10)+65536}},zp={codeAt:_T(!1),charAt:_T(!0)},T2=zp.charAt,R2=Ki,ET=Vo,v2=lS,mT=Qd,fT="String Iterator",C2=ET.set,y2=ET.getterFor(fT);v2(String,"String",function(t){C2(this,{type:fT,string:R2(t),index:0})},function(){var t,e=y2(this),i=e.string,n=e.index;return n>=i.length?mT(void 0,!0):(t=T2(i,n),e.index+=t.length,mT(t,!1))});var I2=sn.Promise,A2={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},b2=ie,w2=Lr,gT=Ds;for(var Xp in A2)w2(b2[Xp],Xp),gT[Xp]=gT.Array;var ST=I2,K=Pt(ST),O2=Sn("Array","values"),N2=no,D2=ti,P2=$e,L2=O2,Jp=Array.prototype,k2={DOMTokenList:!0,NodeList:!0},M2=function(t){var e=t.values;return t===Jp||P2(Jp,t)&&e===Jp.values||D2(k2,N2(t))?L2:e},Ui=Pt(M2),TT=As,U2=TypeError,RT=oo,x2=Math.floor,Qp=function(t,e){var i=t.length;if(i<8)for(var n,r,o=1;o<i;){for(r=o,n=t[o];r&&e(t[r-1],n)>0;)t[r]=t[--r];r!==o++&&(t[r]=n)}else for(var s=x2(i/2),a=Qp(RT(t,0,s),e),c=Qp(RT(t,s),e),d=a.length,l=c.length,u=0,h=0;u<d||h<l;)t[u+h]=u<d&&h<l?e(a[u],c[h])<=0?a[u++]:c[h++]:u<d?a[u++]:c[h++];return t},vT=Qp,CT=Pr.match(/firefox\/(\d+)/i),V2=!!CT&&+CT[1],F2=/MSIE|Trident/.test(Pr),yT=Pr.match(/AppleWebKit\/(\d+)\./),B2=!!yT&&+yT[1],j2=Nt,IT=de,G2=Hi,W2=dr,AT=io,H2=function(t,e){if(!delete t[e])throw new U2("Cannot delete property "+TT(e)+" of "+TT(t))},bT=Ki,Zp=Lt,K2=vT,Y2=kd,wT=V2,q2=F2,OT=Mo,NT=B2,ao=[],DT=IT(ao.sort),z2=IT(ao.push),X2=Zp(function(){ao.sort(void 0)}),J2=Zp(function(){ao.sort(null)}),Q2=Y2("sort"),PT=!Zp(function(){if(OT)return OT<70;if(!(wT&&wT>3)){if(q2)return!0;if(NT)return NT<603;var t,e,i,n,r="";for(t=65;t<76;t++){switch(e=String.fromCharCode(t),t){case 66:case 69:case 70:case 72:i=3;break;case 68:case 71:i=4;break;default:i=2}for(n=0;n<47;n++)ao.push({k:e+n,v:i})}for(ao.sort(function(o,s){return s.v-o.v}),n=0;n<ao.length;n++)e=ao[n].k.charAt(0),r.charAt(r.length-1)!==e&&(r+=e);return r!=="DGBEFHACIJK"}});j2({target:"Array",proto:!0,forced:X2||!J2||!Q2||!PT},{sort:function(t){t!==void 0&&G2(t);var e=W2(this);if(PT)return t===void 0?DT(e):DT(e,t);var i,n,r=[],o=AT(e);for(n=0;n<o;n++)n in e&&z2(r,e[n]);for(K2(r,function(s){return function(a,c){return c===void 0?-1:a===void 0?1:s!==void 0?+s(a,c)||0:bT(a)>bT(c)?1:-1}}(t)),i=AT(r),n=0;n<i;)e[n]=r[n++];for(;n<o;)H2(e,n++);return e}});var Z2=Sn("Array","sort"),$2=$e,tx=Z2,$p=Array.prototype,ex=function(t){var e=t.sort;return t===$p||$2($p,t)&&e===$p.sort?tx:e},jo=Pt(ex),ix=Nt,nx=de,rx=Wh,ox=RangeError,LT=String.fromCharCode,kT=String.fromCodePoint,sx=nx([].join);ix({target:"String",stat:!0,arity:1,forced:!!kT&&kT.length!==1},{fromCodePoint:function(t){for(var e,i=[],n=arguments.length,r=0;n>r;){if(e=+arguments[r++],rx(e,1114111)!==e)throw new ox(e+" is not a valid code point");i[r]=e<65536?LT(e):LT(55296+((e-=65536)>>10),e%1024+56320)}return sx(i,"")}});var ax=Lt,cx=Re("iterator"),cl=!ax(function(){var t=new URL("b?a=1&b=2&c=3","https://a"),e=t.searchParams,i=new URLSearchParams("a=1&a=2&b=3"),n="";return t.pathname="c%20d",e.forEach(function(r,o){e.delete("b"),n+=o+r}),i.delete("a",2),i.delete("b",void 0),!t.toJSON||!i.has("a",1)||i.has("a",2)||!i.has("a",void 0)||i.has("b")||!e.size&&!0||!e.sort||t.href!=="https://a/c%20d?a=1&c=3"||e.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!e[cx]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("https://тест").host!=="xn--e1aybc"||new URL("https://a#б").hash!=="#%D0%B1"||n!=="a1c3"||new URL("https://x",void 0).host!=="x"}),dx=ro,t_=Nt,MT=ie,e_=PS,lx=Si,dl=Ye,Wn=de,cc=wi,UT=cl,xT=ro,ux=$d,hx=function(t,e,i){for(var n in e)i&&i.unsafe&&t[n]?t[n]=e[n]:dx(t,n,e[n],i);return t},px=Lr,_x=Ep,i_=Vo,VT=fp,n_=Be,Ex=ti,mx=eo,fx=no,gx=Mi,FT=gi,xi=Ki,Sx=Za,BT=$r,jT=op,Tx=Wd,ll=Qd,Bs=Fo,Rx=vT,vx=Re("iterator"),js="URLSearchParams",GT=js+"Iterator",WT=i_.set,Rn=i_.getterFor(js),Cx=i_.getterFor(GT),HT=e_("fetch"),ul=e_("Request"),dc=e_("Headers"),r_=ul&&ul.prototype,KT=dc&&dc.prototype,yx=MT.TypeError,Ix=MT.encodeURIComponent,Ax=String.fromCharCode,bx=lx("String","fromCodePoint"),wx=parseInt,hl=Wn("".charAt),YT=Wn([].join),co=Wn([].push),qT=Wn("".replace),Ox=Wn([].shift),zT=Wn([].splice),XT=Wn("".split),JT=Wn("".slice),Nx=Wn(/./.exec),Dx=/\+/g,Px=/^[0-9a-f]+$/i,QT=function(t,e){var i=JT(t,e,e+2);return Nx(Px,i)?wx(i,16):NaN},Lx=function(t){for(var e=0,i=128;i>0&&t&i;i>>=1)e++;return e},kx=function(t){var e=null;switch(t.length){case 1:e=t[0];break;case 2:e=(31&t[0])<<6|63&t[1];break;case 3:e=(15&t[0])<<12|(63&t[1])<<6|63&t[2];break;case 4:e=(7&t[0])<<18|(63&t[1])<<12|(63&t[2])<<6|63&t[3]}return e>1114111?null:e},ZT=function(t){for(var e=(t=qT(t,Dx," ")).length,i="",n=0;n<e;){var r=hl(t,n);if(r==="%"){if(hl(t,n+1)==="%"||n+3>e){i+="%",n++;continue}var o=QT(t,n+1);if(o!=o){i+=r,n++;continue}n+=2;var s=Lx(o);if(s===0)r=Ax(o);else{if(s===1||s>4){i+="<22>",n++;continue}for(var a=[o],c=1;c<s&&!(++n+3>e||hl(t,n)!=="%");){var d=QT(t,n+1);if(d!=d){n+=3;break}if(d>191||d<128)break;co(a,d),n+=2,c++}if(a.length!==s){i+="<22>";continue}var l=kx(a);l===null?i+="<22>":r=bx(l)}}i+=r,n++}return i},Mx=/[!'()~]|%20/g,Ux={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},xx=function(t){return Ux[t]},$T=function(t){return qT(Ix(t),Mx,xx)},o_=_x(function(t,e){WT(this,{type:GT,target:Rn(t).entries,index:0,kind:e})},js,function(){var t=Cx(this),e=t.target,i=t.index++;if(!e||i>=e.length)return t.target=null,ll(void 0,!0);var n=e[i];switch(t.kind){case"keys":return ll(n.key,!1);case"values":return ll(n.value,!1)}return ll([n.key,n.value],!1)},!0),tR=function(t){this.entries=[],this.url=null,t!==void 0&&(FT(t)?this.parseObject(t):this.parseQuery(typeof t=="string"?hl(t,0)==="?"?JT(t,1):t:xi(t)))};tR.prototype={type:js,bindURL:function(t){this.url=t,this.update()},parseObject:function(t){var e,i,n,r,o,s,a,c=this.entries,d=Tx(t);if(d)for(i=(e=jT(t,d)).next;!(n=dl(i,e)).done;){if(o=(r=jT(gx(n.value))).next,(s=dl(o,r)).done||(a=dl(o,r)).done||!dl(o,r).done)throw new yx("Expected sequence with length 2");co(c,{key:xi(s.value),value:xi(a.value)})}else for(var l in t)Ex(t,l)&&co(c,{key:l,value:xi(t[l])})},parseQuery:function(t){if(t)for(var e,i,n=this.entries,r=XT(t,"&"),o=0;o<r.length;)(e=r[o++]).length&&(i=XT(e,"="),co(n,{key:ZT(Ox(i)),value:ZT(YT(i,"="))}))},serialize:function(){for(var t,e=this.entries,i=[],n=0;n<e.length;)t=e[n++],co(i,$T(t.key)+"="+$T(t.value));return YT(i,"&")},update:function(){this.entries.length=0,this.parseQuery(this.url.query)},updateURL:function(){this.url&&this.url.update()}};var pl=function(){VT(this,Gs);var t=WT(this,new tR(arguments.length>0?arguments[0]:void 0));cc||(this.size=t.entries.length)},Gs=pl.prototype;if(hx(Gs,{append:function(t,e){var i=Rn(this);Bs(arguments.length,2),co(i.entries,{key:xi(t),value:xi(e)}),cc||this.length++,i.updateURL()},delete:function(t){for(var e=Rn(this),i=Bs(arguments.length,1),n=e.entries,r=xi(t),o=i<2?void 0:arguments[1],s=o===void 0?o:xi(o),a=0;a<n.length;){var c=n[a];if(c.key!==r||s!==void 0&&c.value!==s)a++;else if(zT(n,a,1),s!==void 0)break}cc||(this.size=n.length),e.updateURL()},get:function(t){var e=Rn(this).entries;Bs(arguments.length,1);for(var i=xi(t),n=0;n<e.length;n++)if(e[n].key===i)return e[n].value;return null},getAll:function(t){var e=Rn(this).entries;Bs(arguments.length,1);for(var i=xi(t),n=[],r=0;r<e.length;r++)e[r].key===i&&co(n,e[r].value);return n},has:function(t){for(var e=Rn(this).entries,i=Bs(arguments.length,1),n=xi(t),r=i<2?void 0:arguments[1],o=r===void 0?r:xi(r),s=0;s<e.length;){var a=e[s++];if(a.key===n&&(o===void 0||a.value===o))return!0}return!1},set:function(t,e){var i=Rn(this);Bs(arguments.length,1);for(var n,r=i.entries,o=!1,s=xi(t),a=xi(e),c=0;c<r.length;c++)(n=r[c]).key===s&&(o?zT(r,c--,1):(o=!0,n.value=a));o||co(r,{key:s,value:a}),cc||(this.size=r.length),i.updateURL()},sort:function(){var t=Rn(this);Rx(t.entries,function(e,i){return e.key>i.key?1:-1}),t.updateURL()},forEach:function(t){for(var e,i=Rn(this).entries,n=mx(t,arguments.length>1?arguments[1]:void 0),r=0;r<i.length;)n((e=i[r++]).value,e.key,this)},keys:function(){return new o_(this,"keys")},values:function(){return new o_(this,"values")},entries:function(){return new o_(this,"entries")}},{enumerable:!0}),xT(Gs,vx,Gs.entries,{name:"entries"}),xT(Gs,"toString",function(){return Rn(this).serialize()},{enumerable:!0}),cc&&ux(Gs,"size",{get:function(){return Rn(this).entries.length},configurable:!0,enumerable:!0}),px(pl,js),t_({global:!0,constructor:!0,forced:!UT},{URLSearchParams:pl}),!UT&&n_(dc)){var Vx=Wn(KT.has),Fx=Wn(KT.set),eR=function(t){if(FT(t)){var e,i=t.body;if(fx(i)===js)return e=t.headers?new dc(t.headers):new dc,Vx(e,"content-type")||Fx(e,"content-type","application/x-www-form-urlencoded;charset=UTF-8"),Sx(t,{body:BT(0,xi(i)),headers:BT(0,e)})}return t};if(n_(HT)&&t_({global:!0,enumerable:!0,dontCallGetSet:!0,forced:!0},{fetch:function(t){return HT(t,arguments.length>1?eR(arguments[1]):{})}}),n_(ul)){var s_=function(t){return VT(this,r_),new ul(t,arguments.length>1?eR(arguments[1]):{})};r_.constructor=s_,s_.prototype=r_,t_({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:s_})}}var vn,Bx={URLSearchParams:pl,getState:Rn},jx=sn.URLSearchParams,iR=wi,Gx=de,Wx=Ye,Hx=Lt,a_=Bd,Kx=Qa,Yx=bd,qx=dr,zx=Od,Ws=Object.assign,nR=Object.defineProperty,Xx=Gx([].concat),Jx=!Ws||Hx(function(){if(iR&&Ws({b:1},Ws(nR({},"a",{enumerable:!0,get:function(){nR(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var t={},e={},i=Symbol("assign detection"),n="abcdefghijklmnopqrst";return t[i]=7,n.split("").forEach(function(r){e[r]=r}),Ws({},t)[i]!==7||a_(Ws({},e)).join("")!==n})?function(t,e){for(var i=qx(t),n=arguments.length,r=1,o=Kx.f,s=Yx.f;n>r;)for(var a,c=zx(arguments[r++]),d=o?Xx(a_(c),o(c)):a_(c),l=d.length,u=0;l>u;)a=d[u++],iR&&!Wx(s,c,a)||(i[a]=c[a]);return i}:Ws,Qx=Mi,Zx=Hg,$x=wi,tV=gn,eV=$r,c_=function(t,e,i){$x?tV.f(t,e,eV(0,i)):t[e]=i},iV=eo,nV=Ye,rV=dr,oV=function(t,e,i,n){try{return n?e(Qx(i)[0],i[1]):e(i)}catch(r){Zx(t,"throw",r)}},sV=jg,aV=tl,cV=io,rR=c_,dV=op,lV=Wd,oR=Array,Go=de,d_=2147483647,uV=/[^\0-\u007E]/,sR=/[.\u3002\uFF0E\uFF61]/g,aR="Overflow: input needs wider integers to process",cR=RangeError,hV=Go(sR.exec),Hs=Math.floor,l_=String.fromCharCode,dR=Go("".charCodeAt),lR=Go([].join),lo=Go([].push),pV=Go("".replace),_V=Go("".split),EV=Go("".toLowerCase),uR=function(t){return t+22+75*(t<26)},mV=function(t,e,i){var n=0;for(t=i?Hs(t/700):t>>1,t+=Hs(t/e);t>455;)t=Hs(t/35),n+=36;return Hs(n+36*t/(t+38))},fV=function(t){var e=[];t=function(T){for(var R=[],A=0,N=T.length;A<N;){var O=dR(T,A++);if(O>=55296&&O<=56319&&A<N){var w=dR(T,A++);(64512&w)==56320?lo(R,((1023&O)<<10)+(1023&w)+65536):(lo(R,O),A--)}else lo(R,O)}return R}(t);var i,n,r=t.length,o=128,s=0,a=72;for(i=0;i<t.length;i++)(n=t[i])<128&&lo(e,l_(n));var c=e.length,d=c;for(c&&lo(e,"-");d<r;){var l=d_;for(i=0;i<t.length;i++)(n=t[i])>=o&&n<l&&(l=n);var u=d+1;if(l-o>Hs((d_-s)/u))throw new cR(aR);for(s+=(l-o)*u,o=l,i=0;i<t.length;i++){if((n=t[i])<o&&++s>d_)throw new cR(aR);if(n===o){for(var h=s,p=36;;){var g=p<=a?1:p>=a+26?26:p-a;if(h<g)break;var m=h-g,f=36-g;lo(e,l_(uR(g+m%f))),h=Hs(m/f),p+=36}lo(e,l_(uR(h))),a=mV(s,u,d===c),s=0,d++}}s++,o++}return lR(e,"")},gV=Nt,u_=wi,SV=cl,h_=ie,hR=eo,Cn=de,_l=ro,yn=$d,TV=fp,p_=ti,__=Jx,Ks=function(t){var e=rV(t),i=aV(this),n=arguments.length,r=n>1?arguments[1]:void 0,o=r!==void 0;o&&(r=iV(r,n>2?arguments[2]:void 0));var s,a,c,d,l,u,h=lV(e),p=0;if(!h||this===oR&&sV(h))for(s=cV(e),a=i?new this(s):oR(s);s>p;p++)u=o?r(e[p],p):e[p],rR(a,p,u);else for(a=i?new this:[],l=(d=dV(e,h)).next;!(c=nV(l,d)).done;p++)u=o?oV(d,r,[c.value,p],!0):c.value,rR(a,p,u);return a.length=p,a},Hn=oo,RV=zp.codeAt,vV=function(t){var e,i,n=[],r=_V(pV(EV(t),sR,"."),".");for(e=0;e<r.length;e++)i=r[e],lo(n,hV(uV,i)?"xn--"+fV(i):i);return lR(n,".")},kr=Ki,CV=Lr,yV=Fo,pR=Bx,_R=Vo,IV=_R.set,El=_R.getterFor("URL"),AV=pR.URLSearchParams,bV=pR.getState,lc=h_.URL,E_=h_.TypeError,ml=h_.parseInt,wV=Math.floor,ER=Math.pow,In=Cn("".charAt),Kn=Cn(/./.exec),uc=Cn([].join),OV=Cn(1 .toString),NV=Cn([].pop),Ys=Cn([].push),m_=Cn("".replace),DV=Cn([].shift),PV=Cn("".split),hc=Cn("".slice),fl=Cn("".toLowerCase),LV=Cn([].unshift),f_="Invalid scheme",Wo="Invalid host",mR="Invalid port",fR=/[a-z]/i,kV=/[\d+-.a-z]/i,g_=/\d/,MV=/^0x/i,UV=/^[0-7]+$/,xV=/^\d+$/,gR=/^[\da-f]+$/i,VV=/[\0\t\n\r #%/:<>?@[\\\]^|]/,FV=/[\0\t\n\r #/:<>?@[\\\]^|]/,BV=/^[\u0000-\u0020]+/,jV=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,GV=/[\t\n\r]/g,pc=function(t){var e,i,n,r;if(typeof t=="number"){for(e=[],i=0;i<4;i++)LV(e,t%256),t=wV(t/256);return uc(e,".")}if(typeof t=="object"){for(e="",n=function(o){for(var s=null,a=1,c=null,d=0,l=0;l<8;l++)o[l]!==0?(d>a&&(s=c,a=d),c=null,d=0):(c===null&&(c=l),++d);return d>a?c:s}(t),i=0;i<8;i++)r&&t[i]===0||(r&&(r=!1),n===i?(e+=i?":":"::",r=!0):(e+=OV(t[i],16),i<7&&(e+=":")));return"["+e+"]"}return t},gl={},SR=__({},gl,{" ":1,'"':1,"<":1,">":1,"`":1}),TR=__({},SR,{"#":1,"?":1,"{":1,"}":1}),S_=__({},TR,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),uo=function(t,e){var i=RV(t,0);return i>32&&i<127&&!p_(e,t)?t:encodeURIComponent(t)},Sl={ftp:21,file:null,http:80,https:443,ws:80,wss:443},_c=function(t,e){var i;return t.length===2&&Kn(fR,In(t,0))&&((i=In(t,1))===":"||!e&&i==="|")},RR=function(t){var e;return t.length>1&&_c(hc(t,0,2))&&(t.length===2||(e=In(t,2))==="/"||e==="\\"||e==="?"||e==="#")},WV=function(t){return t==="."||fl(t)==="%2e"},T_={},vR={},R_={},CR={},yR={},v_={},IR={},AR={},Tl={},Rl={},C_={},y_={},I_={},A_={},bR={},b_={},qs={},hr={},wR={},Ho={},Mr={},w_=function(t,e,i){var n,r,o,s=kr(t);if(e){if(r=this.parse(s))throw new E_(r);this.searchParams=null}else{if(i!==void 0&&(n=new w_(i,!0)),r=this.parse(s,null,n))throw new E_(r);(o=bV(new AV)).bindURL(this),this.searchParams=o}};w_.prototype={type:"URL",parse:function(t,e,i){var n,r,o,s,a,c=this,d=e||T_,l=0,u="",h=!1,p=!1,g=!1;for(t=kr(t),e||(c.scheme="",c.username="",c.password="",c.host=null,c.port=null,c.path=[],c.query=null,c.fragment=null,c.cannotBeABaseURL=!1,t=m_(t,BV,""),t=m_(t,jV,"$1")),t=m_(t,GV,""),n=Ks(t);l<=n.length;){switch(r=n[l],d){case T_:if(!r||!Kn(fR,r)){if(e)return f_;d=R_;continue}u+=fl(r),d=vR;break;case vR:if(r&&(Kn(kV,r)||r==="+"||r==="-"||r==="."))u+=fl(r);else{if(r!==":"){if(e)return f_;u="",d=R_,l=0;continue}if(e&&(c.isSpecial()!==p_(Sl,u)||u==="file"&&(c.includesCredentials()||c.port!==null)||c.scheme==="file"&&!c.host))return;if(c.scheme=u,e)return void(c.isSpecial()&&Sl[c.scheme]===c.port&&(c.port=null));u="",c.scheme==="file"?d=A_:c.isSpecial()&&i&&i.scheme===c.scheme?d=CR:c.isSpecial()?d=AR:n[l+1]==="/"?(d=yR,l++):(c.cannotBeABaseURL=!0,Ys(c.path,""),d=wR)}break;case R_:if(!i||i.cannotBeABaseURL&&r!=="#")return f_;if(i.cannotBeABaseURL&&r==="#"){c.scheme=i.scheme,c.path=Hn(i.path),c.query=i.query,c.fragment="",c.cannotBeABaseURL=!0,d=Mr;break}d=i.scheme==="file"?A_:v_;continue;case CR:if(r!=="/"||n[l+1]!=="/"){d=v_;continue}d=Tl,l++;break;case yR:if(r==="/"){d=Rl;break}d=hr;continue;case v_:if(c.scheme=i.scheme,r===vn)c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Hn(i.path),c.query=i.query;else if(r==="/"||r==="\\"&&c.isSpecial())d=IR;else if(r==="?")c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Hn(i.path),c.query="",d=Ho;else{if(r!=="#"){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Hn(i.path),c.path.length--,d=hr;continue}c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,c.path=Hn(i.path),c.query=i.query,c.fragment="",d=Mr}break;case IR:if(!c.isSpecial()||r!=="/"&&r!=="\\"){if(r!=="/"){c.username=i.username,c.password=i.password,c.host=i.host,c.port=i.port,d=hr;continue}d=Rl}else d=Tl;break;case AR:if(d=Tl,r!=="/"||In(u,l+1)!=="/")continue;l++;break;case Tl:if(r!=="/"&&r!=="\\"){d=Rl;continue}break;case Rl:if(r==="@"){h&&(u="%40"+u),h=!0,o=Ks(u);for(var m=0;m<o.length;m++){var f=o[m];if(f!==":"||g){var T=uo(f,S_);g?c.password+=T:c.username+=T}else g=!0}u=""}else if(r===vn||r==="/"||r==="?"||r==="#"||r==="\\"&&c.isSpecial()){if(h&&u==="")return"Invalid authority";l-=Ks(u).length+1,u="",d=C_}else u+=r;break;case C_:case y_:if(e&&c.scheme==="file"){d=b_;continue}if(r!==":"||p){if(r===vn||r==="/"||r==="?"||r==="#"||r==="\\"&&c.isSpecial()){if(c.isSpecial()&&u==="")return Wo;if(e&&u===""&&(c.includesCredentials()||c.port!==null))return;if(s=c.parseHost(u))return s;if(u="",d=qs,e)return;continue}r==="["?p=!0:r==="]"&&(p=!1),u+=r}else{if(u==="")return Wo;if(s=c.parseHost(u))return s;if(u="",d=I_,e===y_)return}break;case I_:if(!Kn(g_,r)){if(r===vn||r==="/"||r==="?"||r==="#"||r==="\\"&&c.isSpecial()||e){if(u!==""){var R=ml(u,10);if(R>65535)return mR;c.port=c.isSpecial()&&R===Sl[c.scheme]?null:R,u=""}if(e)return;d=qs;continue}return mR}u+=r;break;case A_:if(c.scheme="file",r==="/"||r==="\\")d=bR;else{if(!i||i.scheme!=="file"){d=hr;continue}switch(r){case vn:c.host=i.host,c.path=Hn(i.path),c.query=i.query;break;case"?":c.host=i.host,c.path=Hn(i.path),c.query="",d=Ho;break;case"#":c.host=i.host,c.path=Hn(i.path),c.query=i.query,c.fragment="",d=Mr;break;default:RR(uc(Hn(n,l),""))||(c.host=i.host,c.path=Hn(i.path),c.shortenPath()),d=hr;continue}}break;case bR:if(r==="/"||r==="\\"){d=b_;break}i&&i.scheme==="file"&&!RR(uc(Hn(n,l),""))&&(_c(i.path[0],!0)?Ys(c.path,i.path[0]):c.host=i.host),d=hr;continue;case b_:if(r===vn||r==="/"||r==="\\"||r==="?"||r==="#"){if(!e&&_c(u))d=hr;else if(u===""){if(c.host="",e)return;d=qs}else{if(s=c.parseHost(u))return s;if(c.host==="localhost"&&(c.host=""),e)return;u="",d=qs}continue}u+=r;break;case qs:if(c.isSpecial()){if(d=hr,r!=="/"&&r!=="\\")continue}else if(e||r!=="?")if(e||r!=="#"){if(r!==vn&&(d=hr,r!=="/"))continue}else c.fragment="",d=Mr;else c.query="",d=Ho;break;case hr:if(r===vn||r==="/"||r==="\\"&&c.isSpecial()||!e&&(r==="?"||r==="#")){if((a=fl(a=u))===".."||a==="%2e."||a===".%2e"||a==="%2e%2e"?(c.shortenPath(),r==="/"||r==="\\"&&c.isSpecial()||Ys(c.path,"")):WV(u)?r==="/"||r==="\\"&&c.isSpecial()||Ys(c.path,""):(c.scheme==="file"&&!c.path.length&&_c(u)&&(c.host&&(c.host=""),u=In(u,0)+":"),Ys(c.path,u)),u="",c.scheme==="file"&&(r===vn||r==="?"||r==="#"))for(;c.path.length>1&&c.path[0]==="";)DV(c.path);r==="?"?(c.query="",d=Ho):r==="#"&&(c.fragment="",d=Mr)}else u+=uo(r,TR);break;case wR:r==="?"?(c.query="",d=Ho):r==="#"?(c.fragment="",d=Mr):r!==vn&&(c.path[0]+=uo(r,gl));break;case Ho:e||r!=="#"?r!==vn&&(r==="'"&&c.isSpecial()?c.query+="%27":c.query+=r==="#"?"%23":uo(r,gl)):(c.fragment="",d=Mr);break;case Mr:r!==vn&&(c.fragment+=uo(r,SR))}l++}},parseHost:function(t){var e,i,n;if(In(t,0)==="["){if(In(t,t.length-1)!=="]"||(e=function(r){var o,s,a,c,d,l,u,h=[0,0,0,0,0,0,0,0],p=0,g=null,m=0,f=function(){return In(r,m)};if(f()===":"){if(In(r,1)!==":")return;m+=2,g=++p}for(;f();){if(p===8)return;if(f()!==":"){for(o=s=0;s<4&&Kn(gR,f());)o=16*o+ml(f(),16),m++,s++;if(f()==="."){if(s===0||(m-=s,p>6))return;for(a=0;f();){if(c=null,a>0){if(!(f()==="."&&a<4))return;m++}if(!Kn(g_,f()))return;for(;Kn(g_,f());){if(d=ml(f(),10),c===null)c=d;else{if(c===0)return;c=10*c+d}if(c>255)return;m++}h[p]=256*h[p]+c,++a!=2&&a!==4||p++}if(a!==4)return;break}if(f()===":"){if(m++,!f())return}else if(f())return;h[p++]=o}else{if(g!==null)return;m++,g=++p}}if(g!==null)for(l=p-g,p=7;p!==0&&l>0;)u=h[p],h[p--]=h[g+l-1],h[g+--l]=u;else if(p!==8)return;return h}(hc(t,1,-1)),!e))return Wo;this.host=e}else if(this.isSpecial()){if(t=vV(t),Kn(VV,t)||(e=function(r){var o,s,a,c,d,l,u,h=PV(r,".");if(h.length&&h[h.length-1]===""&&h.length--,(o=h.length)>4)return r;for(s=[],a=0;a<o;a++){if((c=h[a])==="")return r;if(d=10,c.length>1&&In(c,0)==="0"&&(d=Kn(MV,c)?16:8,c=hc(c,d===8?1:2)),c==="")l=0;else{if(!Kn(d===10?xV:d===8?UV:gR,c))return r;l=ml(c,d)}Ys(s,l)}for(a=0;a<o;a++)if(l=s[a],a===o-1){if(l>=ER(256,5-o))return null}else if(l>255)return null;for(u=NV(s),a=0;a<s.length;a++)u+=s[a]*ER(256,3-a);return u}(t),e===null))return Wo;this.host=e}else{if(Kn(FV,t))return Wo;for(e="",i=Ks(t),n=0;n<i.length;n++)e+=uo(i[n],gl);this.host=e}},cannotHaveUsernamePasswordPort:function(){return!this.host||this.cannotBeABaseURL||this.scheme==="file"},includesCredentials:function(){return this.username!==""||this.password!==""},isSpecial:function(){return p_(Sl,this.scheme)},shortenPath:function(){var t=this.path,e=t.length;!e||this.scheme==="file"&&e===1&&_c(t[0],!0)||t.length--},serialize:function(){var t=this,e=t.scheme,i=t.username,n=t.password,r=t.host,o=t.port,s=t.path,a=t.query,c=t.fragment,d=e+":";return r!==null?(d+="//",t.includesCredentials()&&(d+=i+(n?":"+n:"")+"@"),d+=pc(r),o!==null&&(d+=":"+o)):e==="file"&&(d+="//"),d+=t.cannotBeABaseURL?s[0]:s.length?"/"+uc(s,"/"):"",a!==null&&(d+="?"+a),c!==null&&(d+="#"+c),d},setHref:function(t){var e=this.parse(t);if(e)throw new E_(e);this.searchParams.update()},getOrigin:function(){var t=this.scheme,e=this.port;if(t==="blob")try{return new zs(t.path[0]).origin}catch(i){return"null"}return t!=="file"&&this.isSpecial()?t+"://"+pc(this.host)+(e!==null?":"+e:""):"null"},getProtocol:function(){return this.scheme+":"},setProtocol:function(t){this.parse(kr(t)+":",T_)},getUsername:function(){return this.username},setUsername:function(t){var e=Ks(kr(t));if(!this.cannotHaveUsernamePasswordPort()){this.username="";for(var i=0;i<e.length;i++)this.username+=uo(e[i],S_)}},getPassword:function(){return this.password},setPassword:function(t){var e=Ks(kr(t));if(!this.cannotHaveUsernamePasswordPort()){this.password="";for(var i=0;i<e.length;i++)this.password+=uo(e[i],S_)}},getHost:function(){var t=this.host,e=this.port;return t===null?"":e===null?pc(t):pc(t)+":"+e},setHost:function(t){this.cannotBeABaseURL||this.parse(t,C_)},getHostname:function(){var t=this.host;return t===null?"":pc(t)},setHostname:function(t){this.cannotBeABaseURL||this.parse(t,y_)},getPort:function(){var t=this.port;return t===null?"":kr(t)},setPort:function(t){this.cannotHaveUsernamePasswordPort()||((t=kr(t))===""?this.port=null:this.parse(t,I_))},getPathname:function(){var t=this.path;return this.cannotBeABaseURL?t[0]:t.length?"/"+uc(t,"/"):""},setPathname:function(t){this.cannotBeABaseURL||(this.path=[],this.parse(t,qs))},getSearch:function(){var t=this.query;return t?"?"+t:""},setSearch:function(t){(t=kr(t))===""?this.query=null:(In(t,0)==="?"&&(t=hc(t,1)),this.query="",this.parse(t,Ho)),this.searchParams.update()},getSearchParams:function(){return this.searchParams.facade},getHash:function(){var t=this.fragment;return t?"#"+t:""},setHash:function(t){(t=kr(t))!==""?(In(t,0)==="#"&&(t=hc(t,1)),this.fragment="",this.parse(t,Mr)):this.fragment=null},update:function(){this.query=this.searchParams.serialize()||null}};var zs=function(t){var e=TV(this,Vi),i=yV(arguments.length,1)>1?arguments[1]:void 0,n=IV(e,new w_(t,!1,i));u_||(e.href=n.serialize(),e.origin=n.getOrigin(),e.protocol=n.getProtocol(),e.username=n.getUsername(),e.password=n.getPassword(),e.host=n.getHost(),e.hostname=n.getHostname(),e.port=n.getPort(),e.pathname=n.getPathname(),e.search=n.getSearch(),e.searchParams=n.getSearchParams(),e.hash=n.getHash())},Vi=zs.prototype,An=function(t,e){return{get:function(){return El(this)[t]()},set:e&&function(i){return El(this)[e](i)},configurable:!0,enumerable:!0}};if(u_&&(yn(Vi,"href",An("serialize","setHref")),yn(Vi,"origin",An("getOrigin")),yn(Vi,"protocol",An("getProtocol","setProtocol")),yn(Vi,"username",An("getUsername","setUsername")),yn(Vi,"password",An("getPassword","setPassword")),yn(Vi,"host",An("getHost","setHost")),yn(Vi,"hostname",An("getHostname","setHostname")),yn(Vi,"port",An("getPort","setPort")),yn(Vi,"pathname",An("getPathname","setPathname")),yn(Vi,"search",An("getSearch","setSearch")),yn(Vi,"searchParams",An("getSearchParams")),yn(Vi,"hash",An("getHash","setHash"))),_l(Vi,"toJSON",function(){return El(this).serialize()},{enumerable:!0}),_l(Vi,"toString",function(){return El(this).serialize()},{enumerable:!0}),lc){var OR=lc.createObjectURL,NR=lc.revokeObjectURL;OR&&_l(zs,"createObjectURL",hR(OR,lc)),NR&&_l(zs,"revokeObjectURL",hR(NR,lc))}CV(zs,"URL"),gV({global:!0,constructor:!0,forced:!SV,sham:!u_},{URL:zs});var HV=Nt,DR=Lt,KV=Fo,PR=Ki,YV=cl,O_=Si("URL"),qV=YV&&DR(function(){O_.canParse()}),zV=DR(function(){return O_.canParse.length!==1});HV({target:"URL",stat:!0,forced:!qV||zV},{canParse:function(t){var e=KV(arguments.length,1),i=PR(t),n=e<2||arguments[1]===void 0?void 0:PR(arguments[1]);try{return!!new O_(i,n)}catch(r){return!1}}});var XV=Nt,JV=Fo,LR=Ki,QV=cl,ZV=Si("URL");XV({target:"URL",stat:!0,forced:!QV},{parse:function(t){var e=JV(arguments.length,1),i=LR(t),n=e<2||arguments[1]===void 0?void 0:LR(arguments[1]);try{return new ZV(i,n)}catch(r){return null}}});var vl=Pt(sn.URL);let kR=!0,MR=!0;function Cl(t,e,i){const n=t.match(e);return n&&n.length>=i&&parseInt(n[i],10)}function Ko(t,e,i){if(!t.RTCPeerConnection)return;const n=t.RTCPeerConnection.prototype,r=n.addEventListener;n.addEventListener=function(s,a){if(s!==e)return r.apply(this,arguments);const c=d=>{const l=i(d);l&&(a.handleEvent?a.handleEvent(l):a(l))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(a,c),r.apply(this,[s,c])};const o=n.removeEventListener;n.removeEventListener=function(s,a){if(s!==e||!this._eventMap||!this._eventMap[e])return o.apply(this,arguments);if(!this._eventMap[e].has(a))return o.apply(this,arguments);const c=this._eventMap[e].get(a);return this._eventMap[e].delete(a),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,o.apply(this,[s,c])},Object.defineProperty(n,"on"+e,{get(){return this["_on"+e]},set(s){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),s&&this.addEventListener(e,this["_on"+e]=s)},enumerable:!0,configurable:!0})}function $V(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(kR=t,t?"adapter.js logging disabled":"adapter.js logging enabled")}function tF(t){return typeof t!="boolean"?new Error("Argument type: "+typeof t+". Please use a boolean."):(MR=!t,"adapter.js deprecation warnings "+(t?"disabled":"enabled"))}function UR(){if(typeof window=="object"){if(kR)return;typeof console!="undefined"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function N_(t,e){MR&&console.warn(t+" is deprecated, please use "+e+" instead.")}function xR(t){return Object.prototype.toString.call(t)==="[object Object]"}function VR(t){var e;return xR(t)?Tn(e=Object.keys(t)).call(e,function(i,n){const r=xR(t[n]),o=r?VR(t[n]):t[n],s=r&&!Object.keys(o).length;return o===void 0||s?i:Object.assign(i,{[n]:o})},{}):t}function D_(t,e,i){e&&!i.has(e.id)&&(i.set(e.id,e),Object.keys(e).forEach(n=>{n.endsWith("Id")?D_(t,t.get(e[n]),i):n.endsWith("Ids")&&e[n].forEach(r=>{D_(t,t.get(r),i)})}))}function FR(t,e,i){const n=i?"outbound-rtp":"inbound-rtp",r=new Map;if(e===null)return r;const o=[];return t.forEach(s=>{s.type==="track"&&s.trackIdentifier===e.id&&o.push(s)}),o.forEach(s=>{t.forEach(a=>{a.type===n&&a.trackId===s.id&&D_(t,a,r)})}),r}const BR=UR;function jR(t,e){const i=t&&t.navigator;if(!i.mediaDevices)return;const n=function(s){if(typeof s!="object"||s.mandatory||s.optional)return s;const a={};return Object.keys(s).forEach(c=>{if(c==="require"||c==="advanced"||c==="mediaSource")return;const d=typeof s[c]=="object"?s[c]:{ideal:s[c]};d.exact!==void 0&&typeof d.exact=="number"&&(d.min=d.max=d.exact);const l=function(u,h){return u?u+h.charAt(0).toUpperCase()+h.slice(1):h==="deviceId"?"sourceId":h};if(d.ideal!==void 0){a.optional=a.optional||[];let u={};typeof d.ideal=="number"?(u[l("min",c)]=d.ideal,a.optional.push(u),u={},u[l("max",c)]=d.ideal,a.optional.push(u)):(u[l("",c)]=d.ideal,a.optional.push(u))}d.exact!==void 0&&typeof d.exact!="number"?(a.mandatory=a.mandatory||{},a.mandatory[l("",c)]=d.exact):["min","max"].forEach(u=>{d[u]!==void 0&&(a.mandatory=a.mandatory||{},a.mandatory[l(u,c)]=d[u])})}),s.advanced&&(a.optional=(a.optional||[]).concat(s.advanced)),a},r=function(s,a){if(e.version>=61)return a(s);if((s=JSON.parse(JSON.stringify(s)))&&typeof s.audio=="object"){const c=function(d,l,u){l in d&&!(u in d)&&(d[u]=d[l],delete d[l])};c((s=JSON.parse(JSON.stringify(s))).audio,"autoGainControl","googAutoGainControl"),c(s.audio,"noiseSuppression","googNoiseSuppression"),s.audio=n(s.audio)}if(s&&typeof s.video=="object"){let c=s.video.facingMode;c=c&&(typeof c=="object"?c:{ideal:c});const d=e.version<66;if(c&&(c.exact==="user"||c.exact==="environment"||c.ideal==="user"||c.ideal==="environment")&&(!i.mediaDevices.getSupportedConstraints||!i.mediaDevices.getSupportedConstraints().facingMode||d)){let l;if(delete s.video.facingMode,c.exact==="environment"||c.ideal==="environment"?l=["back","rear"]:c.exact!=="user"&&c.ideal!=="user"||(l=["front"]),l)return i.mediaDevices.enumerateDevices().then(u=>{let h=(u=u.filter(p=>p.kind==="videoinput")).find(p=>l.some(g=>{var m;return G(m=p.label.toLowerCase()).call(m,g)}));return!h&&u.length&&G(l).call(l,"back")&&(h=u[u.length-1]),h&&(s.video.deviceId=c.exact?{exact:h.deviceId}:{ideal:h.deviceId}),s.video=n(s.video),BR("chrome: "+JSON.stringify(s)),a(s)})}s.video=n(s.video)}return BR("chrome: "+JSON.stringify(s)),a(s)},o=function(s){return e.version>=64?s:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[s.name]||s.name,message:s.message,constraint:s.constraint||s.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(i.getUserMedia=function(s,a,c){r(s,d=>{i.webkitGetUserMedia(d,a,l=>{c&&c(o(l))})})}.bind(i),i.mediaDevices.getUserMedia){const s=i.mediaDevices.getUserMedia.bind(i.mediaDevices);i.mediaDevices.getUserMedia=function(a){return r(a,c=>s(c).then(d=>{if(c.audio&&!d.getAudioTracks().length||c.video&&!d.getVideoTracks().length)throw d.getTracks().forEach(l=>{l.stop()}),new DOMException("","NotFoundError");return d},d=>K.reject(o(d))))}}}function GR(t){t.MediaStream=t.MediaStream||t.webkitMediaStream}function WR(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("ontrack"in t.RTCPeerConnection.prototype)){Object.defineProperty(t.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(i){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=i)},enumerable:!0,configurable:!0});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=i=>{i.stream.addEventListener("addtrack",n=>{let r;r=t.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(s=>s.track&&s.track.id===n.track.id):{track:n.track};const o=new Event("track");o.track=n.track,o.receiver=r,o.transceiver={receiver:r},o.streams=[i.stream],this.dispatchEvent(o)}),i.stream.getTracks().forEach(n=>{let r;r=t.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(s=>s.track&&s.track.id===n.id):{track:n};const o=new Event("track");o.track=n,o.receiver=r,o.transceiver={receiver:r},o.streams=[i.stream],this.dispatchEvent(o)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else Ko(t,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function HR(t){if(typeof t=="object"&&t.RTCPeerConnection&&!("getSenders"in t.RTCPeerConnection.prototype)&&"createDTMFSender"in t.RTCPeerConnection.prototype){const e=function(r,o){return{track:o,get dtmf(){return this._dtmf===void 0&&(o.kind==="audio"?this._dtmf=r.createDTMFSender(o):this._dtmf=null),this._dtmf},_pc:r}};if(!t.RTCPeerConnection.prototype.getSenders){t.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const r=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(s,a){let c=r.apply(this,arguments);return c||(c=e(this,s),this._senders.push(c)),c};const o=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(s){o.apply(this,arguments);const a=this._senders.indexOf(s);a!==-1&&this._senders.splice(a,1)}}const i=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(r){this._senders=this._senders||[],i.apply(this,[r]),r.getTracks().forEach(o=>{this._senders.push(e(this,o))})};const n=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(r){this._senders=this._senders||[],n.apply(this,[r]),r.getTracks().forEach(o=>{const s=this._senders.find(a=>a.track===o);s&&this._senders.splice(this._senders.indexOf(s),1)})}}else if(typeof t=="object"&&t.RTCPeerConnection&&"getSenders"in t.RTCPeerConnection.prototype&&"createDTMFSender"in t.RTCPeerConnection.prototype&&t.RTCRtpSender&&!("dtmf"in t.RTCRtpSender.prototype)){const e=t.RTCPeerConnection.prototype.getSenders;t.RTCPeerConnection.prototype.getSenders=function(){const i=e.apply(this,[]);return i.forEach(n=>n._pc=this),i},Object.defineProperty(t.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function KR(t){if(!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[i,n,r]=arguments;if(arguments.length>0&&typeof i=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof i!="function"))return e.apply(this,[]);const o=function(a){const c={};return a.result().forEach(d=>{const l={id:d.id,timestamp:d.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[d.type]||d.type};d.names().forEach(u=>{l[u]=d.stat(u)}),c[l.id]=l}),c},s=function(a){return new Map(Object.keys(a).map(c=>[c,a[c]]))};if(arguments.length>=2){const a=function(c){n(s(o(c)))};return e.apply(this,[a,i])}return new K((a,c)=>{e.apply(this,[function(d){a(s(o(d)))},c])}).then(n,r)}}function YR(t){if(!(typeof t=="object"&&t.RTCPeerConnection&&t.RTCRtpSender&&t.RTCRtpReceiver))return;if(!("getStats"in t.RTCRtpSender.prototype)){const i=t.RTCPeerConnection.prototype.getSenders;i&&(t.RTCPeerConnection.prototype.getSenders=function(){const r=i.apply(this,[]);return r.forEach(o=>o._pc=this),r});const n=t.RTCPeerConnection.prototype.addTrack;n&&(t.RTCPeerConnection.prototype.addTrack=function(){const r=n.apply(this,arguments);return r._pc=this,r}),t.RTCRtpSender.prototype.getStats=function(){const r=this;return this._pc.getStats().then(o=>FR(o,r.track,!0))}}if(!("getStats"in t.RTCRtpReceiver.prototype)){const i=t.RTCPeerConnection.prototype.getReceivers;i&&(t.RTCPeerConnection.prototype.getReceivers=function(){const n=i.apply(this,[]);return n.forEach(r=>r._pc=this),n}),Ko(t,"track",n=>(n.receiver._pc=n.srcElement,n)),t.RTCRtpReceiver.prototype.getStats=function(){const n=this;return this._pc.getStats().then(r=>FR(r,n.track,!1))}}if(!("getStats"in t.RTCRtpSender.prototype)||!("getStats"in t.RTCRtpReceiver.prototype))return;const e=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof t.MediaStreamTrack){const i=arguments[0];let n,r,o;return this.getSenders().forEach(s=>{s.track===i&&(n?o=!0:n=s)}),this.getReceivers().forEach(s=>(s.track===i&&(r?o=!0:r=s),s.track===i)),o||n&&r?K.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):n?n.getStats():r?r.getStats():K.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function qR(t){t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(o=>this._shimmedLocalStreams[o][0])};const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addTrack=function(o,s){if(!s)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const a=e.apply(this,arguments);return this._shimmedLocalStreams[s.id]?this._shimmedLocalStreams[s.id].indexOf(a)===-1&&this._shimmedLocalStreams[s.id].push(a):this._shimmedLocalStreams[s.id]=[s,a],a};const i=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(o){this._shimmedLocalStreams=this._shimmedLocalStreams||{},o.getTracks().forEach(c=>{if(this.getSenders().find(l=>l.track===c))throw new DOMException("Track already exists.","InvalidAccessError")});const s=this.getSenders();i.apply(this,arguments);const a=this.getSenders().filter(c=>s.indexOf(c)===-1);this._shimmedLocalStreams[o.id]=[o].concat(a)};const n=t.RTCPeerConnection.prototype.removeStream;t.RTCPeerConnection.prototype.removeStream=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[o.id],n.apply(this,arguments)};const r=t.RTCPeerConnection.prototype.removeTrack;t.RTCPeerConnection.prototype.removeTrack=function(o){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},o&&Object.keys(this._shimmedLocalStreams).forEach(s=>{const a=this._shimmedLocalStreams[s].indexOf(o);a!==-1&&this._shimmedLocalStreams[s].splice(a,1),this._shimmedLocalStreams[s].length===1&&delete this._shimmedLocalStreams[s]}),r.apply(this,arguments)}}function zR(t,e){if(!t.RTCPeerConnection)return;if(t.RTCPeerConnection.prototype.addTrack&&e.version>=65)return qR(t);const i=t.RTCPeerConnection.prototype.getLocalStreams;t.RTCPeerConnection.prototype.getLocalStreams=function(){const c=i.apply(this);return this._reverseStreams=this._reverseStreams||{},c.map(d=>this._reverseStreams[d.id])};const n=t.RTCPeerConnection.prototype.addStream;t.RTCPeerConnection.prototype.addStream=function(c){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.getTracks().forEach(d=>{if(this.getSenders().find(u=>u.track===d))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[c.id]){const d=new t.MediaStream(c.getTracks());this._streams[c.id]=d,this._reverseStreams[d.id]=c,c=d}n.apply(this,[c])};const r=t.RTCPeerConnection.prototype.removeStream;function o(c,d){let l=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(u=>{const h=c._reverseStreams[u],p=c._streams[h.id];l=l.replace(new RegExp(p.id,"g"),h.id)}),new RTCSessionDescription({type:d.type,sdp:l})}t.RTCPeerConnection.prototype.removeStream=function(c){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},r.apply(this,[this._streams[c.id]||c]),delete this._reverseStreams[this._streams[c.id]?this._streams[c.id].id:c.id],delete this._streams[c.id]},t.RTCPeerConnection.prototype.addTrack=function(c,d){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const l=[].slice.call(arguments,1);if(l.length!==1||!l[0].getTracks().find(p=>p===c))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(p=>p.track===c))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const h=this._streams[d.id];if(h)h.addTrack(c),K.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const p=new t.MediaStream([c]);this._streams[d.id]=p,this._reverseStreams[p.id]=d,this.addStream(p)}return this.getSenders().find(p=>p.track===c)},["createOffer","createAnswer"].forEach(function(c){const d=t.RTCPeerConnection.prototype[c],l={[c](){const u=arguments;return arguments.length&&typeof arguments[0]=="function"?d.apply(this,[h=>{const p=o(this,h);u[0].apply(null,[p])},h=>{u[1]&&u[1].apply(null,h)},arguments[2]]):d.apply(this,arguments).then(h=>o(this,h))}};t.RTCPeerConnection.prototype[c]=l[c]});const s=t.RTCPeerConnection.prototype.setLocalDescription;t.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(c,d){let l=d.sdp;return Object.keys(c._reverseStreams||[]).forEach(u=>{const h=c._reverseStreams[u],p=c._streams[h.id];l=l.replace(new RegExp(h.id,"g"),p.id)}),new RTCSessionDescription({type:d.type,sdp:l})}(this,arguments[0]),s.apply(this,arguments)):s.apply(this,arguments)};const a=Object.getOwnPropertyDescriptor(t.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(t.RTCPeerConnection.prototype,"localDescription",{get(){const c=a.get.apply(this);return c.type===""?c:o(this,c)}}),t.RTCPeerConnection.prototype.removeTrack=function(c){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!c._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(c._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let d;this._streams=this._streams||{},Object.keys(this._streams).forEach(l=>{this._streams[l].getTracks().find(u=>c.track===u)&&(d=this._streams[l])}),d&&(d.getTracks().length===1?this.removeStream(this._reverseStreams[d.id]):d.removeTrack(c.track),this.dispatchEvent(new Event("negotiationneeded")))}}function P_(t,e){!t.RTCPeerConnection&&t.webkitRTCPeerConnection&&(t.RTCPeerConnection=t.webkitRTCPeerConnection),t.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(i){const n=t.RTCPeerConnection.prototype[i],r={[i](){return arguments[0]=new(i==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};t.RTCPeerConnection.prototype[i]=r[i]})}function XR(t,e){Ko(t,"negotiationneeded",i=>{const n=i.target;if(!(e.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics==="plan-b")||n.signalingState==="stable")return i})}var JR=Object.freeze({__proto__:null,fixNegotiationNeeded:XR,shimAddTrackRemoveTrack:zR,shimAddTrackRemoveTrackWithNative:qR,shimGetDisplayMedia:function(t,e){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(typeof e=="function"?t.navigator.mediaDevices.getDisplayMedia=function(i){return e(i).then(n=>{const r=i.video&&i.video.width,o=i.video&&i.video.height,s=i.video&&i.video.frameRate;return i.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:n,maxFrameRate:s||3}},r&&(i.video.mandatory.maxWidth=r),o&&(i.video.mandatory.maxHeight=o),t.navigator.mediaDevices.getUserMedia(i)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))},shimGetSendersWithDtmf:HR,shimGetStats:KR,shimGetUserMedia:jR,shimMediaStream:GR,shimOnTrack:WR,shimPeerConnection:P_,shimSenderReceiverGetStats:YR});function QR(t,e){const i=t&&t.navigator,n=t&&t.MediaStreamTrack;if(i.getUserMedia=function(r,o,s){N_("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),i.mediaDevices.getUserMedia(r).then(o,s)},!(e.version>55&&"autoGainControl"in i.mediaDevices.getSupportedConstraints())){const r=function(s,a,c){a in s&&!(c in s)&&(s[c]=s[a],delete s[a])},o=i.mediaDevices.getUserMedia.bind(i.mediaDevices);if(i.mediaDevices.getUserMedia=function(s){return typeof s=="object"&&typeof s.audio=="object"&&(s=JSON.parse(JSON.stringify(s)),r(s.audio,"autoGainControl","mozAutoGainControl"),r(s.audio,"noiseSuppression","mozNoiseSuppression")),o(s)},n&&n.prototype.getSettings){const s=n.prototype.getSettings;n.prototype.getSettings=function(){const a=s.apply(this,arguments);return r(a,"mozAutoGainControl","autoGainControl"),r(a,"mozNoiseSuppression","noiseSuppression"),a}}if(n&&n.prototype.applyConstraints){const s=n.prototype.applyConstraints;n.prototype.applyConstraints=function(a){return this.kind==="audio"&&typeof a=="object"&&(a=JSON.parse(JSON.stringify(a)),r(a,"autoGainControl","mozAutoGainControl"),r(a,"noiseSuppression","mozNoiseSuppression")),s.apply(this,[a])}}}}function ZR(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function L_(t,e){if(typeof t!="object"||!t.RTCPeerConnection&&!t.mozRTCPeerConnection)return;!t.RTCPeerConnection&&t.mozRTCPeerConnection&&(t.RTCPeerConnection=t.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(r){const o=t.RTCPeerConnection.prototype[r],s={[r](){return arguments[0]=new(r==="addIceCandidate"?t.RTCIceCandidate:t.RTCSessionDescription)(arguments[0]),o.apply(this,arguments)}};t.RTCPeerConnection.prototype[r]=s[r]});const i={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},n=t.RTCPeerConnection.prototype.getStats;t.RTCPeerConnection.prototype.getStats=function(){const[r,o,s]=arguments;return n.apply(this,[r||null]).then(a=>{if(e.version<53&&!o)try{a.forEach(c=>{c.type=i[c.type]||c.type})}catch(c){if(c.name!=="TypeError")throw c;a.forEach((d,l)=>{a.set(l,Object.assign({},d,{type:i[d.type]||d.type}))})}return a}).then(o,s)}}function $R(t){if(typeof t!="object"||!t.RTCPeerConnection||!t.RTCRtpSender||t.RTCRtpSender&&"getStats"in t.RTCRtpSender.prototype)return;const e=t.RTCPeerConnection.prototype.getSenders;e&&(t.RTCPeerConnection.prototype.getSenders=function(){const n=e.apply(this,[]);return n.forEach(r=>r._pc=this),n});const i=t.RTCPeerConnection.prototype.addTrack;i&&(t.RTCPeerConnection.prototype.addTrack=function(){const n=i.apply(this,arguments);return n._pc=this,n}),t.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):K.resolve(new Map)}}function tv(t){if(typeof t!="object"||!t.RTCPeerConnection||!t.RTCRtpSender||t.RTCRtpSender&&"getStats"in t.RTCRtpReceiver.prototype)return;const e=t.RTCPeerConnection.prototype.getReceivers;e&&(t.RTCPeerConnection.prototype.getReceivers=function(){const i=e.apply(this,[]);return i.forEach(n=>n._pc=this),i}),Ko(t,"track",i=>(i.receiver._pc=i.srcElement,i)),t.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ev(t){t.RTCPeerConnection&&!("removeStream"in t.RTCPeerConnection.prototype)&&(t.RTCPeerConnection.prototype.removeStream=function(e){N_("removeStream","removeTrack"),this.getSenders().forEach(i=>{var n;i.track&&G(n=e.getTracks()).call(n,i.track)&&this.removeTrack(i)})})}function iv(t){t.DataChannel&&!t.RTCDataChannel&&(t.RTCDataChannel=t.DataChannel)}function nv(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.addTransceiver;e&&(t.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let i=arguments[1]&&arguments[1].sendEncodings;i===void 0&&(i=[]),i=[...i];const n=i.length>0;n&&i.forEach(o=>{if("rid"in o&&!/^[a-z0-9]{0,16}$/i.test(o.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in o&&!(parseFloat(o.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in o&&!(parseFloat(o.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const r=e.apply(this,arguments);if(n){const{sender:o}=r,s=o.getParameters();(!("encodings"in s)||s.encodings.length===1&&Object.keys(s.encodings[0]).length===0)&&(s.encodings=i,o.sendEncodings=i,this.setParametersPromises.push(o.setParameters(s).then(()=>{delete o.sendEncodings}).catch(()=>{delete o.sendEncodings})))}return r})}function rv(t){if(typeof t!="object"||!t.RTCRtpSender)return;const e=t.RTCRtpSender.prototype.getParameters;e&&(t.RTCRtpSender.prototype.getParameters=function(){const i=e.apply(this,arguments);return"encodings"in i||(i.encodings=[].concat(this.sendEncodings||[{}])),i})}function ov(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?K.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function sv(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype.createAnswer;t.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?K.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var av=Object.freeze({__proto__:null,shimAddTransceiver:nv,shimCreateAnswer:sv,shimCreateOffer:ov,shimGetDisplayMedia:function(t,e){t.navigator.mediaDevices&&"getDisplayMedia"in t.navigator.mediaDevices||t.navigator.mediaDevices&&(t.navigator.mediaDevices.getDisplayMedia=function(i){if(!i||!i.video){const n=new DOMException("getDisplayMedia without video constraints is undefined");return n.name="NotFoundError",n.code=8,K.reject(n)}return i.video===!0?i.video={mediaSource:e}:i.video.mediaSource=e,t.navigator.mediaDevices.getUserMedia(i)})},shimGetParameters:rv,shimGetUserMedia:QR,shimOnTrack:ZR,shimPeerConnection:L_,shimRTCDataChannel:iv,shimReceiverGetStats:tv,shimRemoveStream:ev,shimSenderGetStats:$R});function cv(t){if(typeof t=="object"&&t.RTCPeerConnection){if("getLocalStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in t.RTCPeerConnection.prototype)){const e=t.RTCPeerConnection.prototype.addTrack;t.RTCPeerConnection.prototype.addStream=function(i){var n;this._localStreams||(this._localStreams=[]),G(n=this._localStreams).call(n,i)||this._localStreams.push(i),i.getAudioTracks().forEach(r=>e.call(this,r,i)),i.getVideoTracks().forEach(r=>e.call(this,r,i))},t.RTCPeerConnection.prototype.addTrack=function(i){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return r&&r.forEach(s=>{var a;this._localStreams?G(a=this._localStreams).call(a,s)||this._localStreams.push(s):this._localStreams=[s]}),e.apply(this,arguments)}}"removeStream"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const i=this._localStreams.indexOf(e);if(i===-1)return;this._localStreams.splice(i,1);const n=e.getTracks();this.getSenders().forEach(r=>{G(n).call(n,r.track)&&this.removeTrack(r)})})}}function dv(t){if(typeof t=="object"&&t.RTCPeerConnection&&("getRemoteStreams"in t.RTCPeerConnection.prototype||(t.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in t.RTCPeerConnection.prototype))){Object.defineProperty(t.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(i){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=i),this.addEventListener("track",this._onaddstreampoly=n=>{n.streams.forEach(r=>{var o;if(this._remoteStreams||(this._remoteStreams=[]),G(o=this._remoteStreams).call(o,r))return;this._remoteStreams.push(r);const s=new Event("addstream");s.stream=r,this.dispatchEvent(s)})})}});const e=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){const i=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(n){n.streams.forEach(r=>{if(i._remoteStreams||(i._remoteStreams=[]),i._remoteStreams.indexOf(r)>=0)return;i._remoteStreams.push(r);const o=new Event("addstream");o.stream=r,i.dispatchEvent(o)})}),e.apply(i,arguments)}}}function lv(t){if(typeof t!="object"||!t.RTCPeerConnection)return;const e=t.RTCPeerConnection.prototype,i=e.createOffer,n=e.createAnswer,r=e.setLocalDescription,o=e.setRemoteDescription,s=e.addIceCandidate;e.createOffer=function(c,d){const l=arguments.length>=2?arguments[2]:arguments[0],u=i.apply(this,[l]);return d?(u.then(c,d),K.resolve()):u},e.createAnswer=function(c,d){const l=arguments.length>=2?arguments[2]:arguments[0],u=n.apply(this,[l]);return d?(u.then(c,d),K.resolve()):u};let a=function(c,d,l){const u=r.apply(this,[c]);return l?(u.then(d,l),K.resolve()):u};e.setLocalDescription=a,a=function(c,d,l){const u=o.apply(this,[c]);return l?(u.then(d,l),K.resolve()):u},e.setRemoteDescription=a,a=function(c,d,l){const u=s.apply(this,[c]);return l?(u.then(d,l),K.resolve()):u},e.addIceCandidate=a}function uv(t){const e=t&&t.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const i=e.mediaDevices,n=i.getUserMedia.bind(i);e.mediaDevices.getUserMedia=r=>n(hv(r))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(i,n,r){e.mediaDevices.getUserMedia(i).then(n,r)}.bind(e))}function hv(t){return t&&t.video!==void 0?Object.assign({},t,{video:VR(t.video)}):t}function pv(t){if(!t.RTCPeerConnection)return;const e=t.RTCPeerConnection;t.RTCPeerConnection=function(i,n){if(i&&i.iceServers){const r=[];for(let o=0;o<i.iceServers.length;o++){let s=i.iceServers[o];!s.hasOwnProperty("urls")&&s.hasOwnProperty("url")?(N_("RTCIceServer.url","RTCIceServer.urls"),s=JSON.parse(JSON.stringify(s)),s.urls=s.url,delete s.url,r.push(s)):r.push(i.iceServers[o])}i.iceServers=r}return new e(i,n)},t.RTCPeerConnection.prototype=e.prototype,"generateCertificate"in e&&Object.defineProperty(t.RTCPeerConnection,"generateCertificate",{get:()=>e.generateCertificate})}function _v(t){typeof t=="object"&&t.RTCTrackEvent&&"receiver"in t.RTCTrackEvent.prototype&&!("transceiver"in t.RTCTrackEvent.prototype)&&Object.defineProperty(t.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ev(t){const e=t.RTCPeerConnection.prototype.createOffer;t.RTCPeerConnection.prototype.createOffer=function(i){if(i){i.offerToReceiveAudio!==void 0&&(i.offerToReceiveAudio=!!i.offerToReceiveAudio);const n=this.getTransceivers().find(o=>o.receiver.track.kind==="audio");i.offerToReceiveAudio===!1&&n?n.direction==="sendrecv"?n.setDirection?n.setDirection("sendonly"):n.direction="sendonly":n.direction==="recvonly"&&(n.setDirection?n.setDirection("inactive"):n.direction="inactive"):i.offerToReceiveAudio!==!0||n||this.addTransceiver("audio",{direction:"recvonly"}),i.offerToReceiveVideo!==void 0&&(i.offerToReceiveVideo=!!i.offerToReceiveVideo);const r=this.getTransceivers().find(o=>o.receiver.track.kind==="video");i.offerToReceiveVideo===!1&&r?r.direction==="sendrecv"?r.setDirection?r.setDirection("sendonly"):r.direction="sendonly":r.direction==="recvonly"&&(r.setDirection?r.setDirection("inactive"):r.direction="inactive"):i.offerToReceiveVideo!==!0||r||this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function mv(t){typeof t!="object"||t.AudioContext||(t.AudioContext=t.webkitAudioContext)}var fv=Object.freeze({__proto__:null,shimAudioContext:mv,shimCallbacksAPI:lv,shimConstraints:hv,shimCreateOfferLegacy:Ev,shimGetUserMedia:uv,shimLocalStreamsAPI:cv,shimRTCIceServerUrls:pv,shimRemoteStreamsAPI:dv,shimTrackEventTransceiver:_v}),gv=`
\v\f\r    \u2028\u2029\uFEFF`,eF=ko,iF=Ki,k_=gv,Sv=de("".replace),nF=RegExp("^["+k_+"]+"),rF=RegExp("(^|[^"+k_+"])["+k_+"]+$"),M_=function(t){return function(e){var i=iF(eF(e));return 1&t&&(i=Sv(i,nF,"")),2&t&&(i=Sv(i,rF,"$1")),i}},oF={start:M_(1),end:M_(2),trim:M_(3)},sF=eS.PROPER,aF=Lt,Tv=gv,cF=oF.trim;Nt({target:"String",proto:!0,forced:function(t){return aF(function(){return!!Tv[t]()||"…"[t]()!=="…"||sF&&Tv[t].name!==t})}("trim")},{trim:function(){return cF(this)}});var dF=Sn("String","trim"),lF=$e,uF=dF,U_=String.prototype,hF=function(t){var e=t.trim;return typeof t=="string"||t===U_||lF(U_,t)&&e===U_.trim?uF:e},ni=Pt(hF),Rv={exports:{}};(function(t){const e={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};e.localCName=e.generateIdentifier(),e.splitLines=function(i){return i.trim().split(`
`).map(n=>n.trim())},e.splitSections=function(i){return i.split(`
m=`).map((n,r)=>(r>0?"m="+n:n).trim()+`\r
`)},e.getDescription=function(i){const n=e.splitSections(i);return n&&n[0]},e.getMediaSections=function(i){const n=e.splitSections(i);return n.shift(),n},e.matchPrefix=function(i,n){return e.splitLines(i).filter(r=>r.indexOf(n)===0)},e.parseCandidate=function(i){let n;n=i.indexOf("a=candidate:")===0?i.substring(12).split(" "):i.substring(10).split(" ");const r={foundation:n[0],component:{1:"rtp",2:"rtcp"}[n[1]]||n[1],protocol:n[2].toLowerCase(),priority:parseInt(n[3],10),ip:n[4],address:n[4],port:parseInt(n[5],10),type:n[7]};for(let o=8;o<n.length;o+=2)switch(n[o]){case"raddr":r.relatedAddress=n[o+1];break;case"rport":r.relatedPort=parseInt(n[o+1],10);break;case"tcptype":r.tcpType=n[o+1];break;case"ufrag":r.ufrag=n[o+1],r.usernameFragment=n[o+1];break;default:r[n[o]]===void 0&&(r[n[o]]=n[o+1])}return r},e.writeCandidate=function(i){const n=[];n.push(i.foundation);const r=i.component;r==="rtp"?n.push(1):r==="rtcp"?n.push(2):n.push(r),n.push(i.protocol.toUpperCase()),n.push(i.priority),n.push(i.address||i.ip),n.push(i.port);const o=i.type;return n.push("typ"),n.push(o),o!=="host"&&i.relatedAddress&&i.relatedPort&&(n.push("raddr"),n.push(i.relatedAddress),n.push("rport"),n.push(i.relatedPort)),i.tcpType&&i.protocol.toLowerCase()==="tcp"&&(n.push("tcptype"),n.push(i.tcpType)),(i.usernameFragment||i.ufrag)&&(n.push("ufrag"),n.push(i.usernameFragment||i.ufrag)),"candidate:"+n.join(" ")},e.parseIceOptions=function(i){return i.substring(14).split(" ")},e.parseRtpMap=function(i){let n=i.substring(9).split(" ");const r={payloadType:parseInt(n.shift(),10)};return n=n[0].split("/"),r.name=n[0],r.clockRate=parseInt(n[1],10),r.channels=n.length===3?parseInt(n[2],10):1,r.numChannels=r.channels,r},e.writeRtpMap=function(i){let n=i.payloadType;i.preferredPayloadType!==void 0&&(n=i.preferredPayloadType);const r=i.channels||i.numChannels||1;return"a=rtpmap:"+n+" "+i.name+"/"+i.clockRate+(r!==1?"/"+r:"")+`\r
`},e.parseExtmap=function(i){const n=i.substring(9).split(" ");return{id:parseInt(n[0],10),direction:n[0].indexOf("/")>0?n[0].split("/")[1]:"sendrecv",uri:n[1],attributes:n.slice(2).join(" ")}},e.writeExtmap=function(i){return"a=extmap:"+(i.id||i.preferredId)+(i.direction&&i.direction!=="sendrecv"?"/"+i.direction:"")+" "+i.uri+(i.attributes?" "+i.attributes:"")+`\r
`},e.parseFmtp=function(i){const n={};let r;const o=i.substring(i.indexOf(" ")+1).split(";");for(let s=0;s<o.length;s++)r=o[s].trim().split("="),n[r[0].trim()]=r[1];return n},e.writeFmtp=function(i){let n="",r=i.payloadType;if(i.preferredPayloadType!==void 0&&(r=i.preferredPayloadType),i.parameters&&Object.keys(i.parameters).length){const o=[];Object.keys(i.parameters).forEach(s=>{i.parameters[s]!==void 0?o.push(s+"="+i.parameters[s]):o.push(s)}),n+="a=fmtp:"+r+" "+o.join(";")+`\r
`}return n},e.parseRtcpFb=function(i){const n=i.substring(i.indexOf(" ")+1).split(" ");return{type:n.shift(),parameter:n.join(" ")}},e.writeRtcpFb=function(i){let n="",r=i.payloadType;return i.preferredPayloadType!==void 0&&(r=i.preferredPayloadType),i.rtcpFeedback&&i.rtcpFeedback.length&&i.rtcpFeedback.forEach(o=>{n+="a=rtcp-fb:"+r+" "+o.type+(o.parameter&&o.parameter.length?" "+o.parameter:"")+`\r
`}),n},e.parseSsrcMedia=function(i){const n=i.indexOf(" "),r={ssrc:parseInt(i.substring(7,n),10)},o=i.indexOf(":",n);return o>-1?(r.attribute=i.substring(n+1,o),r.value=i.substring(o+1)):r.attribute=i.substring(n+1),r},e.parseSsrcGroup=function(i){const n=i.substring(13).split(" ");return{semantics:n.shift(),ssrcs:n.map(r=>parseInt(r,10))}},e.getMid=function(i){const n=e.matchPrefix(i,"a=mid:")[0];if(n)return n.substring(6)},e.parseFingerprint=function(i){const n=i.substring(14).split(" ");return{algorithm:n[0].toLowerCase(),value:n[1].toUpperCase()}},e.getDtlsParameters=function(i,n){return{role:"auto",fingerprints:e.matchPrefix(i+n,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(i,n){let r="a=setup:"+n+`\r
`;return i.fingerprints.forEach(o=>{r+="a=fingerprint:"+o.algorithm+" "+o.value+`\r
`}),r},e.parseCryptoLine=function(i){const n=i.substring(9).split(" ");return{tag:parseInt(n[0],10),cryptoSuite:n[1],keyParams:n[2],sessionParams:n.slice(3)}},e.writeCryptoLine=function(i){return"a=crypto:"+i.tag+" "+i.cryptoSuite+" "+(typeof i.keyParams=="object"?e.writeCryptoKeyParams(i.keyParams):i.keyParams)+(i.sessionParams?" "+i.sessionParams.join(" "):"")+`\r
`},e.parseCryptoKeyParams=function(i){if(i.indexOf("inline:")!==0)return null;const n=i.substring(7).split("|");return{keyMethod:"inline",keySalt:n[0],lifeTime:n[1],mkiValue:n[2]?n[2].split(":")[0]:void 0,mkiLength:n[2]?n[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(i){return i.keyMethod+":"+i.keySalt+(i.lifeTime?"|"+i.lifeTime:"")+(i.mkiValue&&i.mkiLength?"|"+i.mkiValue+":"+i.mkiLength:"")},e.getCryptoParameters=function(i,n){return e.matchPrefix(i+n,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(i,n){const r=e.matchPrefix(i+n,"a=ice-ufrag:")[0],o=e.matchPrefix(i+n,"a=ice-pwd:")[0];return r&&o?{usernameFragment:r.substring(12),password:o.substring(10)}:null},e.writeIceParameters=function(i){let n="a=ice-ufrag:"+i.usernameFragment+`\r
a=ice-pwd:`+i.password+`\r
`;return i.iceLite&&(n+=`a=ice-lite\r
`),n},e.parseRtpParameters=function(i){const n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=e.splitLines(i)[0].split(" ");n.profile=r[2];for(let s=3;s<r.length;s++){const a=r[s],c=e.matchPrefix(i,"a=rtpmap:"+a+" ")[0];if(c){const d=e.parseRtpMap(c),l=e.matchPrefix(i,"a=fmtp:"+a+" ");switch(d.parameters=l.length?e.parseFmtp(l[0]):{},d.rtcpFeedback=e.matchPrefix(i,"a=rtcp-fb:"+a+" ").map(e.parseRtcpFb),n.codecs.push(d),d.name.toUpperCase()){case"RED":case"ULPFEC":n.fecMechanisms.push(d.name.toUpperCase())}}}e.matchPrefix(i,"a=extmap:").forEach(s=>{n.headerExtensions.push(e.parseExtmap(s))});const o=e.matchPrefix(i,"a=rtcp-fb:* ").map(e.parseRtcpFb);return n.codecs.forEach(s=>{o.forEach(a=>{s.rtcpFeedback.find(c=>c.type===a.type&&c.parameter===a.parameter)||s.rtcpFeedback.push(a)})}),n},e.writeRtpDescription=function(i,n){let r="";r+="m="+i+" ",r+=n.codecs.length>0?"9":"0",r+=" "+(n.profile||"UDP/TLS/RTP/SAVPF")+" ",r+=n.codecs.map(s=>s.preferredPayloadType!==void 0?s.preferredPayloadType:s.payloadType).join(" ")+`\r
`,r+=`c=IN IP4 0.0.0.0\r
`,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
`,n.codecs.forEach(s=>{r+=e.writeRtpMap(s),r+=e.writeFmtp(s),r+=e.writeRtcpFb(s)});let o=0;return n.codecs.forEach(s=>{s.maxptime>o&&(o=s.maxptime)}),o>0&&(r+="a=maxptime:"+o+`\r
`),n.headerExtensions&&n.headerExtensions.forEach(s=>{r+=e.writeExtmap(s)}),r},e.parseRtpEncodingParameters=function(i){const n=[],r=e.parseRtpParameters(i),o=r.fecMechanisms.indexOf("RED")!==-1,s=r.fecMechanisms.indexOf("ULPFEC")!==-1,a=e.matchPrefix(i,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="cname"),c=a.length>0&&a[0].ssrc;let d;const l=e.matchPrefix(i,"a=ssrc-group:FID").map(h=>h.substring(17).split(" ").map(p=>parseInt(p,10)));l.length>0&&l[0].length>1&&l[0][0]===c&&(d=l[0][1]),r.codecs.forEach(h=>{if(h.name.toUpperCase()==="RTX"&&h.parameters.apt){let p={ssrc:c,codecPayloadType:parseInt(h.parameters.apt,10)};c&&d&&(p.rtx={ssrc:d}),n.push(p),o&&(p=JSON.parse(JSON.stringify(p)),p.fec={ssrc:c,mechanism:s?"red+ulpfec":"red"},n.push(p))}}),n.length===0&&c&&n.push({ssrc:c});let u=e.matchPrefix(i,"b=");return u.length&&(u=u[0].indexOf("b=TIAS:")===0?parseInt(u[0].substring(7),10):u[0].indexOf("b=AS:")===0?1e3*parseInt(u[0].substring(5),10)*.95-16e3:void 0,n.forEach(h=>{h.maxBitrate=u})),n},e.parseRtcpParameters=function(i){const n={},r=e.matchPrefix(i,"a=ssrc:").map(a=>e.parseSsrcMedia(a)).filter(a=>a.attribute==="cname")[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);const o=e.matchPrefix(i,"a=rtcp-rsize");n.reducedSize=o.length>0,n.compound=o.length===0;const s=e.matchPrefix(i,"a=rtcp-mux");return n.mux=s.length>0,n},e.writeRtcpParameters=function(i){let n="";return i.reducedSize&&(n+=`a=rtcp-rsize\r
`),i.mux&&(n+=`a=rtcp-mux\r
`),i.ssrc!==void 0&&i.cname&&(n+="a=ssrc:"+i.ssrc+" cname:"+i.cname+`\r
`),n},e.parseMsid=function(i){let n;const r=e.matchPrefix(i,"a=msid:");if(r.length===1)return n=r[0].substring(7).split(" "),{stream:n[0],track:n[1]};const o=e.matchPrefix(i,"a=ssrc:").map(s=>e.parseSsrcMedia(s)).filter(s=>s.attribute==="msid");return o.length>0?(n=o[0].value.split(" "),{stream:n[0],track:n[1]}):void 0},e.parseSctpDescription=function(i){const n=e.parseMLine(i),r=e.matchPrefix(i,"a=max-message-size:");let o;r.length>0&&(o=parseInt(r[0].substring(19),10)),isNaN(o)&&(o=65536);const s=e.matchPrefix(i,"a=sctp-port:");if(s.length>0)return{port:parseInt(s[0].substring(12),10),protocol:n.fmt,maxMessageSize:o};const a=e.matchPrefix(i,"a=sctpmap:");if(a.length>0){const c=a[0].substring(10).split(" ");return{port:parseInt(c[0],10),protocol:c[1],maxMessageSize:o}}},e.writeSctpDescription=function(i,n){let r=[];return r=i.protocol!=="DTLS/SCTP"?["m="+i.kind+" 9 "+i.protocol+" "+n.protocol+`\r
`,`c=IN IP4 0.0.0.0\r
`,"a=sctp-port:"+n.port+`\r
`]:["m="+i.kind+" 9 "+i.protocol+" "+n.port+`\r
`,`c=IN IP4 0.0.0.0\r
`,"a=sctpmap:"+n.port+" "+n.protocol+` 65535\r
`],n.maxMessageSize!==void 0&&r.push("a=max-message-size:"+n.maxMessageSize+`\r
`),r.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(i,n,r){let o;const s=n!==void 0?n:2;return o=i||e.generateSessionId(),`v=0\r
o=`+(r||"thisisadapterortc")+" "+o+" "+s+` IN IP4 127.0.0.1\r
s=-\r
t=0 0\r
`},e.getDirection=function(i,n){const r=e.splitLines(i);for(let o=0;o<r.length;o++)switch(r[o]){case"a=sendrecv":case"a=sendonly":case"a=recvonly":case"a=inactive":return r[o].substring(2)}return n?e.getDirection(n):"sendrecv"},e.getKind=function(i){return e.splitLines(i)[0].split(" ")[0].substring(2)},e.isRejected=function(i){return i.split(" ",2)[1]==="0"},e.parseMLine=function(i){const n=e.splitLines(i)[0].substring(2).split(" ");return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(" ")}},e.parseOLine=function(i){const n=e.matchPrefix(i,"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]}},e.isValidSDP=function(i){if(typeof i!="string"||i.length===0)return!1;const n=e.splitLines(i);for(let r=0;r<n.length;r++)if(n[r].length<2||n[r].charAt(1)!=="=")return!1;return!0},t.exports=e})(Rv);var vv=Rv.exports,Xs=Pt(vv),pF=Ai({__proto__:null,default:Xs},[vv]);function yl(t){if(!t.RTCIceCandidate||t.RTCIceCandidate&&"foundation"in t.RTCIceCandidate.prototype)return;const e=t.RTCIceCandidate;t.RTCIceCandidate=function(i){if(typeof i=="object"&&i.candidate&&i.candidate.indexOf("a=")===0&&((i=JSON.parse(JSON.stringify(i))).candidate=i.candidate.substr(2)),i.candidate&&i.candidate.length){const n=new e(i),r=Xs.parseCandidate(i.candidate),o=Object.assign(n,r);return o.toJSON=function(){return{candidate:o.candidate,sdpMid:o.sdpMid,sdpMLineIndex:o.sdpMLineIndex,usernameFragment:o.usernameFragment}},o}return new e(i)},t.RTCIceCandidate.prototype=e.prototype,Ko(t,"icecandidate",i=>(i.candidate&&Object.defineProperty(i,"candidate",{value:new t.RTCIceCandidate(i.candidate),writable:"false"}),i))}function x_(t){!t.RTCIceCandidate||t.RTCIceCandidate&&"relayProtocol"in t.RTCIceCandidate.prototype||Ko(t,"icecandidate",e=>{if(e.candidate){const i=Xs.parseCandidate(e.candidate.candidate);i.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[i.priority>>24])}return e})}function Il(t,e){if(!t.RTCPeerConnection)return;"sctp"in t.RTCPeerConnection.prototype||Object.defineProperty(t.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const i=function(a){if(!a||!a.sdp)return!1;const c=Xs.splitSections(a.sdp);return c.shift(),c.some(d=>{const l=Xs.parseMLine(d);return l&&l.kind==="application"&&l.protocol.indexOf("SCTP")!==-1})},n=function(a){const c=a.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(c===null||c.length<2)return-1;const d=parseInt(c[1],10);return d!=d?-1:d},r=function(a){let c=65536;return e.browser==="firefox"&&(c=e.version<57?a===-1?16384:2147483637:e.version<60?e.version===57?65535:65536:2147483637),c},o=function(a,c){let d=65536;e.browser==="firefox"&&e.version===57&&(d=65535);const l=Xs.matchPrefix(a.sdp,"a=max-message-size:");return l.length>0?d=parseInt(l[0].substr(19),10):e.browser==="firefox"&&c!==-1&&(d=2147483637),d},s=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(i(arguments[0])){const a=n(arguments[0]),c=r(a),d=o(arguments[0],a);let l;l=c===0&&d===0?Number.POSITIVE_INFINITY:c===0||d===0?Math.max(c,d):Math.min(c,d);const u={};Object.defineProperty(u,"maxMessageSize",{get:()=>l}),this._sctp=u}return s.apply(this,arguments)}}function Al(t){if(!t.RTCPeerConnection||!("createDataChannel"in t.RTCPeerConnection.prototype))return;function e(n,r){const o=n.send;n.send=function(){const s=arguments[0],a=s.length||s.size||s.byteLength;if(n.readyState==="open"&&r.sctp&&a>r.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+r.sctp.maxMessageSize+" bytes)");return o.apply(n,arguments)}}const i=t.RTCPeerConnection.prototype.createDataChannel;t.RTCPeerConnection.prototype.createDataChannel=function(){const n=i.apply(this,arguments);return e(n,this),n},Ko(t,"datachannel",n=>(e(n.channel,n.target),n))}function V_(t){if(!t.RTCPeerConnection||"connectionState"in t.RTCPeerConnection.prototype)return;const e=t.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(i){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),i&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=i)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(i=>{const n=e[i];e[i]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=r=>{const o=r.target;if(o._lastConnectionState!==o.connectionState){o._lastConnectionState=o.connectionState;const s=new Event("connectionstatechange",r);o.dispatchEvent(s)}return r},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),n.apply(this,arguments)}})}function F_(t,e){if(!t.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e.version>=605)return;const i=t.RTCPeerConnection.prototype.setRemoteDescription;t.RTCPeerConnection.prototype.setRemoteDescription=function(n){if(n&&n.sdp&&n.sdp.indexOf(`
a=extmap-allow-mixed`)!==-1){const r=n.sdp.split(`
`).filter(o=>ni(o).call(o)!=="a=extmap-allow-mixed").join(`
`);t.RTCSessionDescription&&n instanceof t.RTCSessionDescription?arguments[0]=new t.RTCSessionDescription({type:n.type,sdp:r}):n.sdp=r}return i.apply(this,arguments)}}function bl(t,e){if(!t.RTCPeerConnection||!t.RTCPeerConnection.prototype)return;const i=t.RTCPeerConnection.prototype.addIceCandidate;i&&i.length!==0&&(t.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?K.resolve():i.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),K.resolve())})}function wl(t,e){if(!t.RTCPeerConnection||!t.RTCPeerConnection.prototype)return;const i=t.RTCPeerConnection.prototype.setLocalDescription;i&&i.length!==0&&(t.RTCPeerConnection.prototype.setLocalDescription=function(){let n=arguments[0]||{};if(typeof n!="object"||n.type&&n.sdp)return i.apply(this,arguments);if(n={type:n.type,sdp:n.sdp},!n.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":n.type="offer";break;default:n.type="answer"}return n.sdp||n.type!=="offer"&&n.type!=="answer"?i.apply(this,[n]):(n.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(r=>i.apply(this,[r]))})}var _F=Object.freeze({__proto__:null,removeExtmapAllowMixed:F_,shimAddIceCandidateNullOrEmpty:bl,shimConnectionState:V_,shimMaxMessageSize:Il,shimParameterlessSetLocalDescription:wl,shimRTCIceCandidate:yl,shimRTCIceCandidateRelayProtocol:x_,shimSendThrowTypeError:Al});(function(){let{window:t}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0};const i=UR,n=function(o){const s={browser:null,version:null};if(o===void 0||!o.navigator)return s.browser="Not a browser.",s;const{navigator:a}=o;if(a.mozGetUserMedia)s.browser="firefox",s.version=Cl(a.userAgent,/Firefox\/(\d+)\./,1);else if(a.webkitGetUserMedia||o.isSecureContext===!1&&o.webkitRTCPeerConnection)s.browser="chrome",s.version=Cl(a.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!o.RTCPeerConnection||!a.userAgent.match(/AppleWebKit\/(\d+)\./))return s.browser="Not a supported browser.",s;s.browser="safari",s.version=Cl(a.userAgent,/AppleWebKit\/(\d+)\./,1),s.supportsUnifiedPlan=o.RTCRtpTransceiver&&"currentDirection"in o.RTCRtpTransceiver.prototype}return s}(t),r={browserDetails:n,commonShim:_F,extractVersion:Cl,disableLog:$V,disableWarnings:tF,sdp:pF};switch(n.browser){case"chrome":if(!JR||!P_||!e.shimChrome)return i("Chrome shim is not included in this adapter release."),r;if(n.version===null)return i("Chrome shim can not determine version, not shimming."),r;i("adapter.js shimming chrome."),r.browserShim=JR,bl(t,n),wl(t),jR(t,n),GR(t),P_(t,n),WR(t),zR(t,n),HR(t),KR(t),YR(t),XR(t,n),yl(t),x_(t),V_(t),Il(t,n),Al(t),F_(t,n);break;case"firefox":if(!av||!L_||!e.shimFirefox)return i("Firefox shim is not included in this adapter release."),r;i("adapter.js shimming firefox."),r.browserShim=av,bl(t,n),wl(t),QR(t,n),L_(t,n),ZR(t),ev(t),$R(t),tv(t),iv(t),nv(t),rv(t),ov(t),sv(t),yl(t),V_(t),Il(t,n),Al(t);break;case"safari":if(!fv||!e.shimSafari)return i("Safari shim is not included in this adapter release."),r;i("adapter.js shimming safari."),r.browserShim=fv,bl(t,n),wl(t),pv(t),Ev(t),lv(t),cv(t),dv(t),_v(t),uv(t),mv(t),yl(t),x_(t),Il(t,n),Al(t),F_(t,n);break;default:i("Unsupported browser!")}})({window:typeof window=="undefined"?void 0:window});var B_=ie;Nt({global:!0,forced:B_.globalThis!==B_},{globalThis:B_});var Cv=Pt(ie),j_={exports:{}};(function(t,e){(function(i,n){var r="function",o="undefined",s="object",a="string",c="major",d="model",l="name",u="type",h="vendor",p="version",g="architecture",m="console",f="mobile",T="tablet",R="smarttv",A="wearable",N="embedded",O="Amazon",w="Apple",L="ASUS",M="BlackBerry",j="Browser",H="Chrome",ht="Firefox",lt="Google",rt="Huawei",Kt="LG",Ft="Microsoft",Ii="Motorola",U="Opera",B="Samsung",X="Sharp",x="Sony",E="Xiaomi",I="Zebra",b="Facebook",F="Chromium OS",ct="Mac OS",Wt=" Browser",ye=function(Te){for(var Ie={},zt=0;zt<Te.length;zt++)Ie[Te[zt].toUpperCase()]=Te[zt];return Ie},mn=function(Te,Ie){return typeof Te===a&&jn(Ie).indexOf(jn(Te))!==-1},jn=function(Te){return Te.toLowerCase()},Rd=function(Te,Ie){if(typeof Te===a)return Te=Te.replace(/^\s\s*/,""),typeof Ie===o?Te:Te.substring(0,500)},Ss=function(Te,Ie){for(var zt,ki,or,pe,Qr,Tt,sr=0;sr<Ie.length&&!Qr;){var Ts=Ie[sr],Dr=Ie[sr+1];for(zt=ki=0;zt<Ts.length&&!Qr&&Ts[zt];)if(Qr=Ts[zt++].exec(Te))for(or=0;or<Dr.length;or++)Tt=Qr[++ki],typeof(pe=Dr[or])===s&&pe.length>0?pe.length===2?typeof pe[1]==r?this[pe[0]]=pe[1].call(this,Tt):this[pe[0]]=pe[1]:pe.length===3?typeof pe[1]!==r||pe[1].exec&&pe[1].test?this[pe[0]]=Tt?Tt.replace(pe[1],pe[2]):n:this[pe[0]]=Tt?pe[1].call(this,Tt,pe[2]):n:pe.length===4&&(this[pe[0]]=Tt?pe[3].call(this,Tt.replace(pe[1],pe[2])):n):this[pe]=Tt||n;sr+=2}},Ga=function(Te,Ie){for(var zt in Ie)if(typeof Ie[zt]===s&&Ie[zt].length>0){for(var ki=0;ki<Ie[zt].length;ki++)if(mn(Ie[zt][ki],Te))return zt==="?"?n:zt}else if(mn(Ie[zt],Te))return zt==="?"?n:zt;return Ie.hasOwnProperty("*")?Ie["*"]:Te},vh={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"},Ch={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[p,[l,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[p,[l,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/ ]+)([\w\.]+)/i],[l,p],[/opios[\/ ]+([\w\.]+)/i],[p,[l,U+" Mini"]],[/\bop(?:rg)?x\/([\w\.]+)/i],[p,[l,U+" GX"]],[/\bopr\/([\w\.]+)/i],[p,[l,U]],[/\bb[ai]*d(?:uhd|[ub]*[aekoprswx]{5,6})[\/ ]?([\w\.]+)/i],[p,[l,"Baidu"]],[/\b(?:mxbrowser|mxios|myie2)\/?([-\w\.]*)\b/i],[p,[l,"Maxthon"]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer|sleipnir)[\/ ]?([\w\.]*)/i,/(avant|iemobile|slim(?:browser|boat|jet))[\/ ]?([\d\.]*)/i,/(?:ms|\()(ie) ([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|qupzilla|falkon|rekonq|puffin|brave|whale(?!.+naver)|qqbrowserlite|duckduckgo|klar|helio|(?=comodo_)?dragon)\/([-\w\.]+)/i,/(heytap|ovi|115)browser\/([\d\.]+)/i,/(weibo)__([\d\.]+)/i],[l,p],[/quark(?:pc)?\/([-\w\.]+)/i],[p,[l,"Quark"]],[/\bddg\/([\w\.]+)/i],[p,[l,"DuckDuckGo"]],[/(?:\buc? ?browser|(?:juc.+)ucweb)[\/ ]?([\w\.]+)/i],[p,[l,"UC"+j]],[/microm.+\bqbcore\/([\w\.]+)/i,/\bqbcore\/([\w\.]+).+microm/i,/micromessenger\/([\w\.]+)/i],[p,[l,"WeChat"]],[/konqueror\/([\w\.]+)/i],[p,[l,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[p,[l,"IE"]],[/ya(?:search)?browser\/([\w\.]+)/i],[p,[l,"Yandex"]],[/slbrowser\/([\w\.]+)/i],[p,[l,"Smart Lenovo "+j]],[/(avast|avg)\/([\w\.]+)/i],[[l,/(.+)/,"$1 Secure "+j],p],[/\bfocus\/([\w\.]+)/i],[p,[l,ht+" Focus"]],[/\bopt\/([\w\.]+)/i],[p,[l,U+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[p,[l,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[p,[l,"Dolphin"]],[/coast\/([\w\.]+)/i],[p,[l,U+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[p,[l,"MIUI"+Wt]],[/fxios\/([\w\.-]+)/i],[p,[l,ht]],[/\bqihoobrowser\/?([\w\.]*)/i],[p,[l,"360"]],[/\b(qq)\/([\w\.]+)/i],[[l,/(.+)/,"$1Browser"],p],[/(oculus|sailfish|huawei|vivo|pico)browser\/([\w\.]+)/i],[[l,/(.+)/,"$1"+Wt],p],[/samsungbrowser\/([\w\.]+)/i],[p,[l,B+" Internet"]],[/metasr[\/ ]?([\d\.]+)/i],[p,[l,"Sogou Explorer"]],[/(sogou)mo\w+\/([\d\.]+)/i],[[l,"Sogou Mobile"],p],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|2345(?=browser|chrome|explorer))\w*[\/ ]?v?([\w\.]+)/i],[l,p],[/(lbbrowser|rekonq)/i,/\[(linkedin)app\]/i],[l],[/ome\/([\w\.]+) \w* ?(iron) saf/i,/ome\/([\w\.]+).+qihu (360)[es]e/i],[p,l],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[l,b],p],[/(Klarna)\/([\w\.]+)/i,/(kakao(?:talk|story))[\/ ]([\w\.]+)/i,/(naver)\(.*?(\d+\.[\w\.]+).*\)/i,/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(alipay)client\/([\w\.]+)/i,/(twitter)(?:and| f.+e\/([\w\.]+))/i,/(chromium|instagram|snapchat)[\/ ]([-\w\.]+)/i],[l,p],[/\bgsa\/([\w\.]+) .*safari\//i],[p,[l,"GSA"]],[/musical_ly(?:.+app_?version\/|_)([\w\.]+)/i],[p,[l,"TikTok"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[p,[l,H+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[l,H+" WebView"],p],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[p,[l,"Android "+j]],[/(chrome|omniweb|arora|[tizenoka]{5} ?browser)\/v?([\w\.]+)/i],[l,p],[/version\/([\w\.\,]+) .*mobile\/\w+ (safari)/i],[p,[l,"Mobile Safari"]],[/version\/([\w(\.|\,)]+) .*(mobile ?safari|safari)/i],[p,l],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[l,[p,Ga,{"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],[l,p],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[l,"Netscape"],p],[/(wolvic|librewolf)\/([\w\.]+)/i],[l,p],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[p,[l,ht+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror)[\/ ]?([\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|obigo|mosaic|(?:go|ice|up)[\. ]?browser)[-\/ ]?v?([\w\.]+)/i,/(links) \(([\w\.]+)/i],[l,[p,/_/g,"."]],[/(cobalt)\/([\w\.]+)/i],[l,[p,/master.|lts./,""]]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[g,"amd64"]],[/(ia32(?=;))/i],[[g,jn]],[/((?:i[346]|x)86)[;\)]/i],[[g,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[g,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[g,"armhf"]],[/windows (ce|mobile); ppc;/i],[[g,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[g,/ower/,"",jn]],[/(sun4\w)[;\)]/i],[[g,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[g,jn]]],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],[d,[h,B],[u,T]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,/samsung[- ]((?!sm-[lr])[-\w]+)/i,/sec-(sgh\w+)/i],[d,[h,B],[u,f]],[/(?:\/|\()(ip(?:hone|od)[\w, ]*)(?:\/|;)/i],[d,[h,w],[u,f]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[d,[h,w],[u,T]],[/(macintosh);/i],[d,[h,w]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[d,[h,X],[u,f]],[/(?:honor)([-\w ]+)[;\)]/i],[d,[h,"Honor"],[u,f]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[d,[h,rt],[u,T]],[/(?:huawei)([-\w ]+)[;\)]/i,/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][012359c][adn]?)\b(?!.+d\/s)/i],[d,[h,rt],[u,f]],[/\b(poco[\w ]+|m2\d{3}j\d\d[a-z]{2})(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/oid[^\)]+; (m?[12][0-389][01]\w{3,6}[c-y])( bui|; wv|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max|cc)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite|pro)?)(?: bui|\))/i],[[d,/_/g," "],[h,E],[u,f]],[/oid[^\)]+; (2\d{4}(283|rpbf)[cgl])( bui|\))/i,/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[d,/_/g," "],[h,E],[u,T]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[d,[h,"OPPO"],[u,f]],[/\b(opd2\d{3}a?) bui/i],[d,[h,"OPPO"],[u,T]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[d,[h,"Vivo"],[u,f]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i],[d,[h,"Realme"],[u,f]],[/\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],[d,[h,Ii],[u,f]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[d,[h,Ii],[u,T]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[d,[h,Kt],[u,T]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/ ]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[d,[h,Kt],[u,f]],[/(ideatab[-\w ]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w ]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[d,[h,"Lenovo"],[u,T]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[d,/_/g," "],[h,"Nokia"],[u,f]],[/(pixel c)\b/i],[d,[h,lt],[u,T]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[d,[h,lt],[u,f]],[/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],[d,[h,x],[u,f]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[d,"Xperia Tablet"],[h,x],[u,T]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i],[d,[h,"OnePlus"],[u,f]],[/(alexa)webm/i,/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[d,[h,O],[u,T]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[d,/(.+)/g,"Fire Phone $1"],[h,O],[u,f]],[/(playbook);[-\w\),; ]+(rim)/i],[d,h,[u,T]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[d,[h,M],[u,f]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[d,[h,L],[u,T]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[d,[h,L],[u,f]],[/(nexus 9)/i],[d,[h,"HTC"],[u,T]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic(?!(?:;|\.))|sony(?!-bra))[-_ ]?([-\w]*)/i],[h,[d,/_/g," "],[u,f]],[/droid [\w\.]+; ((?:8[14]9[16]|9(?:0(?:48|60|8[01])|1(?:3[27]|66)|2(?:6[69]|9[56])|466))[gqswx])\w*(\)| bui)/i],[d,[h,"TCL"],[u,T]],[/(itel) ((\w+))/i],[[h,jn],d,[u,Ga,{tablet:["p10001l","w7001"],"*":"mobile"}]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[d,[h,"Acer"],[u,T]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[d,[h,"Meizu"],[u,f]],[/; ((?:power )?armor(?:[\w ]{0,8}))(?: bui|\))/i],[d,[h,"Ulefone"],[u,f]],[/; (energy ?\w+)(?: bui|\))/i,/; energizer ([\w ]+)(?: bui|\))/i],[d,[h,"Energizer"],[u,f]],[/; cat (b35);/i,/; (b15q?|s22 flip|s48c|s62 pro)(?: bui|\))/i],[d,[h,"Cat"],[u,f]],[/((?:new )?andromax[\w- ]+)(?: bui|\))/i],[d,[h,"Smartfren"],[u,f]],[/droid.+; (a(?:015|06[35]|142p?))/i],[d,[h,"Nothing"],[u,f]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron|infinix|tecno|micromax|advan)[-_ ]?([-\w]*)/i,/; (imo) ((?!tab)[\w ]+?)(?: bui|\))/i,/(hp) ([\w ]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w ]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo) ?([\w ]+) bui/i],[h,d,[u,f]],[/(imo) (tab \w+)/i,/(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],[h,d,[u,T]],[/(surface duo)/i],[d,[h,Ft],[u,T]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[d,[h,"Fairphone"],[u,f]],[/(u304aa)/i],[d,[h,"AT&T"],[u,f]],[/\bsie-(\w*)/i],[d,[h,"Siemens"],[u,f]],[/\b(rct\w+) b/i],[d,[h,"RCA"],[u,T]],[/\b(venue[\d ]{2,7}) b/i],[d,[h,"Dell"],[u,T]],[/\b(q(?:mv|ta)\w+) b/i],[d,[h,"Verizon"],[u,T]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+ ]*) b/i],[d,[h,"Barnes & Noble"],[u,T]],[/\b(tm\d{3}\w+) b/i],[d,[h,"NuVision"],[u,T]],[/\b(k88) b/i],[d,[h,"ZTE"],[u,T]],[/\b(nx\d{3}j) b/i],[d,[h,"ZTE"],[u,f]],[/\b(gen\d{3}) b.+49h/i],[d,[h,"Swiss"],[u,f]],[/\b(zur\d{3}) b/i],[d,[h,"Swiss"],[u,T]],[/\b((zeki)?tb.*\b) b/i],[d,[h,"Zeki"],[u,T]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[h,"Dragon Touch"],d,[u,T]],[/\b(ns-?\w{0,9}) b/i],[d,[h,"Insignia"],[u,T]],[/\b((nxa|next)-?\w{0,9}) b/i],[d,[h,"NextBook"],[u,T]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[h,"Voice"],d,[u,f]],[/\b(lvtel\-)?(v1[12]) b/i],[[h,"LvTel"],d,[u,f]],[/\b(ph-1) /i],[d,[h,"Essential"],[u,f]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[d,[h,"Envizen"],[u,T]],[/\b(trio[-\w\. ]+) b/i],[d,[h,"MachSpeed"],[u,T]],[/\btu_(1491) b/i],[d,[h,"Rotor"],[u,T]],[/(shield[\w ]+) b/i],[d,[h,"Nvidia"],[u,T]],[/(sprint) (\w+)/i],[h,d,[u,f]],[/(kin\.[onetw]{3})/i],[[d,/\./g," "],[h,Ft],[u,f]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[d,[h,I],[u,T]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[d,[h,I],[u,f]],[/smart-tv.+(samsung)/i],[h,[u,R]],[/hbbtv.+maple;(\d+)/i],[[d,/^/,"SmartTV"],[h,B],[u,R]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[h,Kt],[u,R]],[/(apple) ?tv/i],[h,[d,w+" TV"],[u,R]],[/crkey/i],[[d,H+"cast"],[h,lt],[u,R]],[/droid.+aft(\w+)( bui|\))/i],[d,[h,O],[u,R]],[/\(dtv[\);].+(aquos)/i,/(aquos-tv[\w ]+)\)/i],[d,[h,X],[u,R]],[/(bravia[\w ]+)( bui|\))/i],[d,[h,x],[u,R]],[/(mitv-\w{5}) bui/i],[d,[h,E],[u,R]],[/Hbbtv.*(technisat) (.*);/i],[h,d,[u,R]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)/i],[[h,Rd],[d,Rd],[u,R]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,R]],[/(ouya)/i,/(nintendo) ([wids3utch]+)/i],[h,d,[u,m]],[/droid.+; (shield) bui/i],[d,[h,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[d,[h,x],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[d,[h,Ft],[u,m]],[/\b(sm-[lr]\d\d[05][fnuw]?s?)\b/i],[d,[h,B],[u,A]],[/((pebble))app/i],[h,d,[u,A]],[/(watch)(?: ?os[,\/]|\d,\d\/)[\d\.]+/i],[d,[h,w],[u,A]],[/droid.+; (glass) \d/i],[d,[h,lt],[u,A]],[/droid.+; (wt63?0{2,3})\)/i],[d,[h,I],[u,A]],[/droid.+; (glass) \d/i],[d,[h,lt],[u,A]],[/(pico) (4|neo3(?: link|pro)?)/i],[h,d,[u,A]],[/; (quest( \d| pro)?)/i],[d,[h,b],[u,A]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[h,[u,N]],[/(aeobc)\b/i],[d,[h,O],[u,N]],[/droid .+?; ([^;]+?)(?: bui|; wv\)|\) applew).+? mobile safari/i],[d,[u,f]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[d,[u,T]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,T]],[/(phone|mobile(?:[;\/]| [ \w\/\.]*safari)|pda(?=.+windows ce))/i],[[u,f]],[/(android[-\w\. ]{0,9});.+buil/i],[d,[h,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[p,[l,"EdgeHTML"]],[/(arkweb)\/([\w\.]+)/i],[l,p],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[p,[l,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna|servo)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/ ]\(?([\w\.]+)/i,/(icab)[\/ ]([23]\.[\d\.]+)/i,/\b(libweb)/i],[l,p],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[p,l]],os:[[/microsoft (windows) (vista|xp)/i],[l,p],[/(windows (?:phone(?: os)?|mobile))[\/ ]?([\d\.\w ]*)/i],[l,[p,Ga,vh]],[/windows nt 6\.2; (arm)/i,/windows[\/ ]?([ntce\d\. ]+\w)(?!.+xbox)/i,/(?:win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[p,Ga,vh],[l,"Windows"]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/(?:ios;fbsv\/|iphone.+ios[\/ ])([\d\.]+)/i,/cfnetwork\/.+darwin/i],[[p,/_/g,"."],[l,"iOS"]],[/(mac os x) ?([\w\. ]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[l,ct],[p,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86|harmonyos)/i],[p,l],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish|openharmony)[-\/ ]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/ ]([\w\.]+)/i,/\((series40);/i],[l,p],[/\(bb(10);/i],[p,[l,M]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/ ]?([\w\.]*)/i],[p,[l,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w ]+); rv:.+ gecko\/([\w\.]+)/i],[p,[l,ht+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[p,[l,"webOS"]],[/watch(?: ?os[,\/]|\d,\d\/)([\d\.]+)/i],[p,[l,"watchOS"]],[/crkey\/([\d\.]+)/i],[p,[l,H+"cast"]],[/(cros) [\w]+(?:\)| ([\w\.]+)\b)/i],[[l,F],p],[/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],[l,p],[/(sunos) ?([\w\.\d]*)/i],[[l,"Solaris"],p],[/((?:open)?solaris)[-\/ ]?([\w\.]*)/i,/(aix) ((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux|serenityos)/i,/(unix) ?([\w\.]*)/i],[l,p]]},fn=function(Te,Ie){if(typeof Te===s&&(Ie=Te,Te=n),!(this instanceof fn))return new fn(Te,Ie).getResult();var zt=typeof i!==o&&i.navigator?i.navigator:n,ki=Te||(zt&&zt.userAgent?zt.userAgent:""),or=zt&&zt.userAgentData?zt.userAgentData:n,pe=Ie?function(Tt,sr){var Ts={};for(var Dr in Tt)sr[Dr]&&sr[Dr].length%2==0?Ts[Dr]=sr[Dr].concat(Tt[Dr]):Ts[Dr]=Tt[Dr];return Ts}(Ch,Ie):Ch,Qr=zt&&zt.userAgent==ki;return this.getBrowser=function(){var Tt={};return Tt[l]=n,Tt[p]=n,Ss.call(Tt,ki,pe.browser),Tt[c]=function(sr){return typeof sr===a?sr.replace(/[^\d\.]/g,"").split(".")[0]:n}(Tt[p]),Qr&&zt&&zt.brave&&typeof zt.brave.isBrave==r&&(Tt[l]="Brave"),Tt},this.getCPU=function(){var Tt={};return Tt[g]=n,Ss.call(Tt,ki,pe.cpu),Tt},this.getDevice=function(){var Tt={};return Tt[h]=n,Tt[d]=n,Tt[u]=n,Ss.call(Tt,ki,pe.device),Qr&&!Tt[u]&&or&&or.mobile&&(Tt[u]=f),Qr&&Tt[d]=="Macintosh"&&zt&&typeof zt.standalone!==o&&zt.maxTouchPoints&&zt.maxTouchPoints>2&&(Tt[d]="iPad",Tt[u]=T),Tt},this.getEngine=function(){var Tt={};return Tt[l]=n,Tt[p]=n,Ss.call(Tt,ki,pe.engine),Tt},this.getOS=function(){var Tt={};return Tt[l]=n,Tt[p]=n,Ss.call(Tt,ki,pe.os),Qr&&!Tt[l]&&or&&or.platform&&or.platform!="Unknown"&&(Tt[l]=or.platform.replace(/chrome os/i,F).replace(/macos/i,ct)),Tt},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 ki},this.setUA=function(Tt){return ki=typeof Tt===a&&Tt.length>500?Rd(Tt,500):Tt,this},this.setUA(ki),this};fn.VERSION="0.7.40",fn.BROWSER=ye([l,p,c]),fn.CPU=ye([g]),fn.DEVICE=ye([d,h,u,m,f,R,T,A,N]),fn.ENGINE=fn.OS=ye([l,p]),t.exports&&(e=t.exports=fn),e.UAParser=fn;var Jr=typeof i!==o&&(i.jQuery||i.Zepto);if(Jr&&!Jr.ua){var yh=new fn;Jr.ua=yh.getResult(),Jr.ua.get=function(){return yh.getUA()},Jr.ua.set=function(Te){yh.setUA(Te);var Ie=yh.getResult();for(var zt in Ie)Jr.ua[zt]=Ie[zt]}}})(typeof window=="object"?window:Qe)})(j_,j_.exports);var EF=Pt(j_.exports),yv=el.clear;Nt({global:!0,bind:!0,enumerable:!0,forced:ie.clearImmediate!==yv},{clearImmediate:yv});var Iv=ie,mF=fi,fF=Be,gF=zh,SF=Pr,TF=oo,RF=Fo,vF=Iv.Function,CF=/MSIE .\./.test(SF)||gF==="BUN"&&function(){var t=Iv.Bun.version.split(".");return t.length<3||t[0]==="0"&&(t[1]<3||t[1]==="3"&&t[2]==="0")}(),yF=Nt,Av=ie,bv=el.set,IF=function(t,e){var i=1;return CF?function(n,r){var o=RF(arguments.length,1)>i,s=fF(n)?n:vF(n),a=o?TF(arguments,i):[],c=o?function(){mF(s,this,a)}:s;return t(c)}:t},wv=Av.setImmediate?IF(bv):bv;yF({global:!0,bind:!0,enumerable:!0,forced:Av.setImmediate!==wv},{setImmediate:wv});var Ov=Pt(sn.setImmediate),AF=ie,bF=BS,wF=Hi,OF=Fo,NF=wi;Nt({global:!0,enumerable:!0,dontCallGetSet:!0,forced:Lt(function(){return NF&&Object.getOwnPropertyDescriptor(AF,"queueMicrotask").value.length!==1})},{queueMicrotask:function(t){OF(arguments.length,1),bF(wF(t))}});var Nv=Pt(sn.queueMicrotask);function Dv(t,e){return function(){return t.apply(e,arguments)}}const{toString:DF}=Object.prototype,{getPrototypeOf:G_}=Object,{iterator:Ol,toStringTag:Pv}=Symbol,Nl=(W_=Object.create(null),t=>{const e=DF.call(t);return W_[e]||(W_[e]=e.slice(8,-1).toLowerCase())});var W_;const Yn=t=>(t=t.toLowerCase(),e=>Nl(e)===t),Dl=t=>e=>typeof e===t,{isArray:Js}=Array,Ec=Dl("undefined"),Lv=Yn("ArrayBuffer"),PF=Dl("string"),Yi=Dl("function"),kv=Dl("number"),Pl=t=>t!==null&&typeof t=="object",Ll=t=>{if(Nl(t)!=="object")return!1;const e=G_(t);return!(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null||Pv in t||Ol in t)},LF=Yn("Date"),kF=Yn("File"),MF=Yn("Blob"),UF=Yn("FileList"),xF=Yn("URLSearchParams"),[VF,FF,BF,jF]=["ReadableStream","Request","Response","Headers"].map(Yn);function mc(t,e){let i,n,{allOwnKeys:r=!1}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(t!=null)if(typeof t!="object"&&(t=[t]),Js(t))for(i=0,n=t.length;i<n;i++)e.call(null,t[i],i,t);else{const o=r?Object.getOwnPropertyNames(t):Object.keys(t),s=o.length;let a;for(i=0;i<s;i++)a=o[i],e.call(null,t[a],a,t)}}function Mv(t,e){e=e.toLowerCase();const i=Object.keys(t);let n,r=i.length;for(;r-- >0;)if(n=i[r],e===n.toLowerCase())return n;return null}const Yo=Cv!==void 0?Cv:typeof self!="undefined"?self:typeof window!="undefined"?window:xf,Uv=t=>!Ec(t)&&t!==Yo,GF=(H_=typeof Uint8Array!="undefined"&&G_(Uint8Array),t=>H_&&t instanceof H_);var H_;const WF=Yn("HTMLFormElement"),xv=(t=>{let{hasOwnProperty:e}=t;return(i,n)=>e.call(i,n)})(Object.prototype),HF=Yn("RegExp"),Vv=(t,e)=>{const i=Object.getOwnPropertyDescriptors(t),n={};mc(i,(r,o)=>{let s;(s=e(r,o,t))!==!1&&(n[o]=s||r)}),Object.defineProperties(t,n)},KF=Yn("AsyncFunction"),Fv=(Bv=typeof Ov=="function",jv=Yi(Yo.postMessage),Bv?Ov:jv?(K_="axios@".concat(Math.random()),kl=[],Yo.addEventListener("message",t=>{let{source:e,data:i}=t;e===Yo&&i===K_&&kl.length&&kl.shift()()},!1),t=>{kl.push(t),Yo.postMessage(K_,"*")}):t=>setTimeout(t));var Bv,jv,K_,kl;const YF=Nv!==void 0?Nv.bind(Yo):typeof process!="undefined"&&process.nextTick||Fv;var W={isArray:Js,isArrayBuffer:Lv,isBuffer:function(t){return t!==null&&!Ec(t)&&t.constructor!==null&&!Ec(t.constructor)&&Yi(t.constructor.isBuffer)&&t.constructor.isBuffer(t)},isFormData:t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||Yi(t.append)&&((e=Nl(t))==="formdata"||e==="object"&&Yi(t.toString)&&t.toString()==="[object FormData]"))},isArrayBufferView:function(t){let e;return e=typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&Lv(t.buffer),e},isString:PF,isNumber:kv,isBoolean:t=>t===!0||t===!1,isObject:Pl,isPlainObject:Ll,isReadableStream:VF,isRequest:FF,isResponse:BF,isHeaders:jF,isUndefined:Ec,isDate:LF,isFile:kF,isBlob:MF,isRegExp:HF,isFunction:Yi,isStream:t=>Pl(t)&&Yi(t.pipe),isURLSearchParams:xF,isTypedArray:GF,isFileList:UF,forEach:mc,merge:function t(){const{caseless:e}=Uv(this)&&this||{},i={},n=(r,o)=>{const s=e&&Mv(i,o)||o;Ll(i[s])&&Ll(r)?i[s]=t(i[s],r):Ll(r)?i[s]=t({},r):Js(r)?i[s]=r.slice():i[s]=r};for(let r=0,o=arguments.length;r<o;r++)arguments[r]&&mc(arguments[r],n);return i},extend:function(t,e,i){let{allOwnKeys:n}=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};return mc(e,(r,o)=>{i&&Yi(r)?t[o]=Dv(r,i):t[o]=r},{allOwnKeys:n}),t},trim:t=>ni(t)?ni(t).call(t):t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),inherits:(t,e,i,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),i&&Object.assign(t.prototype,i)},toFlatObject:(t,e,i,n)=>{let r,o,s;const a={};if(e=e||{},t==null)return e;do{for(r=Object.getOwnPropertyNames(t),o=r.length;o-- >0;)s=r[o],n&&!n(s,t,e)||a[s]||(e[s]=t[s],a[s]=!0);t=i!==!1&&G_(t)}while(t&&(!i||i(t,e))&&t!==Object.prototype);return e},kindOf:Nl,kindOfTest:Yn,endsWith:(t,e,i)=>{t=String(t),(i===void 0||i>t.length)&&(i=t.length),i-=e.length;const n=t.indexOf(e,i);return n!==-1&&n===i},toArray:t=>{if(!t)return null;if(Js(t))return t;let e=t.length;if(!kv(e))return null;const i=new Array(e);for(;e-- >0;)i[e]=t[e];return i},forEachEntry:(t,e)=>{const i=(t&&t[Ol]).call(t);let n;for(;(n=i.next())&&!n.done;){const r=n.value;e.call(t,r[0],r[1])}},matchAll:(t,e)=>{let i;const n=[];for(;(i=t.exec(e))!==null;)n.push(i);return n},isHTMLForm:WF,hasOwnProperty:xv,hasOwnProp:xv,reduceDescriptors:Vv,freezeMethods:t=>{Vv(t,(e,i)=>{if(Yi(t)&&["arguments","caller","callee"].indexOf(i)!==-1)return!1;const n=t[i];Yi(n)&&(e.enumerable=!1,"writable"in e?e.writable=!1:e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+i+"'")}))})},toObjectSet:(t,e)=>{const i={},n=r=>{r.forEach(o=>{i[o]=!0})};return Js(t)?n(t):n(String(t).split(e)),i},toCamelCase:t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,i,n){return i.toUpperCase()+n}),noop:()=>{},toFiniteNumber:(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e,findKey:Mv,global:Yo,isContextDefined:Uv,isSpecCompliantForm:function(t){return!!(t&&Yi(t.append)&&t[Pv]==="FormData"&&t[Ol])},toJSONObject:t=>{const e=new Array(10),i=(n,r)=>{if(Pl(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[r]=n;const o=Js(n)?[]:{};return mc(n,(s,a)=>{const c=i(s,r+1);!Ec(c)&&(o[a]=c)}),e[r]=void 0,o}}return n};return i(t,0)},isAsyncFn:KF,isThenable:t=>t&&(Pl(t)||Yi(t))&&Yi(t.then)&&Yi(t.catch),setImmediate:Fv,asap:YF,isIterable:t=>t!=null&&Yi(t[Ol])};function Ut(t,e,i,n,r){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),i&&(this.config=i),n&&(this.request=n),r&&(this.response=r,this.status=r.status?r.status:null)}W.inherits(Ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:W.toJSONObject(this.config),code:this.code,status:this.status}}});const Gv=Ut.prototype,Wv={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{Wv[t]={value:t}}),Object.defineProperties(Ut,Wv),Object.defineProperty(Gv,"isAxiosError",{value:!0}),Ut.from=(t,e,i,n,r,o)=>{const s=Object.create(Gv);return W.toFlatObject(t,s,function(a){return a!==Error.prototype},a=>a!=="isAxiosError"),Ut.call(s,t.message,e,i,n,r),s.cause=t,s.name=t.name,o&&Object.assign(s,o),s};function Y_(t){return W.isPlainObject(t)||W.isArray(t)}function Hv(t){return W.endsWith(t,"[]")?t.slice(0,-2):t}function Kv(t,e,i){return t?t.concat(e).map(function(n,r){return n=Hv(n),!i&&r?"["+n+"]":n}).join(i?".":""):e}const qF=W.toFlatObject(W,{},null,function(t){return/^is[A-Z]/.test(t)});function Ml(t,e,i){if(!W.isObject(t))throw new TypeError("target must be an object");e=e||new FormData;const n=(i=W.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,p){return!W.isUndefined(p[h])})).metaTokens,r=i.visitor||d,o=i.dots,s=i.indexes,a=(i.Blob||typeof Blob!="undefined"&&Blob)&&W.isSpecCompliantForm(e);if(!W.isFunction(r))throw new TypeError("visitor must be a function");function c(h){if(h===null)return"";if(W.isDate(h))return h.toISOString();if(!a&&W.isBlob(h))throw new Ut("Blob is not supported. Use a Buffer instead.");return W.isArrayBuffer(h)||W.isTypedArray(h)?a&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function d(h,p,g){let m=h;if(h&&!g&&typeof h=="object"){if(W.endsWith(p,"{}"))p=n?p:p.slice(0,-2),h=JSON.stringify(h);else if(W.isArray(h)&&function(f){return W.isArray(f)&&!f.some(Y_)}(h)||(W.isFileList(h)||W.endsWith(p,"[]"))&&(m=W.toArray(h)))return p=Hv(p),m.forEach(function(f,T){!W.isUndefined(f)&&f!==null&&e.append(s===!0?Kv([p],T,o):s===null?p:p+"[]",c(f))}),!1}return!!Y_(h)||(e.append(Kv(g,p,o),c(h)),!1)}const l=[],u=Object.assign(qF,{defaultVisitor:d,convertValue:c,isVisitable:Y_});if(!W.isObject(t))throw new TypeError("data must be an object");return function h(p,g){if(!W.isUndefined(p)){if(l.indexOf(p)!==-1)throw Error("Circular reference detected in "+g.join("."));l.push(p),W.forEach(p,function(m,f){(!(W.isUndefined(m)||m===null)&&r.call(e,m,W.isString(f)?ni(f).call(f):f,g,u))===!0&&h(m,g?g.concat(f):[f])}),l.pop()}}(t),e}function Yv(t){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(i){return e[i]})}function q_(t,e){this._pairs=[],t&&Ml(t,this,e)}const qv=q_.prototype;function zF(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function zv(t,e,i){if(!e)return t;const n=i&&i.encode||zF;W.isFunction(i)&&(i={serialize:i});const r=i&&i.serialize;let o;if(o=r?r(e,i):W.isURLSearchParams(e)?e.toString():new q_(e,i).toString(n),o){const s=t.indexOf("#");s!==-1&&(t=t.slice(0,s)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}qv.append=function(t,e){this._pairs.push([t,e])},qv.toString=function(t){const e=t?function(i){return t.call(this,i,Yv)}:Yv;return this._pairs.map(function(i){return e(i[0])+"="+e(i[1])},"").join("&")};var Xv=class{constructor(){this.handlers=[]}use(t,e,i){return this.handlers.push({fulfilled:t,rejected:e,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){W.forEach(this.handlers,function(e){e!==null&&t(e)})}},Jv={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Qv={exports:{}},XF=Nt,JF=wi,Zv=gn.f;XF({target:"Object",stat:!0,forced:Object.defineProperty!==Zv,sham:!JF},{defineProperty:Zv});var $v=sn.Object,QF=Qv.exports=function(t,e,i){return $v.defineProperty(t,e,i)};$v.defineProperty.sham&&(QF.sham=!0);var tC=Pt(Qv.exports),ZF=TypeError,eC=Ja,$F=tl,tB=gi,eB=Re("species"),iC=Array,iB=function(t){var e;return eC(t)&&(e=t.constructor,($F(e)&&(e===iC||eC(e.prototype))||tB(e)&&(e=e[eB])===null)&&(e=void 0)),e===void 0?iC:e},nC=function(t,e){return new(iB(t))(e===0?0:e)},nB=Lt,rB=Mo,oB=Re("species"),rC=function(t){return rB>=51||!nB(function(){var e=[];return(e.constructor={})[oB]=function(){return{foo:1}},e[t](Boolean).foo!==1})},sB=Nt,aB=Lt,cB=Ja,dB=gi,lB=dr,uB=io,oC=function(t){if(t>9007199254740991)throw ZF("Maximum allowed index exceeded");return t},sC=c_,hB=nC,pB=rC,_B=Mo,aC=Re("isConcatSpreadable"),EB=_B>=51||!aB(function(){var t=[];return t[aC]=!1,t.concat()[0]!==t}),mB=function(t){if(!dB(t))return!1;var e=t[aC];return e!==void 0?!!e:cB(t)};sB({target:"Array",proto:!0,arity:1,forced:!EB||!pB("concat")},{concat:function(t){var e,i,n,r,o,s=lB(this),a=hB(s,0),c=0;for(e=-1,n=arguments.length;e<n;e++)if(mB(o=e===-1?s:arguments[e]))for(r=uB(o),oC(c+r),i=0;i<r;i++,c++)i in o&&sC(a,c,o[i]);else oC(c+1),sC(a,c++,o);return a.length=c,a}});var cC={},fB=cr,gB=to,dC=Vd.f,SB=oo,lC=typeof window=="object"&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];cC.f=function(t){return lC&&fB(t)==="Window"?function(e){try{return dC(e)}catch(i){return SB(lC)}}(t):dC(gB(t))};var Qs={},TB=Re;Qs.f=TB;var uC=sn,RB=ti,vB=Qs,CB=gn.f,ke=function(t){var e=uC.Symbol||(uC.Symbol={});RB(e,t)||CB(e,t,{value:vB.f(t)})},yB=Ye,IB=Si,AB=Re,bB=ro,hC=function(){var t=IB("Symbol"),e=t&&t.prototype,i=e&&e.valueOf,n=AB("toPrimitive");e&&!e[n]&&bB(e,n,function(r){return yB(i,this)},{arity:1})},wB=eo,OB=Od,NB=dr,DB=io,PB=nC,pC=de([].push),ho=function(t){var e=t===1,i=t===2,n=t===3,r=t===4,o=t===6,s=t===7,a=t===5||o;return function(c,d,l,u){for(var h,p,g=NB(c),m=OB(g),f=DB(m),T=wB(d,l),R=0,A=u||PB,N=e?A(c,f):i||s?A(c,0):void 0;f>R;R++)if((a||R in m)&&(p=T(h=m[R],R,g),t))if(e)N[R]=p;else if(p)switch(t){case 3:return!0;case 5:return h;case 6:return R;case 2:pC(N,h)}else switch(t){case 4:return!1;case 7:pC(N,h)}return o?-1:n||r?r:N}},_C={forEach:ho(0),map:ho(1),filter:ho(2),some:ho(3),every:ho(4),find:ho(5),findIndex:ho(6),filterReject:ho(7)},Ul=Nt,fc=ie,z_=Ye,LB=de,Zs=wi,$s=Is,kB=Lt,di=ti,MB=$e,X_=Mi,xl=to,J_=Mh,UB=Ki,Q_=$r,ta=Za,EC=Bd,xB=Vd,mC=cC,VB=Qa,fC=Id,gC=gn,FB=ep,SC=bd,TC=ro,BB=$d,Z_=bs,RC=Fd,vC=Lh,jB=Re,GB=Qs,WB=ke,HB=hC,KB=Lr,CC=Vo,Vl=_C.forEach,qi=xd("hidden"),Fl="Symbol",gc="prototype",YB=CC.set,yC=CC.getterFor(Fl),qn=Object[gc],qo=fc.Symbol,Bl=qo&&qo[gc],qB=fc.RangeError,zB=fc.TypeError,$_=fc.QObject,IC=fC.f,zo=gC.f,AC=mC.f,XB=SC.f,bC=LB([].push),Ur=Z_("symbols"),Sc=Z_("op-symbols"),JB=Z_("wks"),tE=!$_||!$_[gc]||!$_[gc].findChild,wC=function(t,e,i){var n=IC(qn,e);n&&delete qn[e],zo(t,e,i),n&&t!==qn&&zo(qn,e,n)},eE=Zs&&kB(function(){return ta(zo({},"a",{get:function(){return zo(this,"a",{value:7}).a}})).a!==7})?wC:zo,iE=function(t,e){var i=Ur[t]=ta(Bl);return YB(i,{type:Fl,tag:t,description:e}),Zs||(i.description=e),i},jl=function(t,e,i){t===qn&&jl(Sc,e,i),X_(t);var n=J_(e);return X_(i),di(Ur,n)?(i.enumerable?(di(t,qi)&&t[qi][n]&&(t[qi][n]=!1),i=ta(i,{enumerable:Q_(0,!1)})):(di(t,qi)||zo(t,qi,Q_(1,ta(null))),t[qi][n]=!0),eE(t,n,i)):zo(t,n,i)},nE=function(t,e){X_(t);var i=xl(e),n=EC(i).concat(PC(i));return Vl(n,function(r){Zs&&!z_(OC,i,r)||jl(t,r,i[r])}),t},OC=function(t){var e=J_(t),i=z_(XB,this,e);return!(this===qn&&di(Ur,e)&&!di(Sc,e))&&(!(i||!di(this,e)||!di(Ur,e)||di(this,qi)&&this[qi][e])||i)},NC=function(t,e){var i=xl(t),n=J_(e);if(i!==qn||!di(Ur,n)||di(Sc,n)){var r=IC(i,n);return!r||!di(Ur,n)||di(i,qi)&&i[qi][n]||(r.enumerable=!0),r}},DC=function(t){var e=AC(xl(t)),i=[];return Vl(e,function(n){di(Ur,n)||di(RC,n)||bC(i,n)}),i},PC=function(t){var e=t===qn,i=AC(e?Sc:xl(t)),n=[];return Vl(i,function(r){!di(Ur,r)||e&&!di(qn,r)||bC(n,Ur[r])}),n};$s||(qo=function(){if(MB(Bl,this))throw new zB("Symbol is not a constructor");var t=arguments.length&&arguments[0]!==void 0?UB(arguments[0]):void 0,e=vC(t),i=function(n){var r=this===void 0?fc:this;r===qn&&z_(i,Sc,n),di(r,qi)&&di(r[qi],e)&&(r[qi][e]=!1);var o=Q_(1,n);try{eE(r,e,o)}catch(s){if(!(s instanceof qB))throw s;wC(r,e,o)}};return Zs&&tE&&eE(qn,e,{configurable:!0,set:i}),iE(e,t)},TC(Bl=qo[gc],"toString",function(){return yC(this).tag}),TC(qo,"withoutSetter",function(t){return iE(vC(t),t)}),SC.f=OC,gC.f=jl,FB.f=nE,fC.f=NC,xB.f=mC.f=DC,VB.f=PC,GB.f=function(t){return iE(jB(t),t)},Zs&&BB(Bl,"description",{configurable:!0,get:function(){return yC(this).description}})),Ul({global:!0,constructor:!0,wrap:!0,forced:!$s,sham:!$s},{Symbol:qo}),Vl(EC(JB),function(t){WB(t)}),Ul({target:Fl,stat:!0,forced:!$s},{useSetter:function(){tE=!0},useSimple:function(){tE=!1}}),Ul({target:"Object",stat:!0,forced:!$s,sham:!Zs},{create:function(t,e){return e===void 0?ta(t):nE(ta(t),e)},defineProperty:jl,defineProperties:nE,getOwnPropertyDescriptor:NC}),Ul({target:"Object",stat:!0,forced:!$s},{getOwnPropertyNames:DC}),HB(),KB(qo,Fl),RC[qi]=!0;var LC=Is&&!!Symbol.for&&!!Symbol.keyFor,QB=Nt,ZB=Si,$B=ti,tj=Ki,kC=bs,ej=LC,rE=kC("string-to-symbol-registry"),ij=kC("symbol-to-string-registry");QB({target:"Symbol",stat:!0,forced:!ej},{for:function(t){var e=tj(t);if($B(rE,e))return rE[e];var i=ZB("Symbol")(e);return rE[e]=i,ij[i]=e,i}});var nj=Nt,rj=ti,oj=Ya,sj=As,aj=LC,MC=bs("symbol-to-string-registry");nj({target:"Symbol",stat:!0,forced:!aj},{keyFor:function(t){if(!oj(t))throw new TypeError(sj(t)+" is not a symbol");if(rj(MC,t))return MC[t]}});var UC=Ja,cj=Be,xC=cr,dj=Ki,VC=de([].push),lj=Nt,FC=Si,BC=fi,uj=Ye,Tc=de,jC=Lt,GC=Be,WC=Ya,HC=oo,hj=function(t){if(cj(t))return t;if(UC(t)){for(var e=t.length,i=[],n=0;n<e;n++){var r=t[n];typeof r=="string"?VC(i,r):typeof r!="number"&&xC(r)!=="Number"&&xC(r)!=="String"||VC(i,dj(r))}var o=i.length,s=!0;return function(a,c){if(s)return s=!1,c;if(UC(this))return c;for(var d=0;d<o;d++)if(i[d]===a)return c}}},pj=Is,_j=String,po=FC("JSON","stringify"),Gl=Tc(/./.exec),KC=Tc("".charAt),Ej=Tc("".charCodeAt),mj=Tc("".replace),fj=Tc(1 .toString),gj=/[\uD800-\uDFFF]/g,YC=/^[\uD800-\uDBFF]$/,qC=/^[\uDC00-\uDFFF]$/,zC=!pj||jC(function(){var t=FC("Symbol")("stringify detection");return po([t])!=="[null]"||po({a:t})!=="{}"||po(Object(t))!=="{}"}),XC=jC(function(){return po("\uDF06\uD834")!=='"\\udf06\\ud834"'||po("\uDEAD")!=='"\\udead"'}),Sj=function(t,e){var i=HC(arguments),n=hj(e);if(GC(n)||t!==void 0&&!WC(t))return i[1]=function(r,o){if(GC(n)&&(o=uj(n,this,_j(r),o)),!WC(o))return o},BC(po,null,i)},Tj=function(t,e,i){var n=KC(i,e-1),r=KC(i,e+1);return Gl(YC,t)&&!Gl(qC,r)||Gl(qC,t)&&!Gl(YC,n)?"\\u"+fj(Ej(t,0),16):t};po&&lj({target:"JSON",stat:!0,arity:3,forced:zC||XC},{stringify:function(t,e,i){var n=HC(arguments),r=BC(zC?Sj:po,null,n);return XC&&typeof r=="string"?mj(r,gj,Tj):r}});var JC=Qa,Rj=dr;Nt({target:"Object",stat:!0,forced:!Is||Lt(function(){JC.f(1)})},{getOwnPropertySymbols:function(t){var e=JC.f;return e?e(Rj(t)):[]}}),ke("asyncIterator"),ke("hasInstance"),ke("isConcatSpreadable"),ke("iterator"),ke("match"),ke("matchAll"),ke("replace"),ke("search"),ke("species"),ke("split");var vj=hC;ke("toPrimitive"),vj();var Cj=Si,yj=Lr;ke("toStringTag"),yj(Cj("Symbol"),"Symbol"),ke("unscopables"),Lr(ie.JSON,"JSON",!0);var Ij=sn.Symbol,Aj=Re,bj=gn.f,QC=Aj("metadata"),ZC=Function.prototype;ZC[QC]===void 0&&bj(ZC,QC,{value:null}),ke("asyncDispose"),ke("dispose"),ke("metadata");var wj=Ij,Oj=de,oE=Si("Symbol"),Nj=oE.keyFor,Dj=Oj(oE.prototype.valueOf),$C=oE.isRegisteredSymbol||function(t){try{return Nj(Dj(t))!==void 0}catch(e){return!1}};Nt({target:"Symbol",stat:!0},{isRegisteredSymbol:$C});for(var Pj=bs,ty=Si,Lj=de,kj=Ya,Mj=Re,Wl=ty("Symbol"),ey=Wl.isWellKnownSymbol,iy=ty("Object","getOwnPropertyNames"),Uj=Lj(Wl.prototype.valueOf),ny=Pj("wks"),sE=0,ry=iy(Wl),xj=ry.length;sE<xj;sE++)try{var oy=ry[sE];kj(Wl[oy])&&Mj(oy)}catch(t){}var sy=function(t){if(ey&&ey(t))return!0;try{for(var e=Uj(t),i=0,n=iy(ny),r=n.length;i<r;i++)if(ny[n[i]]==e)return!0}catch(o){}return!1};Nt({target:"Symbol",stat:!0,forced:!0},{isWellKnownSymbol:sy}),ke("customMatcher"),ke("observable"),Nt({target:"Symbol",stat:!0,name:"isRegisteredSymbol"},{isRegistered:$C}),Nt({target:"Symbol",stat:!0,name:"isWellKnownSymbol",forced:!0},{isWellKnown:sy}),ke("matcher"),ke("metadataKey"),ke("patternMatch"),ke("replaceAll");var ea=Pt(wj),ay=Pt(Qs.f("iterator"));function Rc(t){return Rc=typeof ea=="function"&&typeof ay=="symbol"?function(e){return typeof e}:function(e){return e&&typeof ea=="function"&&e.constructor===ea&&e!==ea.prototype?"symbol":typeof e},Rc(t)}var Vj=Pt(Qs.f("toPrimitive"));function Fj(t){var e=function(i,n){if(Rc(i)!="object"||!i)return i;var r=i[Vj];if(r!==void 0){var o=r.call(i,n||"default");if(Rc(o)!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(i)}(t,"string");return Rc(e)=="symbol"?e:e+""}function S(t,e,i){return(e=Fj(e))in t?tC(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}var cy=Pt(jx),Bj={isBrowser:!0,classes:{URLSearchParams:cy!==void 0?cy:q_,FormData:typeof FormData!="undefined"?FormData:null,Blob:typeof Blob!="undefined"?Blob:null},protocols:["http","https","file","blob","url","data"]};const aE=typeof window!="undefined"&&typeof document!="undefined",cE=typeof navigator=="object"&&navigator||void 0,jj=aE&&(!cE||["ReactNative","NativeScript","NS"].indexOf(cE.product)<0),Gj=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Wj=aE&&window.location.href||"http://localhost";function dy(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function ly(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?dy(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):dy(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}var Oi=ly(ly({},Object.freeze({__proto__:null,hasBrowserEnv:aE,hasStandardBrowserEnv:jj,hasStandardBrowserWebWorkerEnv:Gj,navigator:cE,origin:Wj})),Bj),Hj=Mi,Kj=Ye,Yj=ti,qj=$e,zj=function(){var t=Hj(this),e="";return t.hasIndices&&(e+="d"),t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.unicodeSets&&(e+="v"),t.sticky&&(e+="y"),e},uy=RegExp.prototype,hy=function(t){var e=t.flags;return e!==void 0||"flags"in uy||Yj(t,"flags")||!qj(uy,t)?e:Kj(zj,t)},Xj=zp.charAt,py=Ye,Jj=Mi,Qj=Be,Zj=cr,$j=/./.exec,tG=TypeError,eG=Nt,_y=Ye,Ey=Ka,iG=Ep,Hl=Qd,my=ko,fy=Eg,vc=Ki,nG=Mi,rG=gi,oG=cr,sG=fg,gy=hy,aG=Dd,cG=Lt,dG=Rp,lG=function(t,e,i){return e+(i?Xj(t,e).length:1)},uG=function(t,e){var i=t.exec;if(Qj(i)){var n=py(i,t,e);return n!==null&&Jj(n),n}if(Zj(t)==="RegExp")return py($j,t,e);throw new tG("RegExp#exec called on incompatible receiver")},Sy=Vo,hG=Re("matchAll"),Ty="RegExp String",Ry=Ty+" Iterator",pG=Sy.set,_G=Sy.getterFor(Ry),EG=TypeError,dE=Ey("".indexOf),Kl=Ey("".matchAll),lE=!!Kl&&!cG(function(){Kl("a",/./)}),mG=iG(function(t,e,i,n){pG(this,{type:Ry,regexp:t,string:e,global:i,unicode:n,done:!1})},Ty,function(){var t=_G(this);if(t.done)return Hl(void 0,!0);var e=t.regexp,i=t.string,n=uG(e,i);return n===null?(t.done=!0,Hl(void 0,!0)):t.global?(vc(n[0])===""&&(e.lastIndex=lG(i,fy(e.lastIndex),t.unicode)),Hl(n,!1)):(t.done=!0,Hl(n,!1))}),vy=function(t){var e,i,n,r=nG(this),o=vc(t),s=dG(r,RegExp),a=vc(gy(r));return e=new s(s===RegExp?r.source:r,a),i=!!~dE(a,"g"),n=!!~dE(a,"u"),e.lastIndex=fy(r.lastIndex),new mG(e,o,i,n)};eG({target:"String",proto:!0,forced:lE},{matchAll:function(t){var e,i,n,r,o=my(this);if(rG(t)){if(sG(t)&&(e=vc(my(gy(t))),!~dE(e,"g")))throw new EG("`.matchAll` does not allow non-global regexes");if(lE)return Kl(o,t);if((n=aG(t,hG))===void 0&&oG(t)==="RegExp"&&(n=vy),n)return _y(n,t,o)}else if(lE)return Kl(o,t);return i=vc(o),r=new RegExp(t,"g"),_y(vy,r,i)}});var fG=Sn("String","matchAll"),gG=$e,SG=fG,uE=String.prototype,TG=function(t){var e=t.matchAll;return typeof t=="string"||t===uE||gG(uE,t)&&e===uE.matchAll?SG:e},RG=Pt(TG);function Cy(t){function e(i,n,r,o){let s=i[o++];if(s==="__proto__")return!0;const a=Number.isFinite(+s),c=o>=i.length;return s=!s&&W.isArray(r)?r.length:s,c?(W.hasOwnProp(r,s)?r[s]=[r[s],n]:r[s]=n,!a):(r[s]&&W.isObject(r[s])||(r[s]=[]),e(i,n,r[s],o)&&W.isArray(r[s])&&(r[s]=function(d){const l={},u=Object.keys(d);let h;const p=u.length;let g;for(h=0;h<p;h++)g=u[h],l[g]=d[g];return l}(r[s])),!a)}if(W.isFormData(t)&&W.isFunction(t.entries)){const i={};return W.forEachEntry(t,(n,r)=>{e(function(o){return RG(W).call(W,/\w+|\[(\w*)]/g,o).map(s=>s[0]==="[]"?"":s[1]||s[0])}(n),r,i,0)}),i}return null}const hE={transitional:Jv,adapter:["xhr","http","fetch"],transformRequest:[function(t,e){const i=e.getContentType()||"",n=i.indexOf("application/json")>-1,r=W.isObject(t);if(r&&W.isHTMLForm(t)&&(t=new FormData(t)),W.isFormData(t))return n?JSON.stringify(Cy(t)):t;if(W.isArrayBuffer(t)||W.isBuffer(t)||W.isStream(t)||W.isFile(t)||W.isBlob(t)||W.isReadableStream(t))return t;if(W.isArrayBufferView(t))return t.buffer;if(W.isURLSearchParams(t))return e.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let o;if(r){if(i.indexOf("application/x-www-form-urlencoded")>-1)return function(s,a){return Ml(s,new Oi.classes.URLSearchParams,Object.assign({visitor:function(c,d,l,u){return Oi.isNode&&W.isBuffer(c)?(this.append(d,c.toString("base64")),!1):u.defaultVisitor.apply(this,arguments)}},a))}(t,this.formSerializer).toString();if((o=W.isFileList(t))||i.indexOf("multipart/form-data")>-1){const s=this.env&&this.env.FormData;return Ml(o?{"files[]":t}:t,s&&new s,this.formSerializer)}}return r||n?(e.setContentType("application/json",!1),function(s,a,c){if(W.isString(s))try{return(a||JSON.parse)(s),ni(W).call(W,s)}catch(d){if(d.name!=="SyntaxError")throw d}return(0,JSON.stringify)(s)}(t)):t}],transformResponse:[function(t){const e=this.transitional||hE.transitional,i=e&&e.forcedJSONParsing,n=this.responseType==="json";if(W.isResponse(t)||W.isReadableStream(t))return t;if(t&&W.isString(t)&&(i&&!this.responseType||n)){const r=!(e&&e.silentJSONParsing)&&n;try{return JSON.parse(t)}catch(o){if(r)throw o.name==="SyntaxError"?Ut.from(o,Ut.ERR_BAD_RESPONSE,this,null,this.response):o}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Oi.classes.FormData,Blob:Oi.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};W.forEach(["delete","get","head","post","put","patch"],t=>{hE.headers[t]={}});var pE=hE;const vG=W.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"]),yy=Symbol("internals");function Cc(t){var e;return t&&ni(e=String(t)).call(e).toLowerCase()}function Yl(t){return t===!1||t==null?t:W.isArray(t)?t.map(Yl):String(t)}function _E(t,e,i,n,r){return W.isFunction(n)?n.call(this,e,i):(r&&(e=i),W.isString(e)?W.isString(n)?e.indexOf(n)!==-1:W.isRegExp(n)?n.test(e):void 0:void 0)}class ql{constructor(e){e&&this.set(e)}set(e,i,n){const r=this;function o(c,d,l){const u=Cc(d);if(!u)throw new Error("header name must be a non-empty string");const h=W.findKey(r,u);(!h||r[h]===void 0||l===!0||l===void 0&&r[h]!==!1)&&(r[h||d]=Yl(c))}const s=(c,d)=>W.forEach(c,(l,u)=>o(l,u,d));if(W.isPlainObject(e)||e instanceof this.constructor)s(e,i);else if(W.isString(e)&&(e=ni(e).call(e))&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(ni(a=e).call(a)))s((c=>{const d={};let l,u,h;return c&&c.split(`
`).forEach(function(p){var g,m;h=p.indexOf(":"),l=ni(g=p.substring(0,h)).call(g).toLowerCase(),u=ni(m=p.substring(h+1)).call(m),!l||d[l]&&vG[l]||(l==="set-cookie"?d[l]?d[l].push(u):d[l]=[u]:d[l]=d[l]?d[l]+", "+u:u)}),d})(e),i);else if(W.isObject(e)&&W.isIterable(e)){let c,d,l={};for(const u of e){if(!W.isArray(u))throw TypeError("Object iterator must return a key-value pair");l[d=u[0]]=(c=l[d])?W.isArray(c)?[...c,u[1]]:[c,u[1]]:u[1]}s(l,i)}else e!=null&&o(i,e,n);var a;return this}get(e,i){if(e=Cc(e)){const n=W.findKey(this,e);if(n){const r=this[n];if(!i)return r;if(i===!0)return function(o){const s=Object.create(null),a=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let c;for(;c=a.exec(o);)s[c[1]]=c[2];return s}(r);if(W.isFunction(i))return i.call(this,r,n);if(W.isRegExp(i))return i.exec(r);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,i){if(e=Cc(e)){const n=W.findKey(this,e);return!(!n||this[n]===void 0||i&&!_E(0,this[n],n,i))}return!1}delete(e,i){const n=this;let r=!1;function o(s){if(s=Cc(s)){const a=W.findKey(n,s);!a||i&&!_E(0,n[a],a,i)||(delete n[a],r=!0)}}return W.isArray(e)?e.forEach(o):o(e),r}clear(e){const i=Object.keys(this);let n=i.length,r=!1;for(;n--;){const o=i[n];e&&!_E(0,this[o],o,e,!0)||(delete this[o],r=!0)}return r}normalize(e){const i=this,n={};return W.forEach(this,(r,o)=>{var s;const a=W.findKey(n,o);if(a)return i[a]=Yl(r),void delete i[o];const c=e?function(d){return ni(d).call(d).toLowerCase().replace(/([a-z\d])(\w*)/g,(l,u,h)=>u.toUpperCase()+h)}(o):ni(s=String(o)).call(s);c!==o&&delete i[o],i[c]=Yl(r),n[c]=!0}),this}concat(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return this.constructor.concat(this,...i)}toJSON(e){const i=Object.create(null);return W.forEach(this,(n,r)=>{n!=null&&n!==!1&&(i[r]=e&&W.isArray(n)?n.join(", "):n)}),i}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(e=>{let[i,n]=e;return i+": "+n}).join(`
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e){const i=new this(e);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return r.forEach(s=>i.set(s)),i}static accessor(e){const i=(this[yy]=this[yy]={accessors:{}}).accessors,n=this.prototype;function r(o){const s=Cc(o);i[s]||(function(a,c){const d=W.toCamelCase(" "+c);["get","set","has"].forEach(l=>{Object.defineProperty(a,l+d,{value:function(u,h,p){return this[l].call(this,c,u,h,p)},configurable:!0})})}(n,o),i[s]=!0)}return W.isArray(e)?e.forEach(r):r(e),this}}ql.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),W.reduceDescriptors(ql.prototype,(t,e)=>{let{value:i}=t,n=e[0].toUpperCase()+e.slice(1);return{get:()=>i,set(r){this[n]=r}}}),W.freezeMethods(ql);var zn=ql;function EE(t,e){const i=this||pE,n=e||i,r=zn.from(n.headers);let o=n.data;return W.forEach(t,function(s){o=s.call(i,o,r.normalize(),e?e.status:void 0)}),r.normalize(),o}function Iy(t){return!(!t||!t.__CANCEL__)}function ia(t,e,i){Ut.call(this,t==null?"canceled":t,Ut.ERR_CANCELED,e,i),this.name="CanceledError"}function Ay(t,e,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?e(new Ut("Request failed with status code "+i.status,[Ut.ERR_BAD_REQUEST,Ut.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):t(i)}W.inherits(ia,Ut,{__CANCEL__:!0});const zl=function(t,e){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:3,n=0;const r=function(o,s){o=o||10;const a=new Array(o),c=new Array(o);let d,l=0,u=0;return s=s!==void 0?s:1e3,function(h){const p=Date.now(),g=c[u];d||(d=p),a[l]=h,c[l]=p;let m=u,f=0;for(;m!==l;)f+=a[m++],m%=o;if(l=(l+1)%o,l===u&&(u=(u+1)%o),p-d<s)return;const T=g&&p-g;return T?Math.round(1e3*f/T):void 0}}(50,250);return function(o,s){let a,c,d=0,l=1e3/s;const u=function(h){d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Date.now(),a=null,c&&(clearTimeout(c),c=null),o.apply(null,h)};return[function(){const h=Date.now(),p=h-d;for(var g=arguments.length,m=new Array(g),f=0;f<g;f++)m[f]=arguments[f];p>=l?u(m,h):(a=m,c||(c=setTimeout(()=>{c=null,u(a)},l-p)))},()=>a&&u(a)]}(o=>{const s=o.loaded,a=o.lengthComputable?o.total:void 0,c=s-n,d=r(c);n=s,t({loaded:s,total:a,progress:a?s/a:void 0,bytes:c,rate:d||void 0,estimated:d&&a&&s<=a?(a-s)/d:void 0,event:o,lengthComputable:a!=null,[e?"download":"upload"]:!0})},i)},by=(t,e)=>{const i=t!=null;return[n=>e[0]({lengthComputable:i,total:t,loaded:n}),e[1]]},wy=t=>function(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];return W.asap(()=>t(...i))};var CG=Oi.hasStandardBrowserEnv?((t,e)=>i=>(i=new vl(i,Oi.origin),t.protocol===i.protocol&&t.host===i.host&&(e||t.port===i.port)))(new vl(Oi.origin),Oi.navigator&&/(msie|trident)/i.test(Oi.navigator.userAgent)):()=>!0,yG=Oi.hasStandardBrowserEnv?{write(t,e,i,n,r,o){const s=[t+"="+encodeURIComponent(e)];W.isNumber(i)&&s.push("expires="+new Date(i).toGMTString()),W.isString(n)&&s.push("path="+n),W.isString(r)&&s.push("domain="+r),o===!0&&s.push("secure"),document.cookie=s.join("; ")},read(t){const e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Oy(t,e,i){let n=!function(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}(e);return t&&(n||i==0)?function(r,o){return o?r.replace(/\/?\/$/,"")+"/"+o.replace(/^\/+/,""):r}(t,e):e}function Ny(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}const Dy=t=>t instanceof zn?function(e){for(var i=1;i<arguments.length;i++){var n=arguments[i]!=null?arguments[i]:{};i%2?Ny(Object(n),!0).forEach(function(r){S(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ny(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}({},t):t;function Xo(t,e){e=e||{};const i={};function n(d,l,u,h){return W.isPlainObject(d)&&W.isPlainObject(l)?W.merge.call({caseless:h},d,l):W.isPlainObject(l)?W.merge({},l):W.isArray(l)?l.slice():l}function r(d,l,u,h){return W.isUndefined(l)?W.isUndefined(d)?void 0:n(void 0,d,0,h):n(d,l,0,h)}function o(d,l){if(!W.isUndefined(l))return n(void 0,l)}function s(d,l){return W.isUndefined(l)?W.isUndefined(d)?void 0:n(void 0,d):n(void 0,l)}function a(d,l,u){return u in e?n(d,l):u in t?n(void 0,d):void 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,responseEncoding:s,validateStatus:a,headers:(d,l,u)=>r(Dy(d),Dy(l),0,!0)};return W.forEach(Object.keys(Object.assign({},t,e)),function(d){const l=c[d]||r,u=l(t[d],e[d],d);W.isUndefined(u)&&l!==a||(i[d]=u)}),i}var Py=t=>{const e=Xo({},t);let i,{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:c}=e;if(e.headers=a=zn.from(a),e.url=zv(Oy(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),W.isFormData(n)){if(Oi.hasStandardBrowserEnv||Oi.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if((i=a.getContentType())!==!1){const[d,...l]=i?i.split(";").map(u=>ni(u).call(u)).filter(Boolean):[];a.setContentType([d||"multipart/form-data",...l].join("; "))}}if(Oi.hasStandardBrowserEnv&&(r&&W.isFunction(r)&&(r=r(e)),r||r!==!1&&CG(e.url))){const d=o&&s&&yG.read(s);d&&a.set(o,d)}return e},IG=typeof XMLHttpRequest!="undefined"&&function(t){return new K(function(e,i){const n=Py(t);let r=n.data;const o=zn.from(n.headers).normalize();let s,a,c,d,l,{responseType:u,onUploadProgress:h,onDownloadProgress:p}=n;function g(){d&&d(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(s),n.signal&&n.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const R=zn.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Ay(function(A){e(A),g()},function(A){i(A),g()},{data:u&&u!=="text"&&u!=="json"?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:R,config:t,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&m.readyState===4&&(m.status!==0||m.responseURL&&m.responseURL.indexOf("file:")===0)&&setTimeout(f)},m.onabort=function(){m&&(i(new Ut("Request aborted",Ut.ECONNABORTED,t,m)),m=null)},m.onerror=function(){i(new Ut("Network Error",Ut.ERR_NETWORK,t,m)),m=null},m.ontimeout=function(){let R=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const A=n.transitional||Jv;n.timeoutErrorMessage&&(R=n.timeoutErrorMessage),i(new Ut(R,A.clarifyTimeoutError?Ut.ETIMEDOUT:Ut.ECONNABORTED,t,m)),m=null},r===void 0&&o.setContentType(null),"setRequestHeader"in m&&W.forEach(o.toJSON(),function(R,A){m.setRequestHeader(A,R)}),W.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),u&&u!=="json"&&(m.responseType=n.responseType),p&&([c,l]=zl(p,!0),m.addEventListener("progress",c)),h&&m.upload&&([a,d]=zl(h),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",d)),(n.cancelToken||n.signal)&&(s=R=>{m&&(i(!R||R.type?new ia(null,t,m):R),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(s),n.signal&&(n.signal.aborted?s():n.signal.addEventListener("abort",s)));const T=function(R){const A=/^([-+\w]{1,25})(:?\/\/|:)/.exec(R);return A&&A[1]||""}(n.url);T&&Oi.protocols.indexOf(T)===-1?i(new Ut("Unsupported protocol "+T+":",Ut.ERR_BAD_REQUEST,t)):m.send(r||null)})},AG=(t,e)=>{const{length:i}=t=t?t.filter(Boolean):[];if(e||i){let n,r=new AbortController;const o=function(d){if(!n){n=!0,a();const l=d instanceof Error?d:this.reason;r.abort(l instanceof Ut?l:new ia(l instanceof Error?l.message:l))}};let s=e&&setTimeout(()=>{s=null,o(new Ut("timeout ".concat(e," of ms exceeded"),Ut.ETIMEDOUT))},e);const a=()=>{t&&(s&&clearTimeout(s),s=null,t.forEach(d=>{d.unsubscribe?d.unsubscribe(o):d.removeEventListener("abort",o)}),t=null)};t.forEach(d=>d.addEventListener("abort",o));const{signal:c}=r;return c.unsubscribe=()=>W.asap(a),c}},mE=Pt(ST),Ly=Qs.f("asyncIterator"),bG=Pt(Ly);function fE(t,e){this.v=t,this.k=e}function cn(t){return function(){return new yc(t.apply(this,arguments))}}function yc(t){var e,i;function n(o,s){try{var a=t[o](s),c=a.value,d=c instanceof fE;mE.resolve(d?c.v:c).then(function(l){if(d){var u=o==="return"?"return":"next";if(!c.k||l.done)return n(u,l);l=t[u](l).value}r(a.done?"return":"normal",l)},function(l){n("throw",l)})}catch(l){r("throw",l)}}function r(o,s){switch(o){case"return":e.resolve({value:s,done:!0});break;case"throw":e.reject(s);break;default:e.resolve({value:s,done:!1})}(e=e.next)?n(e.key,e.arg):i=null}this._invoke=function(o,s){return new mE(function(a,c){var d={key:o,arg:s,resolve:a,reject:c,next:null};i?i=i.next=d:(e=i=d,n(o,s))})},typeof t.return!="function"&&(this.return=void 0)}function Rt(t){return new fE(t,0)}function Xl(t){var e={},i=!1;function n(r,o){return i=!0,o=new mE(function(s){s(t[r](o))}),{done:!1,value:new fE(o,1)}}return e[ea!==void 0&&ay||"@@iterator"]=function(){return this},e.next=function(r){return i?(i=!1,r):n("next",r)},typeof t.throw=="function"&&(e.throw=function(r){if(i)throw i=!1,r;return n("throw",r)}),typeof t.return=="function"&&(e.return=function(r){return i?(i=!1,r):n("return",r)}),e}yc.prototype[typeof ea=="function"&&bG||"@@asyncIterator"]=function(){return this},yc.prototype.next=function(t){return this._invoke("next",t)},yc.prototype.throw=function(t){return this._invoke("throw",t)},yc.prototype.return=function(t){return this._invoke("return",t)};var gE=Pt(Ly);function SE(t){var e,i,n,r=2;for(typeof Symbol!="undefined"&&(i=gE,n=Symbol.iterator);r--;){if(i&&(e=t[i])!=null)return e.call(t);if(n&&(e=t[n])!=null)return new Jl(e.call(t));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function Jl(t){function e(i){if(Object(i)!==i)return K.reject(new TypeError(i+" is not an object."));var n=i.done;return K.resolve(i.value).then(function(r){return{value:r,done:n}})}return Jl=function(i){this.s=i,this.n=i.next},Jl.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(i){var n=this.s.return;return n===void 0?K.resolve({value:i,done:!0}):e(n.apply(this.s,arguments))},throw:function(i){var n=this.s.return;return n===void 0?K.reject(i):e(n.apply(this.s,arguments))}},new Jl(t)}const wG=function*(t,e){let i=t.byteLength;if(!e||i<e)return void(yield t);let n,r=0;for(;r<i;)n=r+e,yield t.slice(r,n),r=n},OG=function(){var t=cn(function*(e,i){var n,r=!1,o=!1;try{for(var s,a=SE(NG(e));r=!(s=yield Rt(a.next())).done;r=!1){const c=s.value;yield*vd(Xl(SE(wG(c,i))))}}catch(c){o=!0,n=c}finally{try{r&&a.return!=null&&(yield Rt(a.return()))}finally{if(o)throw n}}});return function(e,i){return t.apply(this,arguments)}}(),NG=function(){var t=cn(function*(e){if(e[gE])return void(yield*vd(Xl(SE(e))));const i=e.getReader();try{for(;;){const{done:n,value:r}=yield Rt(i.read());if(n)break;yield r}}finally{yield Rt(i.cancel())}});return function(e){return t.apply(this,arguments)}}(),ky=(t,e,i,n)=>{const r=OG(t,e);let o,s=0,a=d=>{o||(o=!0,n&&n(d))};return new ReadableStream({pull(d){return C(this,null,function*(){try{const{done:l,value:u}=yield r.next();if(l)return a(),void d.close();let h=u.byteLength;if(i){let p=s+=h;i(p)}d.enqueue(new Uint8Array(u))}catch(l){throw a(l),l}})},cancel:d=>(a(d),r.return())},{highWaterMark:2})};function My(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Uy(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?My(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):My(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}const Ql=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",xy=Ql&&typeof ReadableStream=="function",DG=Ql&&(typeof TextEncoder=="function"?(Vy=new TextEncoder,t=>Vy.encode(t)):t=>C(this,null,function*(){return new Uint8Array(yield new Response(t).arrayBuffer())}));var Vy;const Fy=function(t){try{for(var e=arguments.length,i=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];return!!t(...i)}catch(r){return!1}},PG=xy&&Fy(()=>{let t=!1;const e=new Request(Oi.origin,{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),TE=xy&&Fy(()=>W.isReadableStream(new Response("").body)),Zl={stream:TE&&(t=>t.body)};var By;Ql&&(By=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Zl[t]&&(Zl[t]=W.isFunction(By[t])?e=>e[t]():(e,i)=>{throw new Ut("Response type '".concat(t,"' is not supported"),Ut.ERR_NOT_SUPPORT,i)})}));const LG=(t,e)=>C(this,null,function*(){const i=W.toFiniteNumber(t.getContentLength());return i==null?(n=>C(this,null,function*(){return n==null?0:W.isBlob(n)?n.size:W.isSpecCompliantForm(n)?(yield new Request(Oi.origin,{method:"POST",body:n}).arrayBuffer()).byteLength:W.isArrayBufferView(n)||W.isArrayBuffer(n)?n.byteLength:(W.isURLSearchParams(n)&&(n+=""),W.isString(n)?(yield DG(n)).byteLength:void 0)}))(e):i});var kG=Ql&&(t=>C(this,null,function*(){let{url:e,method:i,data:n,signal:r,cancelToken:o,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:d,headers:l,withCredentials:u="same-origin",fetchOptions:h}=Py(t);d=d?(d+"").toLowerCase():"text";let p,g=AG([r,o&&o.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&PG&&i!=="get"&&i!=="head"&&(f=yield LG(l,n))!==0){let O,w=new Request(e,{method:"POST",body:n,duplex:"half"});if(W.isFormData(n)&&(O=w.headers.get("content-type"))&&l.setContentType(O),w.body){const[L,M]=by(f,zl(wy(c)));n=ky(w.body,65536,L,M)}}W.isString(u)||(u=u?"include":"omit");const T="credentials"in Request.prototype;p=new Request(e,Uy(Uy({},h),{},{signal:g,method:i.toUpperCase(),headers:l.normalize().toJSON(),body:n,duplex:"half",credentials:T?u:void 0}));let R=yield fetch(p);const A=TE&&(d==="stream"||d==="response");if(TE&&(a||A&&m)){const O={};["status","statusText","headers"].forEach(j=>{O[j]=R[j]});const w=W.toFiniteNumber(R.headers.get("content-length")),[L,M]=a&&by(w,zl(wy(a),!0))||[];R=new Response(ky(R.body,65536,L,()=>{M&&M(),m&&m()}),O)}d=d||"text";let N=yield Zl[W.findKey(Zl,d)||"text"](R,t);return!A&&m&&m(),yield new K((O,w)=>{Ay(O,w,{data:N,headers:zn.from(R.headers),status:R.status,statusText:R.statusText,config:t,request:p})})}catch(T){throw m&&m(),T&&T.name==="TypeError"&&/Load failed|fetch/i.test(T.message)?Object.assign(new Ut("Network Error",Ut.ERR_NETWORK,t,p),{cause:T.cause||T}):Ut.from(T,T&&T.code,t,p)}}));const RE={http:null,xhr:IG,fetch:kG};W.forEach(RE,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(i){}Object.defineProperty(t,"adapterName",{value:e})}});const jy=t=>"- ".concat(t),MG=t=>W.isFunction(t)||t===null||t===!1;var Gy={getAdapter:t=>{t=W.isArray(t)?t:[t];const{length:e}=t;let i,n;const r={};for(let o=0;o<e;o++){let s;if(i=t[o],n=i,!MG(i)&&(n=RE[(s=String(i)).toLowerCase()],n===void 0))throw new Ut("Unknown adapter '".concat(s,"'"));if(n)break;r[s||"#"+o]=n}if(!n){const o=Object.entries(r).map(s=>{let[a,c]=s;return"adapter ".concat(a," ")+(c===!1?"is not supported by the environment":"is not available in the build")});throw new Ut("There is no suitable adapter to dispatch the request "+(e?o.length>1?`since :
`+o.map(jy).join(`
`):" "+jy(o[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n},adapters:RE};function vE(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new ia(null,t)}function Wy(t){return vE(t),t.headers=zn.from(t.headers),t.data=EE.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Gy.getAdapter(t.adapter||pE.adapter)(t).then(function(e){return vE(t),e.data=EE.call(t,t.transformResponse,e),e.headers=zn.from(e.headers),e},function(e){return Iy(e)||(vE(t),e&&e.response&&(e.response.data=EE.call(t,t.transformResponse,e.response),e.response.headers=zn.from(e.response.headers))),K.reject(e)})}const Hy="1.9.0",$l={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{$l[t]=function(i){return typeof i===t||"a"+(e<1?"n ":" ")+t}});const Ky={};$l.transitional=function(t,e,i){function n(r,o){return"[Axios v"+Hy+"] Transitional option '"+r+"'"+o+(i?". "+i:"")}return(r,o,s)=>{if(t===!1)throw new Ut(n(o," has been removed"+(e?" in "+e:"")),Ut.ERR_DEPRECATED);return e&&!Ky[o]&&(Ky[o]=!0,console.warn(n(o," has been deprecated since v"+e+" and will be removed in the near future"))),!t||t(r,o,s)}},$l.spelling=function(t){return(e,i)=>(console.warn("".concat(i," is likely a misspelling of ").concat(t)),!0)};var tu={assertOptions:function(t,e,i){if(typeof t!="object")throw new Ut("options must be an object",Ut.ERR_BAD_OPTION_VALUE);const n=Object.keys(t);let r=n.length;for(;r-- >0;){const o=n[r],s=e[o];if(s){const a=t[o],c=a===void 0||s(a,o,t);if(c!==!0)throw new Ut("option "+o+" must be "+c,Ut.ERR_BAD_OPTION_VALUE)}else if(i!==!0)throw new Ut("Unknown option "+o,Ut.ERR_BAD_OPTION)}},validators:$l};const pr=tu.validators;let eu=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Xv,response:new Xv}}request(t,e){return C(this,null,function*(){try{return yield this._request(t,e)}catch(i){if(i instanceof Error){let n={};Error.captureStackTrace?Error.captureStackTrace(n):n=new Error;const r=n.stack?n.stack.replace(/^.+\n/,""):"";try{i.stack?r&&!String(i.stack).endsWith(r.replace(/^.+\n.+\n/,""))&&(i.stack+=`
`+r):i.stack=r}catch(o){}}throw i}})}_request(t,e){typeof t=="string"?(e=e||{}).url=t:e=t||{},e=Xo(this.defaults,e);const{transitional:i,paramsSerializer:n,headers:r}=e;i!==void 0&&tu.assertOptions(i,{silentJSONParsing:pr.transitional(pr.boolean),forcedJSONParsing:pr.transitional(pr.boolean),clarifyTimeoutError:pr.transitional(pr.boolean)},!1),n!=null&&(W.isFunction(n)?e.paramsSerializer={serialize:n}:tu.assertOptions(n,{encode:pr.function,serialize:pr.function},!0)),e.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?e.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:e.allowAbsoluteUrls=!0),tu.assertOptions(e,{baseUrl:pr.spelling("baseURL"),withXsrfToken:pr.spelling("withXSRFToken")},!0),e.method=(e.method||this.defaults.method||"get").toLowerCase();let o=r&&W.merge(r.common,r[e.method]);r&&W.forEach(["delete","get","head","post","put","patch","common"],p=>{delete r[p]}),e.headers=zn.concat(o,r);const s=[];let a=!0;this.interceptors.request.forEach(function(p){typeof p.runWhen=="function"&&p.runWhen(e)===!1||(a=a&&p.synchronous,s.unshift(p.fulfilled,p.rejected))});const c=[];let d;this.interceptors.response.forEach(function(p){c.push(p.fulfilled,p.rejected)});let l,u=0;if(!a){const p=[Wy.bind(this),void 0];for(p.unshift.apply(p,s),p.push.apply(p,c),l=p.length,d=K.resolve(e);u<l;)d=d.then(p[u++],p[u++]);return d}l=s.length;let h=e;for(u=0;u<l;){const p=s[u++],g=s[u++];try{h=p(h)}catch(m){g.call(this,m);break}}try{d=Wy.call(this,h)}catch(p){return K.reject(p)}for(u=0,l=c.length;u<l;)d=d.then(c[u++],c[u++]);return d}getUri(t){return zv(Oy((t=Xo(this.defaults,t)).baseURL,t.url,t.allowAbsoluteUrls),t.params,t.paramsSerializer)}};W.forEach(["delete","get","head","options"],function(t){eu.prototype[t]=function(e,i){return this.request(Xo(i||{},{method:t,url:e,data:(i||{}).data}))}}),W.forEach(["post","put","patch"],function(t){function e(i){return function(n,r,o){return this.request(Xo(o||{},{method:t,headers:i?{"Content-Type":"multipart/form-data"}:{},url:n,data:r}))}}eu.prototype[t]=e(),eu.prototype[t+"Form"]=e(!0)});var iu=eu;class CE{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let i;this.promise=new K(function(r){i=r});const n=this;this.promise.then(r=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](r);n._listeners=null}),this.promise.then=r=>{let o;const s=new K(a=>{n.subscribe(a),o=a}).then(r);return s.cancel=function(){n.unsubscribe(o)},s},e(function(r,o,s){n.reason||(n.reason=new ia(r,o,s),i(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 i=this._listeners.indexOf(e);i!==-1&&this._listeners.splice(i,1)}toAbortSignal(){const e=new AbortController,i=n=>{e.abort(n)};return this.subscribe(i),e.signal.unsubscribe=()=>this.unsubscribe(i),e.signal}static source(){let e;return{token:new CE(function(n){e=n}),cancel:e}}}var UG=CE;const yE={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};Object.entries(yE).forEach(t=>{let[e,i]=t;yE[i]=e});var xG=yE;const ei=function t(e){const i=new iu(e),n=Dv(iu.prototype.request,i);return W.extend(n,iu.prototype,i,{allOwnKeys:!0}),W.extend(n,i,null,{allOwnKeys:!0}),n.create=function(r){return t(Xo(e,r))},n}(pE);ei.Axios=iu,ei.CanceledError=ia,ei.CancelToken=UG,ei.isCancel=Iy,ei.VERSION=Hy,ei.toFormData=Ml,ei.AxiosError=Ut,ei.Cancel=ei.CanceledError,ei.all=function(t){return K.all(t)},ei.spread=function(t){return function(e){return t.apply(null,e)}},ei.isAxiosError=function(t){return W.isObject(t)&&t.isAxiosError===!0},ei.mergeConfig=Xo,ei.AxiosHeaders=zn,ei.formToJSON=t=>Cy(W.isHTMLForm(t)?new FormData(t):t),ei.getAdapter=Gy.getAdapter,ei.HttpStatusCode=xG,ei.default=ei;var Ti=ei;const VG=()=>{};function Ic(){const t={promise:void 0,isResolved:!1,isRejected:!1,isFinished:!1,resolve:void 0,reject:void 0,cancel:VG};return t.promise=new K((e,i)=>{t.resolve=n=>{t.isFinished||(t.isResolved=!0,t.isFinished=!0,e(n),t.value=n)},t.reject=n=>{t.isFinished||(t.isRejected=!0,t.isFinished=!0,i(n))}}),t}const nu=new Map,ru=new Map,_r=new Map;let we=function(t){return t.WIN_10="Windows 10",t.WIN_81="Windows 8.1",t.WIN_8="Windows 8",t.WIN_7="Windows 7",t.WIN_VISTA="Windows Vista",t.WIN_SERVER_2003="Windows Server 2003",t.WIN_XP="Windows XP",t.WIN_2000="Windows 2000",t.ANDROID="Android",t.HARMONY_OS="HarmonyOS",t.OPEN_BSD="Open BSD",t.SUN_OS="Sun OS",t.LINUX="Linux",t.IOS="iOS",t.MAC_OS="Mac OS",t.CHROMIUM_OS="Chromium OS",t.QNX="QNX",t.UNIX="UNIX",t.BEOS="BeOS",t.OS_2="OS/2",t.SEARCH_BOT="Search Bot",t}({}),It=function(t){return t.CHROME="Chrome",t.SAFARI="Safari",t.EDGE="Edge",t.FIREFOX="Firefox",t.OPERA="OPR",t.QQ="QQBrowser",t.WECHAT="MicroMessenger",t}({});const Yy=new EF;let Xn=Yy.getResult(),IE=null;function vt(t){if(!IE){Xn=Yy.getResult();const e=function(a){if(a.engine.name==="Blink"&&a.browser.name!=="WeChat")return It.CHROME;switch(a.browser.name){case"Chrome Headless":case"Chrome":case"Chromium":return It.CHROME;case"Safari":case"Mobile Safari":return It.SAFARI;case"Edge":return It.EDGE;case"Firefox":return It.FIREFOX;case"QQ":case"QQBrowser":return It.QQ;case"Opera":return It.OPERA;case"WeChat":return It.WECHAT;default:return a.browser.name||""}}(Xn),i=qy(Xn),n=function(a){return a.os.name==="Windows"?a.os.version?a.os.name+" "+a.os.version:a.os.name:a.os.name||""}(Xn),r=Xn.os.version,o=qy(Xn,!1),s=Xn.device.type;if(!(e&&i&&n&&r))return{name:e,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s};IE={name:e,version:i,os:n,osVersion:r,browserVersion:o,deviceType:s}}return IE}function qy(t){let e,i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return e=t.engine.name==="Blink"?t.engine.version||"":t.browser.version||"",i?e.split(".")[0]:e}function ou(){return vt().os}function zy(){const t=vt();return"".concat(t.os," ").concat(t.osVersion)}function su(){const t=vt();return!!(Xn.engine.name==="WebKit"&&t.os===we.MAC_OS&&navigator.maxTouchPoints&&navigator.maxTouchPoints>0&&t.name!==It.SAFARI||li()&&t.name!==It.SAFARI)}function xr(){return vt().name===It.CHROME}function je(){return vt().name===It.SAFARI}function Xy(){return vt().name===It.EDGE}function ne(){return vt().name===It.FIREFOX}function li(){return vt().os===we.IOS}function Ac(t){const e=vt();return!(e.name!==It.CHROME||!e.osVersion)&&Number(e.version)>=t}function Jy(t){const e=vt();return!(e.name!==It.CHROME||!e.osVersion)&&Number(e.version)<t}function AE(t,e,i){const n=vt();return!(n.name!==t||!n.osVersion)&&(i?Number(n.version)>=e&&Number(n.version)<=i:Number(n.version)===e)}function bE(t){const e=vt();return!(e.name!==It.EDGE||!e.osVersion)&&Number(e.version)>=t}function Qy(t){const e=vt();return!(e.name!==It.SAFARI||!e.osVersion)&&Number(e.version)>=t}function Zy(t,e,i){const n=vt();if(n.os!==we.IOS||!n.osVersion)return!1;const r=n.osVersion.split(".");return e&&Number(r[0])===t&&Number(r[1])<e||Number(r[0])<t}function $y(t,e,i){const n=vt();if(n.name!==It.SAFARI||!n.osVersion||!n.browserVersion)return!1;const r=n.browserVersion.split(".");return e&&Number(r[0])===t&&Number(r[1])<e||Number(r[0])<t}function wE(t){const e=vt();return!(e.name!==It.OPERA||!e.osVersion)&&Number(e.version)>=t}function tI(){const t=vt();if(t.os!==we.IOS||!t.osVersion)return!1;const e=t.osVersion.split(".");return Number(e[0])<14||Number(e[0])===14&&Number(e[1])<=6}function na(){const t=vt();if(t.os!==we.IOS||!t.osVersion)return!1;const e=t.osVersion.split(".");return Number(e[0])===15}function OE(){const t=vt();if(t.os!==we.IOS||!t.osVersion)return!1;const e=t.osVersion.split(".");return Number(e[0])===16}function eI(){const t=vt();if(t.os!==we.IOS||!t.osVersion)return!1;const e=t.osVersion.split(".");return Number(e[0])===15&&Number(e[1])>=1}function bn(){return je()&&navigator.maxTouchPoints>0}function iI(){return vt().name===It.WECHAT}function nI(){return window.navigator.appVersion&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)!==null&&window.navigator.appVersion.match(/Chrome\/([\w\W]*?)\./)[1]<=35}function NE(){const t=ou();return function(){const{deviceType:e}=vt();return e==="mobile"||e==="tablet"}()||t===we.ANDROID||t===we.IOS||t===we.HARMONY_OS}function Vr(){const t=vt();return t.name!==It.EDGE&&t.name!==It.SAFARI&&!!navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]./i)}function au(){return ou()===we.ANDROID}function bc(){const t=vt();return au()&&(t.name===It.CHROME||t.name===It.WECHAT||/chrome|chromium/i.test(navigator.userAgent))}function st(t,e,i){return(e=function(n){var r=function(o,s){if(typeof o!="object"||!o)return o;var a=o[Symbol.toPrimitive];if(a!==void 0){var c=a.call(o,"string");if(typeof c!="object")return c;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}(n);return typeof r=="symbol"?r:r+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function rI(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function z(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?rI(Object(i),!0).forEach(function(n){st(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):rI(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}let v=function(t){return t.UNEXPECTED_ERROR="UNEXPECTED_ERROR",t.UNEXPECTED_RESPONSE="UNEXPECTED_RESPONSE",t.TIMEOUT="TIMEOUT",t.INVALID_PARAMS="INVALID_PARAMS",t.NOT_READABLE="NOT_READABLE",t.NOT_SUPPORTED="NOT_SUPPORTED",t.INVALID_OPERATION="INVALID_OPERATION",t.OPERATION_ABORTED="OPERATION_ABORTED",t.WEB_SECURITY_RESTRICT="WEB_SECURITY_RESTRICT",t.EXCHANGE_SDP_FAILED="EXCHANGE_SDP_FAILED",t.ADD_CANDIDATE_FAILED="ADD_CANDIDATE_FAILED",t.DATACHANNEL_FAILED="DATACHANNEL_FAILED",t.NETWORK_ERROR="NETWORK_ERROR",t.NETWORK_TIMEOUT="NETWORK_TIMEOUT",t.NETWORK_RESPONSE_ERROR="NETWORK_RESPONSE_ERROR",t.API_INVOKE_TIMEOUT="API_INVOKE_TIMEOUT",t.ENUMERATE_DEVICES_FAILED="ENUMERATE_DEVICES_FAILED",t.DEVICE_NOT_FOUND="DEVICE_NOT_FOUND",t.ELECTRON_IS_NULL="ELECTRON_IS_NULL",t.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR="ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR",t.CHROME_PLUGIN_NO_RESPONSE="CHROME_PLUGIN_NO_RESPONSE",t.CHROME_PLUGIN_NOT_INSTALL="CHROME_PLUGIN_NOT_INSTALL",t.MEDIA_OPTION_INVALID="MEDIA_OPTION_INVALID",t.PERMISSION_DENIED="PERMISSION_DENIED",t.CONSTRAINT_NOT_SATISFIED="CONSTRAINT_NOT_SATISFIED",t.TRACK_IS_DISABLED="TRACK_IS_DISABLED",t.GET_VIDEO_ELEMENT_VISIBLE_ERROR="GET_VIDEO_ELEMENT_VISIBLE_ERROR",t.SHARE_AUDIO_NOT_ALLOWED="SHARE_AUDIO_NOT_ALLOWED",t.LOW_STREAM_ENCODING_ERROR="LOW_STREAM_ENCODING_ERROR",t.SET_ENCODING_PARAMETER_ERROR="SET_ENCODING_PARAMETER_ERROR",t.TRACK_STATE_UNREACHABLE="TRACK_STATE_UNREACHABLE",t.INVALID_UINT_UID_FROM_STRING_UID="INVALID_UINT_UID_FROM_STRING_UID",t.CAN_NOT_GET_PROXY_SERVER="CAN_NOT_GET_PROXY_SERVER",t.CAN_NOT_GET_GATEWAY_SERVER="CAN_NOT_GET_GATEWAY_SERVER",t.VOID_GATEWAY_ADDRESS="VOID_GATEWAY_ADDRESS",t.UID_CONFLICT="UID_CONFLICT",t.MULTI_UNILBS_RESPONSE_ERROR="MULTI_UNILBS_RESPONSE_ERROR",t.UPDATE_TICKET_FAILED="UPDATE_TICKET_FAILED",t.TOKEN_EXPIRE="TOKEN_EXPIRE",t.INVALID_LOCAL_TRACK="INVALID_LOCAL_TRACK",t.INVALID_TRACK="INVALID_TRACK",t.SENDER_NOT_FOUND="SENDER_NOT_FOUND",t.CREATE_OFFER_FAILED="CREATE_OFFER_FAILED",t.SET_ANSWER_FAILED="SET_ANSWER_FAILED",t.ICE_FAILED="ICE_FAILED",t.PC_CLOSED="PC_CLOSED",t.SENDER_REPLACE_FAILED="SENDER_REPLACE_FAILED",t.GET_LOCAL_CAPABILITIES_FAILED="GET_LOCAL_CAPABILITIES_FAILED",t.GET_LOCAL_CONNECTION_PARAMS_FAILED="GET_LOCAL_CONNECTION_PARAMS_FAILED",t.SUBSCRIBE_FAILED="SUBSCRIBE_FAILED",t.UNSUBSCRIBE_FAILED="UNSUBSCRIBE_FAILED",t.GATEWAY_P2P_LOST="GATEWAY_P2P_LOST",t.NO_ICE_CANDIDATE="NO_ICE_CANDIDATE",t.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS="CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS",t.EXIST_DISABLED_VIDEO_TRACK="EXIST_DISABLED_VIDEO_TRACK",t.INVALID_REMOTE_USER="INVALID_REMOTE_USER",t.REMOTE_USER_IS_NOT_PUBLISHED="REMOTE_USER_IS_NOT_PUBLISHED",t.CUSTOM_REPORT_SEND_FAILED="CUSTOM_REPORT_SEND_FAILED",t.CUSTOM_REPORT_FREQUENCY_TOO_HIGH="CUSTOM_REPORT_FREQUENCY_TOO_HIGH",t.FETCH_AUDIO_FILE_FAILED="FETCH_AUDIO_FILE_FAILED",t.READ_LOCAL_AUDIO_FILE_ERROR="READ_LOCAL_AUDIO_FILE_ERROR",t.DECODE_AUDIO_FILE_FAILED="DECODE_AUDIO_FILE_FAILED",t.WS_ABORT="WS_ABORT",t.WS_DISCONNECT="WS_DISCONNECT",t.WS_ERR="WS_ERR",t.EXTERNAL_SIGNAL_ABORT="EXTERNAL_SIGNAL_ABORT",t.LIVE_STREAMING_TASK_CONFLICT="LIVE_STREAMING_TASK_CONFLICT",t.LIVE_STREAMING_INVALID_ARGUMENT="LIVE_STREAMING_INVALID_ARGUMENT",t.LIVE_STREAMING_INTERNAL_SERVER_ERROR="LIVE_STREAMING_INTERNAL_SERVER_ERROR",t.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED="LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED",t.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED="LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED",t.LIVE_STREAMING_CDN_ERROR="LIVE_STREAMING_CDN_ERROR",t.LIVE_STREAMING_INVALID_RAW_STREAM="LIVE_STREAMING_INVALID_RAW_STREAM",t.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT="LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT",t.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE="LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE",t.LIVE_STREAMING_WARN_FREQUENT_REQUEST="LIVE_STREAMING_WARN_FREQUENT_REQUEST",t.WEBGL_INTERNAL_ERROR="WEBGL_INTERNAL_ERROR",t.BEAUTY_PROCESSOR_INTERNAL_ERROR="BEAUTY_PROCESSOR_INTERNAL_ERROR",t.CROSS_CHANNEL_WAIT_STATUS_ERROR="CROSS_CHANNEL_WAIT_STATUS_ERROR",t.CROSS_CHANNEL_FAILED_JOIN_SRC="CROSS_CHANNEL_FAILED_JOIN_SEC",t.CROSS_CHANNEL_FAILED_JOIN_DEST="CROSS_CHANNEL_FAILED_JOIN_DEST",t.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST="CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST",t.CROSS_CHANNEL_SERVER_ERROR_RESPONSE="CROSS_CHANNEL_SERVER_ERROR_RESPONSE",t.METADATA_OUT_OF_RANGE="METADATA_OUT_OF_RANGE",t.LOCAL_AEC_ERROR="LOCAL_AEC_ERROR",t.INVALID_PLUGIN="INVALID_PLUGIN",t.DISCONNECT_P2P="DISCONNECT_P2P",t.CONVERTING_IMAGEDATA_TO_BLOB_FAILED="CONVERTING_IMAGEDATA_TO_BLOB_FAILED",t.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED="CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED",t.INIT_DATACHANNEL_TIMEOUT="INIT_DATACHANNEL_TIMEOUT",t.CREATE_DATACHANNEL_ERROR="CREATE_DATACHANNEL_ERROR",t.DATACHANNEL_CONNECTION_TIMEOUT="DATACHANNEL_CONNECTION_TIMEOUT",t.PROHIBITED_OPERATION="PROHIBITED_OPERATION",t.IMAGE_MODERATION_UPLOAD_FAILED="IMAGE_MODERATION_UPLOAD_FAILED",t.P2P_MESSAGE_FAILED="P2P_MESSAGE_FAILED",t}({}),k=class extends Error{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",i=arguments.length>2?arguments[2]:void 0;super(e),st(this,"code",void 0),st(this,"message",void 0),st(this,"data",void 0),st(this,"name","AgoraRTCException"),this.code=t,this.message="AgoraRTCError ".concat(this.code,": ").concat(e),this.data=i}toString(){return this.data?"".concat(this.message,`
data: `).concat(JSON.stringify(this.data)):this.message}print(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"error",e=arguments.length>1?arguments[1]:void 0;return t==="error"&&(e||console).error(this.toString()),t==="warning"&&(e||console).warn(this.toString()),this}throw(t){throw this.print("error",t),this}};function Fr(t,e){if(typeof t!="boolean")throw new k(v.INVALID_PARAMS,"Invalid ".concat(e,": The value is of the boolean type."))}function Ae(t,e,i){if(!G(i).call(i,t))throw new k(v.INVALID_PARAMS,"".concat(e," can only be set as ").concat(JSON.stringify(i)))}function xt(t,e){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1e4;if(t<i||t>n||(!(arguments.length>4&&arguments[4]!==void 0)||arguments[4])&&!function(r){return typeof r=="number"&&r%1==0}(t))throw new k(v.INVALID_PARAMS,"invalid ".concat(e,": the value range is [").concat(i,", ").concat(n,"]. integer only"))}function DE(t,e){if(typeof t!="number"){if(!(t.min||t.max||t.ideal||t.exact))throw new k(v.INVALID_PARAMS,"".concat(e," is not a valid ConstrainLong"));t.min!==void 0&&xt(t.min,"".concat(e,".min"),0,1/0),t.max!==void 0&&xt(t.max,"".concat(e,".max"),1,1/0),t.exact!==void 0&&xt(t.exact,"".concat(e,".exact"),1,1/0),t.ideal!==void 0&&xt(t.ideal,"".concat(e,".ideal"),1,1/0)}else xt(t,e,1,1/0)}function Me(t,e){let i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:255,r=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4];if(t==null)throw new k(v.INVALID_PARAMS,"".concat(e||"param"," cannot be empty"));if(!oI(t,i,n,r))throw new k(v.INVALID_PARAMS,"Invalid ".concat(e||"string param",": Length of the string: [").concat(i,",").concat(n,"].").concat(r?" ASCII characters only.":""))}function Br(t,e){if(!Array.isArray(t))throw new k(v.INVALID_PARAMS,"".concat(e," should be an array"))}function re(t){return t==null}function oI(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:255,n=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];return typeof t=="string"&&t.length<=i&&t.length>=e&&(!n||function(r){if(typeof r!="string")return!1;for(let o=0;o<r.length;o+=1){const s=r.charCodeAt(o);if(s<0||s>255)return!1}return!0}(t))}var wc=function(t){return t.COVERED="COVERED",t.POSITION="POSITION",t.SIZE="SIZE",t.STYLE="STYLE",t}(wc||{}),PE=function(t){return t.UNMOUNTED="UNMOUNTED",t.INVALID_HTML_ELEMENT="INVALID_HTML_ELEMENT",t}(PE||{});const sI=new class{constructor(){st(this,"_clientSize",null),st(this,"getClientWidth",()=>document.documentElement?document.documentElement.clientWidth:document.body.clientWidth),st(this,"getClientHeight",()=>document.documentElement?document.documentElement.clientHeight:document.body.clientHeight),st(this,"getStyle",t=>window.getComputedStyle(t,null)),st(this,"checkCssVisibleProperty",t=>{var e;let i=!0;const n=this.getStyle(t),{display:r,visibility:o,opacity:s,filter:a}=n;return(r==="none"||G(e=["hidden","collapse"]).call(e,o)||Number(s)<.1)&&(i=!1),!!i&&(a&&a.split(" ").filter(c=>{var d;const l=c.split("(")[0];return G(d=["brightness","blur","opacity"]).call(d,l)}).map(c=>{const[d,l]=c.split(/\(|\)/);return[d,Number(l.match(/^[0-9\.]+/))]}).forEach(c=>{const[d,l]=c;switch(d){case"brightness":(l<.1||l>3)&&(i=!1);break;case"blur":l>3&&(i=!1);break;case"opacity":l<.1&&(i=!1)}}),i)}),st(this,"checkPropertyUpToAllParentNodes",(t,e)=>{let i=!0,n=!0;const r=s=>e(s);let o=t;for(;o&&n;)r(o)||(i=!1,n=!1),o=o.parentElement,o||(n=!1);return i}),st(this,"checkActualCssVisibleIncludeInherit",t=>this.checkPropertyUpToAllParentNodes(t,this.checkCssVisibleProperty)),st(this,"getSizeAboutClient",t=>{const{width:e,height:i,left:n,right:r,top:o,bottom:s}=t.getBoundingClientRect(),a=this.getClientWidth(),c=this.getClientHeight();return{width:e,height:i,left:n,right:r,top:o,bottom:s,clientWidth:a,clientHeight:c,clientMin:Math.min(a,c)}}),st(this,"checkActualSize",()=>{const{width:t,height:e,clientMin:i}=this._clientSize;return this.checkSizeIsVisible(t,e,i)}),st(this,"elementFromPoint",(t,e)=>document.elementFromPoint?document.elementFromPoint(t,e):null),st(this,"checkCoverForAPoint",(t,e,i)=>{const n=this.elementFromPoint(t,e);return n!==null&&n!==i}),st(this,"getPointPositionList",()=>{const{width:t,height:e,left:i,top:n}=this._clientSize,r=t/6,o=e/6,s=[],a=XN(10,6);for(let c=0;c<5;c++)for(let d=0;d<5;d++){const l=(i*a+(c===0?.1:c===4?(r*c*a-1e5)/a:r*c)*a)/a,u=(n*a+(d===0?.1:d===4?(o*d*a-1e5)/a:o*d)*a)/a;s.push({x:l,y:u})}return[...s]}),st(this,"checkElementCover",t=>this.getPointPositionList().map(e=>this.checkCoverForAPoint(e.x,e.y,t)).filter(e=>!!e).length>6),st(this,"checkSizeIsVisible",(t,e,i)=>(t>50||i/t<=10)&&(e>50||i/e<=10)),st(this,"checkSizeOfPartInClient",()=>{const{left:t,right:e,top:i,bottom:n,clientHeight:r,clientWidth:o,clientMin:s}=this._clientSize;let a,c,d,l;if(t<0)a=0;else{if(!(t<o))return!1;a=t}if(e<0)return!1;if(c=e<o?e:o,i<0)d=0;else{if(!(i<r))return!1;d=i}if(n<0)return!1;l=n<r?n:r;const u=c-a,h=l-d;return this.checkSizeIsVisible(u,h,s)}),st(this,"returnHiddenResult",t=>(this._clientSize=null,{visible:!1,reason:t})),st(this,"checkOneElementVisible",t=>{if(t instanceof HTMLElement){if(this.checkElementIsMountedOnDom(t)){if(this.checkActualCssVisibleIncludeInherit(t)){if(this._clientSize=this.getSizeAboutClient(t),this.checkElementCover(t))return this.returnHiddenResult(wc.COVERED);{const e=this.checkActualSize(),i=this.checkSizeOfPartInClient();return e&&!i?this.returnHiddenResult(wc.POSITION):e?(this._clientSize=null,{visible:!0}):this.returnHiddenResult(wc.SIZE)}}return this.returnHiddenResult(wc.STYLE)}return this.returnHiddenResult(PE.UNMOUNTED)}return this.returnHiddenResult(PE.INVALID_HTML_ELEMENT)}),st(this,"checkElementIsMountedOnDom",t=>this.checkPropertyUpToAllParentNodes(t,e=>e.nodeName.toUpperCase()!=="HTML"?e.parentElement!==null:!!document.documentElement))}};function LE(t){return new TextEncoder().encode(t)}const aI=function(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(new Uint8Array(t),0),i.set(new Uint8Array(e),t.byteLength),i},kE=t=>C(this,null,function*(){return function(e,i){let n="";return new Uint8Array(e).forEach(r=>{n+=r.toString(i).padStart(2,"0")}),n}(yield crypto.subtle.digest("SHA-256",LE(t)),16)});let $t=class{constructor(){st(this,"_events",{}),st(this,"addListener",this.on)}getListeners(t){return this._events[t]?this._events[t].map(e=>e.listener):[]}on(t,e){this._events[t]||(this._events[t]=[]);const i=this._events[t];this._indexOfListener(i,e)===-1&&i.push({listener:e,once:!1})}once(t,e){this._events[t]||(this._events[t]=[]);const i=this._events[t];this._indexOfListener(i,e)===-1&&i.push({listener:e,once:!0})}off(t,e){if(!this._events[t])return;const i=this._events[t],n=this._indexOfListener(i,e);n!==-1&&i.splice(n,1),this._events[t].length===0&&delete this._events[t]}removeAllListeners(t){t?delete this._events[t]:this._events={}}emit(t){this._events[t]||(this._events[t]=[]);const e=this._events[t].map(o=>o);for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];for(let o=0;o<e.length;o+=1){const s=e[o];s.once&&this.off(t,s.listener),s.listener.apply(this,n||[])}}safeEmit(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];[...this._events[t]||[]].forEach(r=>{r.once&&this.off(t,r.listener);try{r.listener.apply(this,i)}catch(o){console.error("safeEmit event:".concat(t," error ").concat(o==null?void 0:o.toString()))}})}_indexOfListener(t,e){let i=t.length;for(;i--;)if(t[i].listener===e)return i;return-1}},Oc=null;function cI(){if(Oc)return Oc;if(window.electron)return Oc=window.electron;if(!window.require)return null;try{return Oc=window.require("electron"),Oc}catch(t){return null}}let _e=function(t){return t.CREATE_CLIENT="createClient",t.CHECK_SYSTEM_REQUIREMENTS="checkSystemRequirements",t.SET_AREA="setArea",t.PRELOAD="PRELOAD",t.CHECK_VIDEO_TRACK_IS_ACTIVE="checkVideoTrackIsActive",t.CHECK_AUDIO_TRACK_IS_ACTIVE="checkAudioTrackIsActive",t.CREATE_MIC_AUDIO_TRACK="createMicrophoneAudioTrack",t.CREATE_CUSTOM_AUDIO_TRACK="createCustomAudioTrack",t.CREATE_BUFFER_AUDIO_TRACK="createBufferSourceAudioTrack",t.CREATE_CAM_VIDEO_TRACK="createCameraVideoTrack",t.CREATE_CUSTOM_VIDEO_TRACK="createCustomVideoTrack",t.CREATE_MIC_AND_CAM_TRACKS="createMicrophoneAndCameraTracks",t.CREATE_SCREEN_VIDEO_TRACK="createScreenVideoTrack",t.SET_ENCRYPTION_CONFIG="Client.setEncryptionConfig",t.START_PROXY_SERVER="Client.startProxyServer",t.STOP_PROXY_SERVER="Client.stopProxyServer",t.SET_PROXY_SERVER="Client.setProxyServer",t.SET_TURN_SERVER="Client.setTurnServer",t.SET_CLIENT_ROLE="Client.setClientRole",t.SET_LOW_STREAM_PARAMETER="Client.setLowStreamParameter",t.ENABLE_DUAL_STREAM="Client.enableDualStream",t.DISABLE_DUAL_STREAM="Client.disableDualStream",t.JOIN="Client.join",t.LEAVE="Client.leave",t.PUBLISH="Client.publish",t.UNPUBLISH="Client.unpublish",t.SUBSCRIBE="Client.subscribe",t.MASS_SUBSCRIBE="Client.massSubscribe",t.MASS_UNSUBSCRIBE="Client.massUnsubscribe",t.UNSUBSCRIBE="Client.unsubscribe",t.RENEW_TOKEN="Client.renewToken",t.SET_REMOTE_VIDEO_STREAM_TYPE="Client.setRemoteVideoStreamType",t.SET_STREAM_FALLBACK_OPTION="Client.setStreamFallbackOption",t.ENABLE_AUDIO_VOLUME_INDICATOR="Client.enableAudioVolumeIndicator",t.SEND_CUSTOM_REPORT_MESSAGE="Client.sendCustomReportMessage",t.INSPECT_VIDEO_CONTENT="Client.inspectVideoContent",t.STOP_INSPECT_VIDEO_CONTENT="Client.stopInspectVideoContent",t.JOIN_FALLBACK_TO_PROXY="Client._joinFallbackToProxy",t.ON_LIVE_STREAM_WARNING="Client.onLiveStreamWarning",t.ON_LIVE_STREAM_ERROR="Client.onLiveStreamingError",t.START_LIVE_STREAMING="Client.startLiveStreaming",t.SET_LIVE_TRANSCODING="Client.setLiveTranscoding",t.STOP_LIVE_STREAMING="Client.stopLiveStreaming",t.START_CHANNEL_MEDIA_RELAY="Client.startChannelMediaRelay",t.UPDATE_CHANNEL_MEDIA_RELAY="Client.updateChannelMediaRelay",t.STOP_CHANNEL_MEDIA_RELAY="Client.stopChannelMediaRelay",t.REQUEST_CONFIG_DISTRIBUTE="_config-distribute-request",t.SET_CONFIG_DISTRIBUTE="_configDistribute",t.LOCAL_TRACK_SET_MUTED="LocalTrack.setMute",t.LOCAL_AUDIO_TRACK_PLAY="LocalAudioTrack.play",t.LOCAL_AUDIO_TRACK_PLAY_IN_ELEMENT="LocalAudioTrack.playInElement",t.LOCAL_AUDIO_TRACK_STOP="LocalAudioTrack.stop",t.LOCAL_AUDIO_TRACK_SET_VOLUME="LocalAudioTrack.setVolume",t.MIC_AUDIO_TRACK_SET_DEVICE="MicrophoneAudioTrack.setDevice",t.BUFFER_AUDIO_TRACK_START="BufferSourceAudioTrack.startProcessAudioBuffer",t.BUFFER_AUDIO_TRACK_STOP="BufferSourceAudioTrack.stopProcessAudioBuffer",t.BUFFER_AUDIO_TRACK_PAUSE="BufferSourceAudioTrack.pauseProcessAudioBuffer",t.BUFFER_AUDIO_TRACK_RESUME="BufferSourceAudioTrack.resumeProcessAudioBuffer",t.BUFFER_AUDIO_TRACK_SEEK="BufferSourceAudioTrack.seekAudioBuffer",t.LOCAL_VIDEO_TRACK_PLAY="LocalVideoTrack.play",t.LOCAL_VIDEO_TRACK_STOP="LocalVideoTrack.stop",t.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE="LocalVideoTrack.getVideoElementVisibleStatus",t.LOCAL_VIDEO_TRACK_BEAUTY="LocalVideoTrack.setBeautyEffect",t.LOCAL_VIDEO_SEND_SEI_DATA="LocalVideoTrack.sendSeiData",t.CAM_VIDEO_TRACK_SET_DEVICE="CameraVideoTrack.setDevice",t.CAM_VIDEO_TRACK_SET_ENCODER_CONFIG="CameraVideoTrack.setEncoderConfiguration",t.REMOTE_VIDEO_TRACK_PLAY="RemoteVideoTrack.play",t.REMOTE_VIDEO_TRACK_STOP="RemoteVideoTrack.stop",t.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE="RemoteVideoTrack.getVideoElementVisibleStatus",t.REMOTE_AUDIO_TRACK_PLAY="RemoteAudioTrack.play",t.REMOTE_AUDIO_TRACK_STOP="RemoteAudioTrack.stop",t.REMOTE_AUDIO_SET_VOLUME="RemoteAudioTrack.setVolume",t.REMOTE_AUDIO_SET_OUTPUT_DEVICE="RemoteAudioTrack.setOutputDevice",t.GET_MEDIA_STREAM_TRACK="Track.getMediaStreamTrack",t.STREAM_TYPE_CHANGE="streamTypeChange",t.CONNECTION_STATE_CHANGE="connectionStateChange",t.LOAD_CONFIG_FROM_LOCALSTORAGE="loadConfigFromLocalStorage",t.IMAGE_MODERATION_UPLOAD="imageModerationUpload",t.REPUB_AFTER_PC_CONNECTED="repubAfterPCConnected",t}({}),oe=function(t){return t.TRACER="tracer",t}({});function dI(t){return xt(t.timeout,"config.timeout",0,1e5),xt(t.timeoutFactor,"config.timeoutFactor",0,100,!1),xt(t.maxRetryCount,"config.maxRetryConfig",0,1/0),xt(t.maxRetryTimeout,"config.maxRetryTimeout",0,1/0),!0}let FG=function(t){return t[t.AUDIENCE_LEVEL_LOW_LATENCY=1]="AUDIENCE_LEVEL_LOW_LATENCY",t[t.AUDIENCE_LEVEL_ULTRA_LOW_LATENCY=2]="AUDIENCE_LEVEL_ULTRA_LOW_LATENCY",t[t.AUDIENCE_LEVEL_SYNC_LATENCY=3]="AUDIENCE_LEVEL_SYNC_LATENCY",t}({}),bt=function(t){return t.LEAVE="LEAVE",t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.UID_BANNED="UID_BANNED",t.FALLBACK="FALLBACK",t.IP_BANNED="IP_BANNED",t.CHANNEL_BANNED="CHANNEL_BANNED",t.LICENSE_MISSING="LICENSE_MISSING",t.LICENSE_EXPIRED="LICENSE_EXPIRED",t.LICENSE_MINUTES_EXCEEDED="LICENSE_MINUTES_EXCEEDED",t.LICENSE_PERIOD_INVALID="LICENSE_PERIOD_INVALID",t.LICENSE_MULTIPLE_SDK_SERVICE="LICENSE_MULTIPLE_SDK_SERVICE",t.LICENSE_ILLEGAL="LICENSE_ILLEGAL",t.TOKEN_EXPIRE="TOKEN_EXPIRE",t}({});function Nc(t){if(!Array.isArray(t)||t.length<1)return!1;try{t.forEach(e=>{if(!e.urls)throw Error()})}catch(e){return!1}return!0}function lI(t){return Me(t.turnServerURL,"turnServerURL"),Me(t.username,"username"),Me(t.password,"password"),t.udpport&&xt(t.udpport,"udpport",1,99999,!0),t.forceturn&&Fr(t.forceturn,"forceturn"),t.security&&Fr(t.security,"security"),t.tcpport&&xt(t.tcpport,"tcpport",1,99999,!0),!0}function ME(t){return t.level!==void 0&&Ae(t.level,"level",[1,2,3]),t.delay!==void 0&&xt(t.delay,"delay",0,3e3,!0),!0}let _t=function(t){return t.PEERCONNECTION_STATE_CHANGE="peerconnection-state-change",t.AUDIO_METADATA="audio-metadata",t.CONNECTION_STATE_CHANGE="connection-state-change",t.MEDIA_RECONNECT_START="media-reconnect-start",t.MEDIA_RECONNECT_END="media-reconnect-end",t.IS_USING_CLOUD_PROXY="is-using-cloud-proxy",t.USER_JOINED="user-joined",t.USER_LEAVED="user-left",t.USER_PUBLISHED="user-published",t.USER_UNPUBLISHED="user-unpublished",t.USER_INFO_UPDATED="user-info-updated",t.CLIENT_BANNED="client-banned",t.CHANNEL_MEDIA_RELAY_STATE="channel-media-relay-state",t.CHANNEL_MEDIA_RELAY_EVENT="channel-media-relay-event",t.VOLUME_INDICATOR="volume-indicator",t.CRYPT_ERROR="crypt-error",t.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="token-privilege-will-expire",t.ON_TOKEN_PRIVILEGE_DID_EXPIRE="token-privilege-did-expire",t.NETWORK_QUALITY="network-quality",t.STREAM_TYPE_CHANGED="stream-type-changed",t.STREAM_FALLBACK="stream-fallback",t.RECEIVE_METADATA="receive-metadata",t.STREAM_MESSAGE="stream-message",t.LIVE_STREAMING_ERROR="live-streaming-error",t.LIVE_STREAMING_WARNING="live-streaming-warning",t.EXCEPTION="exception",t.ERROR="error",t.P2P_LOST="p2p_lost",t.JOIN_FALLBACK_TO_PROXY="join-fallback-to-proxy",t.CHANNEL_FALLBACK_TO_WEBSOCKET="channel-fallback-to-websocket",t.MEDIA_CONNECTION_TYPE_CHANGE="media-connection-type-change",t.PUBLISHED_USER_LIST="published-user-list",t.CONTENT_INSPECT_CONNECTION_STATE_CHANGE="content-inspect-connection-state-change",t.CONTENT_INSPECT_ERROR="content-inspect-error",t.CONTENT_INSPECT_RESULT="content-inspect-result",t.IMAGE_MODERATION_CONNECTION_STATE_CHANGE="image-moderation-connection-state-change",t}({}),Ge=function(t){return t.NETWORK_ERROR="NETWORK_ERROR",t.SERVER_ERROR="SERVER_ERROR",t.MULTI_IP="MULTI_IP",t.TIMEOUT="TIMEOUT",t.OFFLINE="OFFLINE",t.LEAVE="LEAVE",t.P2P_FAILED="P2P_FAILED",t.FALLBACK="FALLBACK",t.REGIONAL_DISTRIBUTION="REGIONAL_DISTRIBUTION",t}({}),Fi=function(t){return t.ONLINE="ONLINE",t.OFFLINE="OFFLINE",t}({}),ra=function(t){return t.NETWORK_STATE_CHANGE="NETWORK_STATE_CHANGE",t.ONLINE="ONLINE",t.OFFLINE="OFFLINE",t}({});function We(t,e){for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return t.getListeners(e).length===0?K.reject(new k(v.UNEXPECTED_ERROR,"can not emit promise")):new K((o,s)=>{t.emit(e,...n,o,s)})}function Bt(t,e){if(t.getListeners(e).length===0)return K.resolve();for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return We(t,e,...n)}function zi(t,e){if(t.getListeners(e).length===0)return null;for(var i=arguments.length,n=new Array(i>2?i-2:0),r=2;r<i;r++)n[r-2]=arguments[r];return Dc(t,e,...n)}function Dc(t,e){let i=null,n=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(t.emit(e,...o,a=>{i=a},a=>{n=a}),n!==null)throw n;if(i===null)throw new k(v.UNEXPECTED_ERROR,"handler is not sync");return i}const Ee=new class extends $t{set networkState(t){this.emit(ra.NETWORK_STATE_CHANGE,t,this._networkState),t===Fi.ONLINE?this.emit(ra.ONLINE):t===Fi.OFFLINE&&(this.onlineWaiter=new K(e=>{this.once(ra.ONLINE,()=>{this.onlineWaiter=void 0,e(Fi.ONLINE)})}),this.emit(ra.OFFLINE)),this._networkState=t}get networkState(){return this._networkState}get isOnline(){return this._networkState===Fi.ONLINE}constructor(){super(),st(this,"_moduleName","network-indicator"),st(this,"_networkState",Fi.ONLINE),st(this,"onlineWaiter",void 0),window.addEventListener("online",()=>{this.networkState=Fi.ONLINE}),window.addEventListener("offline",()=>{this.networkState=Fi.OFFLINE})}};function cu(t,e){const i=t.indexOf(e);i!==-1&&t.splice(i,1)}function oa(t){const e=[];return t.forEach(i=>{e.indexOf(i)===-1&&e.push(i)}),e}function du(t){K!==void 0?K.resolve().then(t):setTimeout(t,0)}function te(t){return JSON.parse(JSON.stringify(t))}function Jo(t){try{return te(t)}catch(e){return t}}const uI={};function _o(t,e){uI[e]||(uI[e]=!0,t())}function Qo(t){const e=window.atob(t),i=new Uint8Array(new ArrayBuffer(e.length));for(let n=0;n<e.length;n+=1)i[n]=e.charCodeAt(n);return i}function Eo(t){let e="";for(let i=0;i<t.length;i+=1)e+=String.fromCharCode(t[i]);return window.btoa(e)}function hI(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,i=new TextEncoder().encode(t);if(i.length>e)i=i.slice(0,e);else if(i.length<e){const n=new Uint8Array(e);n.set(i),i=n}return i}function pI(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const n=Tn(e).call(e,(s,a)=>s+a.length,0),r=new Uint8Array(new ArrayBuffer(n));let o=0;return e.forEach(s=>{r.set(s,o),o+=s.length}),r}function Er(t){return window.TextEncoder?new TextEncoder().encode(t).length:t.length}function _I(t){let e=0;return(/DingTalk/i.test(navigator.userAgent)||/AliApp/i.test(navigator.userAgent))&&t.realFormData&&(t=t.realFormData),t.forEach(i=>{e+=typeof i=="string"?Er(i):i.size}),e+138}function BG(t){const e=new k(v.TIMEOUT,"timeout");return new K((i,n)=>{window.setTimeout(()=>n(e),t)})}function Ue(t){return new K(e=>{window.setTimeout(e,t)})}function Gt(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:7,e=arguments.length>1?arguments[1]:void 0;const i=Math.random().toString(16).substr(2,t).toLowerCase();return i.length===t?"".concat(e).concat(i):"".concat(e).concat(i)+Gt(t-i.length,"")}function Zo(){return Gt(32,"").toUpperCase()}const lu=()=>{},EI=new class{constructor(){st(this,"fnMap",new Map)}throttleByKey(t,e,i,n){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(e)){const a=this.fnMap.get(e);if(a.threshold!==i){a.fn(...a.args),clearTimeout(a.timer);const c=window.setTimeout(()=>{const d=this.fnMap.get(e);d&&d.fn(...d.args),this.fnMap.delete(e)},i);this.fnMap.set(e,{fn:t,threshold:i,timer:c,args:o,skipFn:n})}else a.skipFn&&a.skipFn(...a.args),this.fnMap.set(e,z(z({},a),{},{fn:t,args:o,skipFn:n}))}else{const a=window.setTimeout(()=>{const c=this.fnMap.get(e);c&&c.fn(...c.args),this.fnMap.delete(e)},i);this.fnMap.set(e,{fn:t,threshold:i,timer:a,args:o,skipFn:n})}}},mI=EI.throttleByKey.bind(EI);function fI(t){return typeof t=="object"&&t!==null&&!(t instanceof RegExp)}function UE(t,e){if(!fI(t)||!fI(e)||Array.isArray(t)&&!Array.isArray(e)||!Array.isArray(t)&&Array.isArray(e))return e;if(Array.isArray(e)&&Array.isArray(t)){const i=[...t];for(let n=0;n<e.length;n++)i[n]=UE(t[n],e[n]);return i}{const i=z({},t);for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(Object.prototype.hasOwnProperty.call(t,n)?i[n]=UE(t[n],e[n]):i[n]=e[n]);return i}}function gI(t,e){let i=[0];if(i=new Array(e).fill(0),t===0)return i;let n=0;for(;t>0&&(i[n]=255&t,t>>=8,n++,n!==e););return i}function xE(t){return typeof t=="number"?t:t.exact||t.ideal||t.max||t.min||0}function VE(t){return Tn(t).call(t,(e,i)=>e+i,0)}function SI(t){const e="0123456789abcdef";function i(A){let N,O="";for(N=0;N<=3;N++)O+=e.charAt(A>>8*N+4&15)+e.charAt(A>>8*N&15);return O}function n(A,N){const O=(65535&A)+(65535&N);return(A>>16)+(N>>16)+(O>>16)<<16|65535&O}function r(A,N,O,w,L,M){return n(function(j,H){return j<<H|j>>>32-H}(n(n(N,A),n(w,M)),L),O)}function o(A,N,O,w,L,M,j){return r(N&O|~N&w,A,N,L,M,j)}function s(A,N,O,w,L,M,j){return r(N&w|O&~w,A,N,L,M,j)}function a(A,N,O,w,L,M,j){return r(N^O^w,A,N,L,M,j)}function c(A,N,O,w,L,M,j){return r(O^(N|~w),A,N,L,M,j)}const d=function(A){let N;const O=1+(A.length+8>>6),w=new Array(16*O);for(N=0;N<16*O;N++)w[N]=0;for(N=0;N<A.length;N++)w[N>>2]|=A.charCodeAt(N)<<N%4*8;return w[N>>2]|=128<<N%4*8,w[16*O-2]=8*A.length,w}(t);let l,u,h,p,g,m=1732584193,f=-271733879,T=-1732584194,R=271733878;for(l=0;l<d.length;l+=16)u=m,h=f,p=T,g=R,m=o(m,f,T,R,d[l+0],7,-680876936),R=o(R,m,f,T,d[l+1],12,-389564586),T=o(T,R,m,f,d[l+2],17,606105819),f=o(f,T,R,m,d[l+3],22,-1044525330),m=o(m,f,T,R,d[l+4],7,-176418897),R=o(R,m,f,T,d[l+5],12,1200080426),T=o(T,R,m,f,d[l+6],17,-1473231341),f=o(f,T,R,m,d[l+7],22,-45705983),m=o(m,f,T,R,d[l+8],7,1770035416),R=o(R,m,f,T,d[l+9],12,-1958414417),T=o(T,R,m,f,d[l+10],17,-42063),f=o(f,T,R,m,d[l+11],22,-1990404162),m=o(m,f,T,R,d[l+12],7,1804603682),R=o(R,m,f,T,d[l+13],12,-40341101),T=o(T,R,m,f,d[l+14],17,-1502002290),f=o(f,T,R,m,d[l+15],22,1236535329),m=s(m,f,T,R,d[l+1],5,-165796510),R=s(R,m,f,T,d[l+6],9,-1069501632),T=s(T,R,m,f,d[l+11],14,643717713),f=s(f,T,R,m,d[l+0],20,-373897302),m=s(m,f,T,R,d[l+5],5,-701558691),R=s(R,m,f,T,d[l+10],9,38016083),T=s(T,R,m,f,d[l+15],14,-660478335),f=s(f,T,R,m,d[l+4],20,-405537848),m=s(m,f,T,R,d[l+9],5,568446438),R=s(R,m,f,T,d[l+14],9,-1019803690),T=s(T,R,m,f,d[l+3],14,-187363961),f=s(f,T,R,m,d[l+8],20,1163531501),m=s(m,f,T,R,d[l+13],5,-1444681467),R=s(R,m,f,T,d[l+2],9,-51403784),T=s(T,R,m,f,d[l+7],14,1735328473),f=s(f,T,R,m,d[l+12],20,-1926607734),m=a(m,f,T,R,d[l+5],4,-378558),R=a(R,m,f,T,d[l+8],11,-2022574463),T=a(T,R,m,f,d[l+11],16,1839030562),f=a(f,T,R,m,d[l+14],23,-35309556),m=a(m,f,T,R,d[l+1],4,-1530992060),R=a(R,m,f,T,d[l+4],11,1272893353),T=a(T,R,m,f,d[l+7],16,-155497632),f=a(f,T,R,m,d[l+10],23,-1094730640),m=a(m,f,T,R,d[l+13],4,681279174),R=a(R,m,f,T,d[l+0],11,-358537222),T=a(T,R,m,f,d[l+3],16,-722521979),f=a(f,T,R,m,d[l+6],23,76029189),m=a(m,f,T,R,d[l+9],4,-640364487),R=a(R,m,f,T,d[l+12],11,-421815835),T=a(T,R,m,f,d[l+15],16,530742520),f=a(f,T,R,m,d[l+2],23,-995338651),m=c(m,f,T,R,d[l+0],6,-198630844),R=c(R,m,f,T,d[l+7],10,1126891415),T=c(T,R,m,f,d[l+14],15,-1416354905),f=c(f,T,R,m,d[l+5],21,-57434055),m=c(m,f,T,R,d[l+12],6,1700485571),R=c(R,m,f,T,d[l+3],10,-1894986606),T=c(T,R,m,f,d[l+10],15,-1051523),f=c(f,T,R,m,d[l+1],21,-2054922799),m=c(m,f,T,R,d[l+8],6,1873313359),R=c(R,m,f,T,d[l+15],10,-30611744),T=c(T,R,m,f,d[l+6],15,-1560198380),f=c(f,T,R,m,d[l+13],21,1309151649),m=c(m,f,T,R,d[l+4],6,-145523070),R=c(R,m,f,T,d[l+11],10,-1120210379),T=c(T,R,m,f,d[l+2],15,718787259),f=c(f,T,R,m,d[l+9],21,-343485551),m=n(m,u),f=n(f,h),T=n(T,p),R=n(R,g);return i(m)+i(f)+i(T)+i(R)}let jG=1,TI=console,qe=class{static setLogger(t){TI=t}constructor(t,e){st(this,"id",void 0),st(this,"lockingPromise",K.resolve()),st(this,"locks",0),st(this,"name",""),st(this,"lockId",void 0),this.lockId=jG++,t&&(this.name=t),e&&(this.id=e),this.logger("created")}logger(t,e){const i=(this.id?"[".concat(this.id,"]"):"")+"[lock-".concat(this.name,"-").concat(this.lockId,"]"),n=t==="created"?"is ".concat(t,"."):"is ".concat(t,", current queue ").concat(this.locks,". ").concat(e!=null?e:"");TI.debug("".concat(i," ").concat(n))}setId(t){this.id=t}get isLocked(){return this.locks>0}lock(t){let e;this.locks+=1,this.logger("locked",t);const i=new K(r=>{e=()=>{this.locks-=1,this.logger("unlocked",t),r()}}),n=this.lockingPromise.then(()=>e);return this.lockingPromise=this.lockingPromise.then(()=>i),n}};function sa(t,e){return function(i,n,r){const o=r.value;if(typeof o!="function")throw new Error("Cannot use mutex on object property.");return r.value=function(){return C(this,arguments,function*(){const s=this[e];if(!s)throw new Error("mutex property key ".concat(e," doesn't exist on ").concat(t));const a=yield s.lock("From ".concat(t,".").concat(n));try{for(var c=arguments.length,d=new Array(c),l=0;l<c;l++)d[l]=arguments[l];return yield o.apply(this,d)}finally{a()}})},r}}const ge={timeout:500,timeoutFactor:1.5,maxRetryCount:1/0,maxRetryTimeout:1e4};function FE(t,e){const i=Math.floor(e.timeout*Math.pow(e.timeoutFactor,t));return Math.min(e.maxRetryTimeout,i)}function Jn(t,e,i,n){const r=Object.assign({},ge,n);let o=r.timeout;const s=()=>C(this,null,function*(){yield function(d){return new K(l=>{window.setTimeout(l,d)})}(o),o*=r.timeoutFactor,o=Math.min(r.maxRetryTimeout,o)});let a=!1;const c=new K((d,l)=>C(this,null,function*(){e=e||(()=>!1),i=i||(()=>!0);for(let u=0;u<r.maxRetryCount;u+=1){if(a)return l(new k(v.OPERATION_ABORTED));try{const h=yield t();if(!e(h,u)||u+1===r.maxRetryCount)return d(h);yield s()}catch(h){if(!i(h,u)||u+1===r.maxRetryCount)return l(h);yield s()}}}));return c.cancel=()=>a=!0,c}let uu,RI=class{constructor(t){st(this,"input",[]),st(this,"size",void 0),this.size=t}add(t){this.input.push(t),this.input.length>this.size&&this.input.splice(0,1)}mean(){var t;return this.input.length===0?0:Tn(t=this.input).call(t,(e,i)=>e+i)/this.input.length}},hu=0,BE=0;function jE(t,e,i,n){return new K((r,o)=>{e.responseType=e.responseType||"json",e.data&&!i?(e.data=JSON.stringify(e.data),hu+=Er(e.data)):i&&(e.data.size?hu+=e.data.size:e.data instanceof FormData?hu+=_I(e.data):hu+=Er(JSON.stringify(e.data))),e.headers=e.headers||{},e.headers["Content-Type"]=e.headers["Content-Type"]||"application/json",e.method="POST",e.url=t,Ti.request(e).then(s=>{typeof s.data=="string"?BE+=Er(s.data):s.data instanceof ArrayBuffer||s.data instanceof Uint8Array?BE+=s.data.byteLength:BE+=Er(JSON.stringify(s.data)),r(s.data)}).catch(s=>{Ti.isCancel(s)?o(new k(v.OPERATION_ABORTED,"cancel token canceled")):s.code==="ECONNABORTED"?o(new k(v.NETWORK_TIMEOUT,s.message)):s.response?o(new k(v.NETWORK_RESPONSE_ERROR,s.response.status)):o(new k(v.NETWORK_ERROR,s.message))})})}function GG(t,e){return C(this,null,function*(){const i=new Blob([e.data],{type:"buffer"});return yield jE(t,z(z({},e),{},{data:i,headers:{"Content-Type":"application/octet-stream"}}),!0)})}const vI=()=>window.isSecureContext!==void 0;function wn(t){if(Array.isArray(t))return t.map(i=>i);if(!CI(t))return t;const e={};for(const i in t){const n=t[i];CI(n)||Array.isArray(n)?e[i]=wn(n):e[i]=n}return e}function CI(t){return!(typeof t!="object"||Array.isArray(t)||!t)}let GE=class{constructor(t){st(this,"input",[]),st(this,"size",void 0),this.size=t}add(t){this.input.push(t),this.input.length>this.size&&this.input.splice(0,1)}diffMean(){return this.input.length===0?0:(this.input[this.input.length-1]-this.input[0])/this.input.length}};const mr={address:"unknown",candidateType:"unknown",id:"unknown",port:0,priority:0,protocol:"unknown",type:"unknown"},Pc={timestamp:0,bitrate:{actualEncoded:0,transmit:0},sendPacketLossRate:0,recvPacketLossRate:0,videoRecv:[],videoSend:[],audioRecv:[],audioSend:[],selectedCandidatePair:{id:"unknown",localCandidate:mr,remoteCandidate:mr},updateInterval:0},yI={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},II={firsCount:0,nacksCount:0,plisCount:0,frameCount:0,bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0,qpSumPerFrame:0},AI={bytes:0,packets:0,packetsLost:0,packetLostRate:0,ssrc:0,rttMs:0,jitterMs:0},bI={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 WE=class{constructor(t,e){st(this,"onFirstVideoReceived",void 0),st(this,"onFirstVideoDecoded",void 0),st(this,"onFirstAudioReceived",void 0),st(this,"onFirstVideoDecodedTimeout",void 0),st(this,"onFirstAudioDecoded",void 0),st(this,"onSelectedLocalCandidateChanged",void 0),st(this,"onSelectedRemoteCandidateChanged",void 0),st(this,"videoIsReady",!1),st(this,"videoIsReady2",{}),st(this,"pc",void 0),st(this,"options",void 0),st(this,"intervalTimer",void 0),st(this,"stats",wn(Pc)),st(this,"isFirstVideoReceived",{}),st(this,"isFirstVideoDecoded",{}),st(this,"isFirstAudioReceived",{}),st(this,"isFirstAudioDecoded",{}),st(this,"isFirstVideoDecodedTimeout",{}),st(this,"lossRateWindowStats",[]),this.pc=t,this.options=e,this.intervalTimer=window.setInterval(()=>C(this,null,function*(){this.updateStats()}),this.options.updateInterval)}getStats(){return this.stats}getSelectedCandidatePair(){return new K(t=>{t({local:z({},mr),remote:z({},mr)})})}setVideoIsReady(t){this.videoIsReady=t}setVideoIsReady2(t,e){this.videoIsReady2[t]=e}getVideoIsReady(t){return this.videoIsReady2[t]||!1}setIsFirstAudioDecoded(t){}destroy(){window.clearInterval(this.intervalTimer),this.pc=void 0}calcLossRate(t){this.lossRateWindowStats.push(t),this.lossRateWindowStats.length>this.options.lossRateInterval&&this.lossRateWindowStats.splice(0,1);const e=this.lossRateWindowStats.length,i=["videoSend","audioSend","videoRecv","audioRecv"];let n=0,r=0,o=0,s=0;for(const a of i)t[a].forEach((c,d)=>{if(!this.lossRateWindowStats[e-1][a][d]||!this.lossRateWindowStats[0][a][d])return;const l=this.lossRateWindowStats[e-1][a][d].packets-this.lossRateWindowStats[0][a][d].packets,u=this.lossRateWindowStats[e-1][a][d].packetsLost-this.lossRateWindowStats[0][a][d].packetsLost;a==="videoSend"||a==="audioSend"?(n+=l,o+=u):(r+=l,s+=u),Number.isNaN(l)||Number.isNaN(l)?c.packetLostRate=0:c.packetLostRate=l<=0||u<=0?0:u/(l+u)});t.sendPacketLossRate=n<=0||o<=0?0:o/(n+o),t.recvPacketLossRate=r<=0||s<=0?0:s/(r+s)}},WG=class extends WE{constructor(){super(...arguments),st(this,"_stats",Pc),st(this,"lastDecodeVideoReceiverStats",new Map)}updateStats(){return C(this,null,function*(){const t=yield this._getStats(),e=this.statsResponsesToObjects(t);this._stats=wn(Pc);const i=e.filter(r=>r.type==="ssrc");this.processSSRCStats(i);const n=e.find(r=>r.type==="VideoBwe");n&&this.processBandwidthStats(n),this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats})}processBandwidthStats(t){this._stats.bitrate={actualEncoded:Number(t.googActualEncBitrate),targetEncoded:Number(t.googTargetEncBitrate),retransmit:Number(t.googRetransmitBitrate),transmit:Number(t.googTransmitBitrate)},this._stats.sendBandwidth=Number(t.googAvailableSendBandwidth)}processSSRCStats(t){t.forEach(e=>{var i;const n=G(i=e.id).call(i,"send");switch("".concat(e.mediaType,"_").concat(n?"send":"recv")){case"video_send":{const r=wn(II);r.codec=e.googCodecName,r.adaptionChangeReason="none",e.googCpuLimitedResolution&&(r.adaptionChangeReason="cpu"),e.googBandwidthLimitedResolution&&(r.adaptionChangeReason="bandwidth"),r.avgEncodeMs=Number(e.googAvgEncodeMs),r.inputFrame={width:Number(e.googFrameWidthInput)||Number(e.googFrameWidthSent),height:Number(e.googFrameHeightInput)||Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},r.sentFrame={width:Number(e.googFrameWidthSent),height:Number(e.googFrameHeightSent),frameRate:Number(e.googFrameRateInput)},r.firsCount=Number(e.googFirReceived),r.nacksCount=Number(e.googNacksReceived),r.plisCount=Number(e.googPlisReceived),r.frameCount=Number(e.framesEncoded),r.bytes=Number(e.bytesSent),r.packets=Number(e.packetsSent),r.packetsLost=Number(e.packetsLost),r.ssrc=Number(e.ssrc),r.rttMs=Number(e.googRtt||0),this._stats.videoSend.push(r),this._stats.rtt=r.rttMs;break}case"video_recv":{const r=wn(yI),o=this.lastDecodeVideoReceiverStats.get(Number(e.ssrc));if(r.codec=e.googCodecName,r.targetDelayMs=Number(e.googTargetDelayMs),r.renderDelayMs=Number(e.googRenderDelayMs),r.currentDelayMs=Number(e.googCurrentDelayMs),r.minPlayoutDelayMs=Number(e.googMinPlayoutDelayMs),r.decodeMs=Number(e.googDecodeMs),r.maxDecodeMs=Number(e.googMaxDecodeMs),r.receivedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateReceived)},r.decodedFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateDecoded)},r.decodeFrameRate=Number(e.googFrameRateDecoded),r.outputFrame={width:Number(e.googFrameWidthReceived),height:Number(e.googFrameHeightReceived),frameRate:Number(e.googFrameRateOutput)},r.jitterBufferMs=Number(e.googJitterBufferMs),r.firsCount=Number(e.googFirsSent),r.nacksCount=Number(e.googNacksSent),r.plisCount=Number(e.googPlisSent),r.framesDecodeCount=Number(e.framesDecoded),r.bytes=Number(e.bytesReceived),r.packets=Number(e.packetsReceived),r.packetsLost=Number(e.packetsLost),r.ssrc=Number(e.ssrc),r.packets>0&&!this.isFirstVideoReceived[r.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(r.ssrc),this.isFirstVideoReceived[r.ssrc]=!0),r.framesDecodeCount>0&&!this.isFirstVideoDecoded[r.ssrc]&&(this.onFirstVideoDecoded&&this.onFirstVideoDecoded(r.ssrc,r.decodedFrame.width,r.decodedFrame.height),this.isFirstVideoDecoded[r.ssrc]=!0),o){const s=o.stats,a=Date.now()-o.lts;r.framesDecodeFreezeTime=s.framesDecodeFreezeTime,r.framesDecodeInterval=s.framesDecodeInterval,r.framesDecodeCount>s.framesDecodeCount&&this.isFirstVideoDecoded[r.ssrc]?(o.lts=Date.now(),r.framesDecodeInterval=a,r.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(e.ssrc,10))?r.framesDecodeFreezeTime+=r.framesDecodeInterval:this.setVideoIsReady2(parseInt(e.ssrc,10),!0))):r.framesDecodeCount<o.stats.framesDecodeCount&&(r.framesDecodeInterval=0)}this.lastDecodeVideoReceiverStats.set(r.ssrc,{stats:z({},r),lts:Date.now()}),this._stats.videoRecv.push(r);break}case"audio_recv":{const r=wn(bI);r.codec=e.googCodecName,r.outputLevel=Math.abs(Number(e.audioOutputLevel))/32767,r.decodingCNG=Number(e.googDecodingCNG),r.decodingCTN=Number(e.googDecodingCTN),r.decodingCTSG=Number(e.googDecodingCTSG),r.decodingNormal=Number(e.googDecodingNormal),r.decodingPLC=Number(e.googDecodingPLC),r.decodingPLCCNG=Number(e.googDecodingPLCCNG),r.expandRate=Number(e.googExpandRate),r.accelerateRate=Number(e.googAccelerateRate),r.preemptiveExpandRate=Number(e.googPreemptiveExpandRate),r.secondaryDecodedRate=Number(e.googSecondaryDecodedRate),r.speechExpandRate=Number(e.googSpeechExpandRate),r.preferredJitterBufferMs=Number(e.googPreferredJitterBufferMs),r.jitterBufferMs=Number(e.googJitterBufferMs),r.jitterMs=Number(e.googJitterReceived),r.bytes=Number(e.bytesReceived),r.packets=Number(e.packetsReceived),r.packetsLost=Number(e.packetsLost),r.ssrc=Number(e.ssrc),r.receivedFrames=Number(e.googDecodingCTN)||Number(e.packetsReceived),r.droppedFrames=Number(e.googDecodingPLC)+Number(e.googDecodingPLCCNG)||Number(e.packetsLost),r.receivedFrames>0&&!this.isFirstAudioReceived[r.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(r.ssrc),this.isFirstAudioReceived[r.ssrc]=!0),r.decodingNormal>0&&!this.isFirstAudioDecoded[r.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(r.ssrc),this.isFirstAudioDecoded[r.ssrc]=!0),this._stats.audioRecv.push(r);break}case"audio_send":{const r=wn(AI);r.codec=e.googCodecName,r.inputLevel=Math.abs(Number(e.audioInputLevel))/32767,r.aecReturnLoss=Number(e.googEchoCancellationReturnLoss||0),r.aecReturnLossEnhancement=Number(e.googEchoCancellationReturnLossEnhancement||0),r.residualEchoLikelihood=Number(e.googResidualEchoLikelihood||0),r.residualEchoLikelihoodRecentMax=Number(e.googResidualEchoLikelihoodRecentMax||0),r.bytes=Number(e.bytesSent),r.packets=Number(e.packetsSent),r.packetsLost=Number(e.packetsLost),r.ssrc=Number(e.ssrc),r.rttMs=Number(e.googRtt||0),this._stats.rtt=r.rttMs,this._stats.audioSend.push(r);break}}})}_getStats(){return new K((t,e)=>{this.pc.getStats(t,e)})}statsResponsesToObjects(t){const e=[];return t.result().forEach(i=>{const n={id:i.id,timestamp:i.timestamp.valueOf().toString(),type:i.type};i.names().forEach(r=>{n[r]=i.stat(r)}),e.push(n)}),e}},Lc=function(t){return t.BANDWIDTH="bandwidth",t.CPU="cpu",t.NONE="none",t.OTHER="other",t}({}),pu=function(t){return t.L1T1="L1T1",t.L1T2="L1T2",t.L1T3="L1T3",t.L1T3_KEY="L1T3_KEY",t.L2T1_KEY="L2T1_KEY",t.L2T2_KEY="L2T2_KEY",t.L2T3_KEY="L2T3_KEY",t.L3T1_KEY="L3T1_KEY",t.L3T2_KEY="L3T2_KEY",t.L3T3_KEY="L3T3_KEY",t}({}),HE=function(t){return t[t.new=0]="new",t[t.connecting=1]="connecting",t[t.connected=2]="connected",t[t.disconnected=3]="disconnected",t[t.failed=4]="failed",t[t.closed=5]="closed",t}({}),Xi=function(t){return t.CERTIFICATE="certificate",t.CODEC="codec",t.CANDIDATE_PAIR="candidate-pair",t.LOCAL_CANDIDATE="local-candidate",t.REMOTE_CANDIDATE="remote-candidate",t.INBOUND="inbound-rtp",t.TRACK="track",t.OUTBOUND="outbound-rtp",t.PC="peer-connection",t.REMOTE_INBOUND="remote-inbound-rtp",t.REMOTE_OUTBOUND="remote-outbound-rtp",t.TRANSPORT="transport",t.CSRC="csrc",t.DATA_CHANNEL="data-channel",t.STREAM="stream",t.SENDER="sender",t.RECEIVER="receiver",t}({});var aa=function(t){return t[t.kNone=1]="kNone",t[t.kMillisecondsFromSeconds=1e3]="kMillisecondsFromSeconds",t[t.kBytesToBits=8]="kBytesToBits",t}(aa||{});function kc(t,e,i,n){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:aa.kNone;if(!e)return;const o=Number(e[i]);if(typeof o!="number")return;const s=Number(e[n]);if(typeof s!="number")return;if(!t)return s?o/s*r:void 0;const a=Number(t[i]);if(typeof a!="number")return;const c=Number(t[n]);if(typeof c!="number")return;const d=s-c;return d?(o-a)/d*r:void 0}let wI=class extends WE{constructor(){super(...arguments),st(this,"_stats",Pc),st(this,"report",void 0),st(this,"lastDecodeVideoReceiverStats",new Map),st(this,"lastVideoFramesRecv",new Map),st(this,"lastVideoFramesSent",new Map),st(this,"lastVideoFramesDecode",new Map),st(this,"lastVideoFramesOutput",new Map),st(this,"lastVideoJBDelay",new Map),st(this,"lastAudioJBDelay",new Map),st(this,"mediaBytesSent",new Map),st(this,"mediaBytesRetransmit",new Map),st(this,"mediaBytesTargetEncode",new Map),st(this,"lastDecodeAudioReceiverStats",new Map),st(this,"lastAudioConcealment",new Map),st(this,"lastEncoderMs",new Map)}updateStats(){return C(this,null,function*(){this.report=yield this.pc.getStats(),this._stats=wn(Pc),this.report.forEach(t=>{switch(t.type){case Xi.OUTBOUND:case Xi.INBOUND:{const e=t.mediaType||t.kind,i=!e&&"frameWidth"in t,n=!e&&!("frameWidth"in t);t.type===Xi.OUTBOUND?e==="audio"||n?this.processAudioOutboundStats(t):(e==="video"||i)&&this.processVideoOutboundStats(t):t.type===Xi.INBOUND&&(e==="audio"||n?this.processAudioInboundStats(t):(e==="video"||i)&&this.processVideoInboundStats(t));break}case Xi.TRANSPORT:{const e=this.report.get(t.selectedCandidatePairId);e&&this.processCandidatePairStats(e);break}case Xi.CANDIDATE_PAIR:t.selected&&this.processCandidatePairStats(t)}}),this.updateSendBitrate(),this._stats.updateInterval=Date.now()-this.stats.timestamp,this._stats.timestamp=Date.now(),this.calcLossRate(this._stats),this.stats=this._stats})}getSelectedCandidatePair(){return C(this,null,function*(){const t=yield this.pc.getStats(),e={local:z({},mr),remote:z({},mr)};return t.forEach(i=>{let n;if(i.type===Xi.TRANSPORT&&(n=t.get(i.selectedCandidatePairId)),i.type===Xi.CANDIDATE_PAIR&&i.selected&&(n=i),n){const r=(o,s)=>{o.type=s.type,o.id=s.id,s.address&&(o.address=s.address),s.candidateType&&(o.candidateType=s.candidateType),s.port&&(o.port=s.port),s.priority&&(o.priority=s.priority),s.protocol&&(o.protocol=s.protocol),s.relayProtocol&&(o.relayProtocol=s.relayProtocol)};if(n.localCandidateId){const o=t.get(n.localCandidateId);o&&r(e.local,o)}if(n.remoteCandidateId){const o=t.get(n.remoteCandidateId);o&&r(e.remote,o)}}}),e})}processCandidatePairStats(t){if(this._stats.sendBandwidth=t.availableOutgoingBitrate||0,t.currentRoundTripTime&&(this._stats.rtt=1e3*t.currentRoundTripTime),this._stats.videoSend.forEach(e=>{t.currentRoundTripTime&&(e.rttMs=1e3*t.currentRoundTripTime)}),this._stats.audioSend.forEach(e=>{t.currentRoundTripTime&&(e.rttMs=1e3*t.currentRoundTripTime)}),this._stats.selectedCandidatePair.id=t.id,t.localCandidateId){const e=this.report.get(t.localCandidateId);e&&this.processCandidateStats(e)}if(t.remoteCandidateId){const e=this.report.get(t.remoteCandidateId);e&&this.processCandidateStats(e)}}processCandidateStats(t){let e;t.type===Xi.LOCAL_CANDIDATE&&(e=this._stats.selectedCandidatePair.localCandidate),t.type===Xi.REMOTE_CANDIDATE&&(e=this._stats.selectedCandidatePair.remoteCandidate),e&&(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),t.type===Xi.LOCAL_CANDIDATE&&this.stats.selectedCandidatePair.localCandidate.id!==e.id&&this.onSelectedLocalCandidateChanged&&this.onSelectedLocalCandidateChanged(z({},e),z({},this.stats.selectedCandidatePair.localCandidate)),t.type===Xi.REMOTE_CANDIDATE&&this.stats.selectedCandidatePair.remoteCandidate.id!==e.id&&this.onSelectedRemoteCandidateChanged&&this.onSelectedRemoteCandidateChanged(z({},e),z({},this.stats.selectedCandidatePair.remoteCandidate)))}processAudioInboundStats(t){let e=this._stats.audioRecv.find(n=>n.ssrc===t.ssrc);e||(e=wn(bI),this._stats.audioRecv.push(e)),e.ssrc=t.ssrc,e.packets=t.packetsReceived,e.packetsLost=t.packetsLost,e.packetsDiscarded=t.packetsDiscarded,e.bytes=t.bytesReceived,e.jitterMs=1e3*t.jitter,e.retransmittedBytesReceived=t.retransmittedBytesReceived,e.retransmittedPacketsReceived=t.retransmittedPacketsReceived,e.totalProcessingDelay=t.totalProcessingDelay,e.jitterBufferEmittedCount=t.jitterBufferEmittedCount;const i=this.lastDecodeAudioReceiverStats.get(e.ssrc);e.avgProcessingDelayMs=kc(i,e,"totalProcessingDelay","jitterBufferEmittedCount",aa.kMillisecondsFromSeconds),this.processAudioTrackReceiverStats(t,t.trackId,e),this.calculateAudioFreeze(e,i,t),t.codecId&&(e.codec=this.getCodecFromCodecStats(t.codecId)),e.receivedFrames||(e.receivedFrames=t.packetsReceived),e.droppedFrames||(e.droppedFrames=t.packetsLost),e.receivedFrames>0&&!this.isFirstAudioReceived[e.ssrc]&&(this.onFirstAudioReceived&&this.onFirstAudioReceived(e.ssrc),this.isFirstAudioReceived[e.ssrc]=!0),e.outputLevel&&e.outputLevel>0&&!this.isFirstAudioDecoded[e.ssrc]&&(this.onFirstAudioDecoded&&this.onFirstAudioDecoded(e.ssrc),this.isFirstAudioDecoded[e.ssrc]=!0),typeof t.concealedSamples=="number"&&(e.concealedSamples=t.concealedSamples),this.lastDecodeAudioReceiverStats.set(e.ssrc,z({},e))}calculateAudioFreeze(t,e,i){const n=this.lastAudioConcealment.get(t.ssrc);if(e!=null&&n!=null){const r=n.lts,o=i.timestamp,s=o-r;if(s<=0)return;const a=t.concealedSamples-e.concealedSamples-0,c=n.nonSilent+a,d=t.totalSamplesReceived-e.totalSamplesReceived;if(d<=0)return;const l=80*d/s,u=200*d/s,h=s/d;let p=0;t.freezeSamples80=e.freezeSamples80,t.freezeMs80=e.freezeMs80,c>l&&(n.plc80>0?(t.freezeSamples80+=a,t.freezeMs80+=Math.round(a*h)):(t.freezeSamples80+=c,t.freezeMs80+=Math.round(c*h)),p=n.plc80+1);let g=0;t.freezeSamples200=e.freezeSamples200,t.freezeMs200=e.freezeMs200,c>u&&(n.plc200>0?(t.freezeSamples200+=a,t.freezeMs200+=Math.round(a*h)):(t.freezeSamples200+=c,t.freezeMs200+=Math.round(c*h)),g=n.plc200+1),this.lastAudioConcealment.set(t.ssrc,{nonSilent:a,lts:o,plc80:p,plc200:g})}else t.freezeSamples80=0,t.freezeSamples200=0,t.freezeMs80=0,t.freezeMs200=0,this.lastAudioConcealment.set(t.ssrc,{nonSilent:0,lts:i.timestamp,plc80:0,plc200:0})}processVideoInboundStats(t){let e=this._stats.videoRecv.find(s=>s.ssrc===t.ssrc);e||(e=wn(yI),this._stats.videoRecv.push(e)),e.ssrc=t.ssrc,e.packets=t.packetsReceived,e.packetsLost=t.packetsLost,e.bytes=t.bytesReceived,e.firsCount=t.firCount,e.nacksCount=t.nackCount,e.plisCount=t.pliCount,e.framesDecodeCount=t.framesDecoded,e.framesDroppedCount=t.framesDropped,e.totalInterFrameDelay=t.totalInterFrameDelay,e.totalSquaredInterFrameDelay=t.totalSquaredInterFrameDelay,e.totalFreezesDuration=t.totalFreezesDuration,e.totalProcessingDelay=t.totalProcessingDelay,e.packetsDiscarded=t.packetsDiscarded,e.framesAssembledFromMultiplePackets=t.framesAssembledFromMultiplePackets,e.totalAssemblyTime=t.totalAssemblyTime,e.keyFramesDecoded=t.keyFramesDecoded,e.retransmittedBytesReceived=t.retransmittedBytesReceived,e.retransmittedPacketsReceived=t.retransmittedPacketsReceived;const i=this.lastDecodeVideoReceiverStats.get(e.ssrc),n=this.lastVideoFramesDecode.get(e.ssrc),r=this.lastVideoFramesOutput.get(e.ssrc),o=Date.now();if(e.framesDecodeCount>0&&!this.isFirstVideoDecoded[e.ssrc]){const s=e.decodedFrame?e.decodedFrame.width:0,a=e.decodedFrame?e.decodedFrame.height:0;this.onFirstVideoDecoded&&this.onFirstVideoDecoded(e.ssrc,s,a),this.isFirstVideoDecoded[e.ssrc]=!0}if(i){const s=i.stats,a=o-i.lts;e.framesDecodeFreezeTime=s.framesDecodeFreezeTime,e.framesDecodeInterval=s.framesDecodeInterval,!this.isFirstVideoDecoded[e.ssrc]&&a>this.options.firstVideoDecodedTimeout&&!this.isFirstVideoDecodedTimeout[e.ssrc]&&(this.onFirstVideoDecodedTimeout&&this.onFirstVideoDecodedTimeout(e.ssrc),this.isFirstVideoDecodedTimeout[e.ssrc]=!0),e.framesDecodeCount>s.framesDecodeCount&&this.isFirstVideoDecoded[e.ssrc]?(i.lts=Date.now(),e.framesDecodeInterval=a,e.framesDecodeInterval>=this.options.freezeRateLimit&&(this.getVideoIsReady(parseInt(t.ssrc))?e.framesDecodeFreezeTime+=e.framesDecodeInterval:this.setVideoIsReady2(parseInt(t.ssrc,10),!0))):e.framesDecodeCount<s.framesDecodeCount&&(e.framesDecodeInterval=0),t.framesDecoded&&t.qpSum&&(i.stats.framesDecodeCount>t.framesDecoded?e.qpSumPerFrame=t.qpSum/t.framesDecoded:e.qpSumPerFrame=(t.qpSum-i.qpSum)/(t.framesDecoded-i.stats.framesDecodeCount))}t.totalDecodeTime&&(e.decodeMs=1e3*t.totalDecodeTime,e.avgDecodeMs=kc(i==null?void 0:i.stats,e,"decodeMs","framesDecodeCount")),e.avgProcessingDelayMs=kc(i==null?void 0:i.stats,e,"totalProcessingDelay","framesDecodeCount",aa.kMillisecondsFromSeconds),e.avgFramesAssembledFromMultiplePacketsMs=kc(i==null?void 0:i.stats,e,"totalAssemblyTime","framesAssembledFromMultiplePackets",aa.kMillisecondsFromSeconds),e.avgInterFrameDelayMs=kc(i==null?void 0:i.stats,e,"totalInterFrameDelay","framesDecodeCount",aa.kMillisecondsFromSeconds),n&&o-n.lts>=800?(e.decodeFrameRate=Math.round((e.framesDecodeCount-n.count)/((o-n.lts)/1e3)),this.lastVideoFramesDecode.set(e.ssrc,{count:e.framesDecodeCount,lts:o,rate:e.decodeFrameRate})):n?e.decodeFrameRate=n.rate:this.lastVideoFramesDecode.set(e.ssrc,{count:e.framesDecodeCount,lts:o,rate:0}),e.framesDroppedCount&&t.framesReceived&&(r&&o-r.lts>=800?(e.outputFrameRate=Math.round((t.framesReceived-e.framesDroppedCount-r.count)/((o-r.lts)/1e3)),this.lastVideoFramesOutput.set(e.ssrc,{count:t.framesReceived-e.framesDroppedCount,lts:o,rate:Math.max(e.outputFrameRate,0)})):r?e.outputFrameRate=r.rate:this.lastVideoFramesOutput.set(e.ssrc,{count:t.framesReceived-e.framesDroppedCount,lts:o,rate:0})),this.processVideoTrackReceiverStats(t,t.trackId,e),t.codecId&&(e.codec=this.getCodecFromCodecStats(t.codecId)),t.framerateMean&&(e.framesRateFirefox=t.framerateMean),e.packets>0&&!this.isFirstVideoReceived[e.ssrc]&&(this.onFirstVideoReceived&&this.onFirstVideoReceived(e.ssrc),this.isFirstVideoReceived[e.ssrc]=!0),this.lastDecodeVideoReceiverStats.set(e.ssrc,{stats:z({},e),lts:i?i.lts:Date.now(),qpSum:t.qpSum})}processVideoOutboundStats(t){let e=this._stats.videoSend.find(n=>n.ssrc===t.ssrc);e||(e=wn(II),this._stats.videoSend.push(e));const i=this.mediaBytesSent.get(t.ssrc);if(i)i.add(t.bytesSent);else{const n=new GE(10);n.add(t.bytesSent),this.mediaBytesSent.set(t.ssrc,n)}if(t.retransmittedBytesSent!==void 0){const n=this.mediaBytesRetransmit.get(t.ssrc);if(n)n.add(t.retransmittedBytesSent);else{const r=new GE(10);r.add(t.retransmittedBytesSent),this.mediaBytesRetransmit.set(t.ssrc,r)}}if(t.totalEncodedBytesTarget){const n=this.mediaBytesTargetEncode.get(t.ssrc);if(n)n.add(t.totalEncodedBytesTarget);else{const r=new GE(10);r.add(t.totalEncodedBytesTarget),this.mediaBytesTargetEncode.set(t.ssrc,r)}}if(e.ssrc=t.ssrc,e.bytes=t.bytesSent,e.packets=t.packetsSent,e.firsCount=t.firCount,e.nacksCount=t.nackCount,e.plisCount=t.pliCount,e.frameCount=t.framesEncoded,e.adaptionChangeReason=t.qualityLimitationReason,e.scalabilityMode=t.scalabilityMode,e.retransmittedBytesSent=t.retransmittedBytesSent,e.retransmittedPacketsSent=t.retransmittedPacketsSent,e.hugeFramesSent=t.hugeFramesSent,e.keyFramesEncoded=t.keyFramesEncoded,e.targetBitrate=t.targetBitrate,t.totalEncodeTime&&t.framesEncoded){const n=this.lastEncoderMs.get(t.ssrc);if(!n||n.lastFrameCount>t.framesEncoded)e.avgEncodeMs=1e3*t.totalEncodeTime/t.framesEncoded;else{const r=t.framesEncoded-n.lastFrameCount,o=t.totalEncodeTime-n.lastEncoderTime;e.avgEncodeMs=1e3*o/r}}if(t.framesEncoded&&t.qpSum){const n=this.lastEncoderMs.get(t.ssrc);!n||n.lastFrameCount>t.framesEncoded?e.qpSumPerFrame=t.qpSum/t.framesEncoded:e.qpSumPerFrame=(t.qpSum-n.lastQpSum)/(t.framesEncoded-n.lastFrameCount)}if(this.lastEncoderMs.set(t.ssrc,{lastFrameCount:t.framesEncoded,lastEncoderTime:t.totalEncodeTime,lastQpSum:t.qpSum,lts:Date.now()}),t.codecId&&(e.codec=this.getCodecFromCodecStats(t.codecId)),t.mediaSourceId&&this.processVideoMediaSource(t.mediaSourceId,e),this.processVideoTrackSenderStats(t,t.trackId,e),t.remoteId)this.processRemoteInboundStats(t.remoteId,e);else{const n=this.findRemoteStatsId(t.ssrc,Xi.REMOTE_INBOUND);n&&this.processRemoteInboundStats(n,e)}}processAudioOutboundStats(t){let e=this._stats.audioSend.find(i=>i.ssrc===t.ssrc);if(e||(e=wn(AI),this._stats.audioSend.push(e)),e.ssrc=t.ssrc,e.packets=t.packetsSent,e.bytes=t.bytesSent,e.retransmittedBytesSent=t.retransmittedBytesSent,e.retransmittedPacketsSent=t.retransmittedPacketsSent,t.mediaSourceId&&this.processAudioMediaSource(t.mediaSourceId,e),t.codecId&&(e.codec=this.getCodecFromCodecStats(t.codecId)),this.processAudioTrackSenderStats(t,t.trackId,e),t.remoteId)this.processRemoteInboundStats(t.remoteId,e);else{const i=this.findRemoteStatsId(t.ssrc,Xi.REMOTE_INBOUND);i&&this.processRemoteInboundStats(i,e)}}findRemoteStatsId(t,e){var i;const n=Array.from(Ui(i=this.report).call(i)).find(r=>r.type===e&&r.ssrc===t);return n?n.id:null}processVideoMediaSource(t,e){const i=this.report.get(t);i&&i.width&&i.height&&i.framesPerSecond&&(e.inputFrame={width:i.width,height:i.height,frameRate:i.framesPerSecond})}processAudioMediaSource(t,e){const i=this.report.get(t);i&&(e.inputLevel=i.audioLevel)}processVideoTrackSenderStats(t,e,i){var n,r,o,s;const a=e?this.report.get(e):void 0,c=(n=a==null?void 0:a.framesSent)!==null&&n!==void 0?n:t.framesSent;if(typeof c!="number")return;let d=(r=a==null?void 0:a.frameWidth)!==null&&r!==void 0?r:t.frameWidth,l=(o=a==null?void 0:a.frameHeight)!==null&&o!==void 0?o:t.frameHeight,u=(s=a==null?void 0:a.framesPerSecond)!==null&&s!==void 0?s:t.framesPerSecond;if(typeof d=="number"&&typeof l=="number"||(d=0,l=0),u==null){const h=Date.now(),p=this.lastVideoFramesSent.get(i.ssrc);p&&h-p.lts>=800?(u=Math.round((c-p.count)/((h-p.lts)/1e3)),this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:h,rate:u})):p?u=p.rate:this.lastVideoFramesSent.set(i.ssrc,{count:c,lts:h,rate:0})}i.sentFrame={width:d,height:l,frameRate:Math.max(0,u)}}processVideoTrackReceiverStats(t,e,i){var n,r,o,s,a;const c=e?this.report.get(e):void 0,d=(n=c==null?void 0:c.framesReceived)!==null&&n!==void 0?n:t.framesReceived,l=(r=c==null?void 0:c.frameWidth)!==null&&r!==void 0?r:t.frameWidth,u=(o=c==null?void 0:c.frameHeight)!==null&&o!==void 0?o:t.frameHeight,h=(s=c==null?void 0:c.jitterBufferDelay)!==null&&s!==void 0?s:t.jitterBufferDelay,p=(a=c==null?void 0:c.jitterBufferEmittedCount)!==null&&a!==void 0?a:t.jitterBufferEmittedCount;if(typeof d=="number"){const g=this.lastVideoFramesRecv.get(i.ssrc),m=Date.now();i.framesReceivedCount=d;let f=0;g&&m-g.lts>=800?(f=Math.round((d-g.count)/((m-g.lts)/1e3)),this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:m,rate:f})):g?f=g.rate:this.lastVideoFramesRecv.set(i.ssrc,{count:d,lts:m,rate:0}),i.receivedFrame={width:l||0,height:u||0,frameRate:f||0},i.decodedFrame={width:l||0,height:u||0,frameRate:i.decodeFrameRate||0},i.outputFrame={width:l||0,height:u||0,frameRate:i.outputFrameRate||i.decodeFrameRate||0}}if(h&&p){const g=this.lastVideoJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let m=g.jitterBufferMs;const f=p-g.jitterBufferEmittedCount;f>0&&(m=1e3*(h-g.jitterBufferDelay)/f),i.jitterBufferMs=m,i.currentDelayMs=Math.round(m),this.lastVideoJBDelay.set(i.ssrc,{jitterBufferDelay:h,jitterBufferEmittedCount:p,jitterBufferMs:i.currentDelayMs})}}processAudioTrackSenderStats(t,e,i){var n,r,o,s;const a=e?this.report.get(e):void 0,c=(n=(r=a==null?void 0:a.echoReturnLoss)!==null&&r!==void 0?r:t.echoReturnLoss)!==null&&n!==void 0?n:0,d=(o=(s=a==null?void 0:a.echoReturnLossEnhancement)!==null&&s!==void 0?s:t.echoReturnLossEnhancement)!==null&&o!==void 0?o:0;i.aecReturnLoss=c,i.aecReturnLossEnhancement=d}processAudioTrackReceiverStats(t,e,i){var n,r,o,s,a,c,d,l,u;const h=e?this.report.get(e):void 0,p=(n=h==null?void 0:h.removedSamplesForAcceleration)!==null&&n!==void 0?n:t.removedSamplesForAcceleration,g=(r=h==null?void 0:h.totalSamplesReceived)!==null&&r!==void 0?r:t.totalSamplesReceived,m=(o=h==null?void 0:h.jitterBufferDelay)!==null&&o!==void 0?o:t.jitterBufferDelay,f=(s=h==null?void 0:h.jitterBufferEmittedCount)!==null&&s!==void 0?s:t.jitterBufferEmittedCount,T=(a=h==null?void 0:h.audioLevel)!==null&&a!==void 0?a:t==null?void 0:t.audioLevel,R=(c=h==null?void 0:h.totalSamplesDuration)!==null&&c!==void 0?c:t==null?void 0:t.totalSamplesDuration,A=(d=h==null?void 0:h.concealedSamples)!==null&&d!==void 0?d:t.concealedSamples,N=(l=h==null?void 0:h.silentConcealedSamples)!==null&&l!==void 0?l:t.silentConcealedSamples,O=(u=h==null?void 0:h.concealmentEvents)!==null&&u!==void 0?u:t.concealmentEvents;if(typeof g=="number"&&(i.totalSamplesReceived=g),typeof N=="number"&&(i.silentConcealedSamples=N),typeof O=="number"&&(i.concealmentEvents=O),typeof A=="number"&&(i.concealedSamples=A),p&&g&&(i.accelerateRate=p/g),m&&f){const L=this.lastAudioJBDelay.get(i.ssrc)||{jitterBufferDelay:0,jitterBufferEmittedCount:0,jitterBufferMs:0};let M=L.jitterBufferMs;const j=f-L.jitterBufferEmittedCount;j>0&&(M=1e3*(m-L.jitterBufferDelay)/j),i.jitterBufferMs=Math.round(M),this.lastAudioJBDelay.set(i.ssrc,{jitterBufferDelay:m,jitterBufferEmittedCount:f,jitterBufferMs:i.jitterBufferMs})}i.outputLevel=T;let w=1920;R&&g&&(w=g/R/50,i.receivedFrames=Math.round(g/w)),A&&(i.droppedFrames=Math.round(A/w))}processRemoteInboundStats(t,e){const i=this.report.get(t);i&&(e.packetsLost=i.packetsLost,i.roundTripTime&&(e.rttMs=1e3*i.roundTripTime),i.jitter&&(e.jitterMs=1e3*i.jitter),i.timestamp&&(e.timestamp=i.timestamp))}getCodecFromCodecStats(t){const e=this.report.get(t);if(!e)return"";const i=e.mimeType.match(/\/(.*)$/);return i&&i[1]?i[1]:""}updateSendBitrate(){let t=0,e=null,i=null;this.mediaBytesSent.forEach(r=>{t+=r.diffMean()}),this.mediaBytesRetransmit.forEach(r=>{e=e===null?r.diffMean():e+r.diffMean()}),this.mediaBytesTargetEncode.forEach(r=>{i=i===null?r.diffMean():i+r.diffMean()});const n=e!==null?t-e:t;this._stats.bitrate={actualEncoded:8*n/(this.options.updateInterval/1e3),transmit:8*t/(this.options.updateInterval/1e3)},e!==null&&(this._stats.bitrate.retransmit=8*e/(this.options.updateInterval/1e3)),i!==null&&(this._stats.bitrate.targetEncoded=8*i/(this.options.updateInterval/1e3))}},HG=class extends WE{updateStats(){return K.resolve()}};function KE(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:250,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:8,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:500,r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1e4;const o=function(){const s=navigator.userAgent.toLocaleLowerCase().match(/chrome\/[\d]*/i);return s&&s[0]?Number(s[0].split("/")[1]):null}();return o?o<76?new WG(t,{updateInterval:e,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new wI(t,{updateInterval:e,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):function(s){if(!window.RTCStatsReport)return!1;const a=s.getStats();return!!(a instanceof K||function(c){return!!c&&(typeof c=="object"||typeof c=="function")&&typeof c.then=="function"}(a))}(t)?new wI(t,{updateInterval:e,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r}):new HG(t,{updateInterval:e,lossRateInterval:i,freezeRateLimit:n,firstVideoDecodedTimeout:r})}const OI="websdk_ng_install_id";function YE(){try{if(y("INSTALL_ID"))return y("INSTALL_ID");let t=window.localStorage.getItem(OI);return t||(t=Zo(),window.localStorage.setItem(OI,t)),kt("INSTALL_ID",t),t}catch(t){return}}const dn=function(t){if(t.match(/[0-9]+\.[0-9]+\.[0-9]+$/))return t;const e=t.match(/([0-9]+\.[0-9]+\.[0-9]+)\-([0-9]+)/);if(e&&e[1]&&e[2]){const i=e[1],n=e[2];return"".concat(i,".").concat(n)}return"4.0.0.999"}("4.23.4"),qE=function(){try{return JSON.parse("true")===!0}catch(t){return!0}}();let $o=function(t){return t.Default="default",t.Auto="auto",t.Relay="relay",t.SdRtn="sd-rtn",t}({});const He=function(){const t="us".concat("erna","me"),e="pa".concat("sswo","rd"),i=["t","s","t"];i.splice(1,0,"e");const n=i.join(""),r=[];for(let a=0;a<6;a++)r.push("1");const o=r.join(""),s={};return s[t]=n,s[e]=o,Object.assign(s,{turnServerURL:"",tcpport:3433,udpport:3478,forceturn:!1})}();window.DEFAULT_TURN_CONFIG=He;const _u={ENABLE_PUBLISHED_USER_LIST:!0,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:!1,ENABLE_INSTANT_VIDEO:!1,ENABLE_USER_AUTO_REBALANCE_CHECK:!0,ENABLE_LOSSBASED_BWE:!0,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,PRE_SUB_NUM:2,ENABLE_AUT_FEEDBACK:!1,SVC_EXTENDED:["VP9"]},zE={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},XE="v4.23.4-0-g17410532-dirty(6/5/2025, 4:24:52 PM)",JE={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,NEW_ICE_RESTART:!1,ICE_RESTART_INTERVAL:1e4,RESTART_SEQUENCE:["udp_tcp_relay","relay"],FIRST_TCP_CANDIDATE:!1,FIRST_TCP_CANDIDATE_INTERVAL:1e3,TURN_DOMAIN:"edge.agora.io",USE_TURN_IP:!1,NEW_TURN_MODE:void 0,NEW_FORCE_TURN:!1,USE_NEW_RENDER_FREEZE_TIME:!1},Xt=z(z(z(z({},JE),{},{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"],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,PRELOAD_MEDIA_COUNT:0,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_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_METADATA:!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_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,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:[],USE_NEW_NETWORK_CONFIG:!1,AUTO_RESET_AUDIO_ROUTE:!1,PLUGIN_INFO:[],OVERUSE_DETECTOR_PARAMS:zE,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},_u),{},{USE_CANDIDATE_FROM_AP_DETAIL:!1,AP_REQUEST_DETAIL:void 0,ENABLE_ROLE_SELECT_EDGE:!1,CLIENT_ROLE_OPTIONS: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,ENABLE_PRE_SUB:!1,ENABLE_SVC:!1},{INSTALL_ID:""}),{},{K_MIN_RENDER_DELAY:66,USE_STANDARD_BITRATE_DEFAULT:!1,VIDEO_NEW_BITRATE_RATIO:void 0,VIDEO_STANDARD_BITRATE_VERSION:void 0,BASELINE_MORE_H264_BITRATE_RATIO:1.1});function kt(t,e,i){var n,r,o;G(n=Object.keys(Xt)).call(n,t)&&(!i&&G(r=Object.keys(Qn)).call(r,t)||(Xt[t]=e,t!=="ENABLE_VIDEO_SEI"&&t!=="ENABLE_AUDIO_TOPN"&&t!=="ENABLE_AUDIO_METADATA"&&t!=="ENABLE_AUDIO_PTS_METADATA"||e!==!0||(Xt.ENABLE_ENCODED_TRANSFORM=!0,t==="ENABLE_AUDIO_PTS_METADATA"&&(Xt.ENABLE_AUDIO_METADATA=!0)),t==="USE_NEW_NETWORK_CONFIG"&&e&&(o=!!e,Xt.USE_NEW_NETWORK_CONFIG=o,o&&(Xt.WEBCS_DOMAIN=["webrtc2-2.ap.sd-rtn.com"],Xt.WEBCS_DOMAIN_BACKUP_LIST=["webrtc2-4.ap.sd-rtn.com"],Xt.CDS_AP=["cds-web-2.ap.sd-rtn.com","cds-web-4.ap.sd-rtn.com"],Xt.ACCOUNT_REGISTER=["sua-web-2.ap.sd-rtn.com","sua-web-4.ap.sd-rtn.com"],Xt.EVENT_REPORT_DOMAIN="web-2.statscollector.sd-rtn.com",Xt.EVENT_REPORT_BACKUP_DOMAIN="statscollector-1.agora.io",Xt.GATEWAY_DOMAINS=["edge.sd-rtn.com"])),t==="ENABLE_PRE_SUB"&&e&&(Xt.ENABLE_INSTANT_VIDEO=!0,Xt.ENABLE_PREALLOC_PC=!0),t==="ENABLE_SVC"&&e&&(Xt.ENABLE_AUT_CC=!0),t==="NEW_FORCE_TURN"&&e&&(Xt.NEW_TURN_MODE||(Xt.NEW_TURN_MODE=4))))}function y(t){return Xt[t]}qE||(Xt.WEBCS_DOMAIN=["ap-web-1-oversea.agora.io","ap-web-1-north-america.agora.io"],Xt.WEBCS_DOMAIN_BACKUP_LIST=["ap-web-2-oversea.agora.io","ap-web-2-north-america.agora.io"],Xt.PROXY_CS=["proxy-ap-web-oversea.agora.io","proxy-ap-web-america.agora.io"],Xt.CDS_AP=["cds-ap-web-oversea.agora.io","cds-ap-web-america.agora.io","cds-ap-web-america2.agora.io"],Xt.ACCOUNT_REGISTER=["sua-ap-web-oversea.agora.io","sua-ap-web-america.agora.io","sua-ap-web-america2.agora.io"],Xt.UAP_AP=["uap-ap-web-oversea.agora.io","uap-ap-web-america.agora.io","uap-ap-web-america2.agora.io"],Xt.LOG_UPLOAD_SERVER="logservice-oversea.agora.io",Xt.EVENT_REPORT_DOMAIN="statscollector-1-oversea.agora.io",Xt.EVENT_REPORT_BACKUP_DOMAIN="statscollector-2-oversea.agora.io",Xt.PROXY_SERVER_TYPE3="webrtc-cloud-proxy.agora.io",Xt.AREAS=["NORTH_AMERICA","OVERSEA"]);let NI=function(t){return t[t.REALTIME=1]="REALTIME",t}({});const Qn={};var ft=function(t){return t.SET_SESSION_ID="SET_SESSION_ID",t.SET_P2P_ID="SET_P2P_id",t.SET_DC_ID="SET_DC_id",t.SET_UID="SET_UID",t.SET_INT_UID="SET_INT_UID",t.SET_PUB_ID="SET_PUB_ID",t.SET_CLOUD_PROXY_SERVER_MODE="SET_CLOUD_PROXY_SERVER_MODE",t.KEY_METRIC_CLIENT_CREATED="KEY_METRIC_CLIENT_CREATED",t.KEY_METRIC_JOIN_START="KEY_METRIC_JOIN_START",t.KEY_METRIC_JOIN_END="KEY_METRIC_JOIN_END",t.KEY_METRIC_REQUEST_AP_START="KEY_METRIC_REQUEST_AP_START",t.KEY_METRIC_REQUEST_AP_END="KEY_METRIC_REQUEST_AP_END",t.KEY_METRIC_JOIN_GATEWAY_START="KEY_METRIC_JOIN_GATEWAY_START",t.KEY_METRIC_JOIN_GATEWAY_END="KEY_METRIC_JOIN_GATEWAY_END",t.KEY_METRIC_PEER_CONNECTION_START="KEY_METRIC_PEER_CONNECTION_START",t.KEY_METRIC_PEER_CONNECTION_END="KEY_METRIC_PEER_CONNECTION_END",t.KEY_METRIC_DESCRIPTION_START="KEY_METRIC_DESCRIPTION_START",t.KEY_METRIC_ICE_CONNECTION_END="KEY_METRIC_ICE_CONNECTION_END",t.KEY_METRIC_SIGNAL_CHANNEL_OPEN="KEY_METRIC_SIGNAL_CHANNEL_OPEN",t.KEY_METRIC_PUBLISH="KEY_METRIC_PUBLISH",t.KEY_METRIC_SUBSCRIBE="KEY_METRIC_SUBSCRIBE",t.RECORD_JOIN_CHANNEL_SERVICE="RECORD_JOIN_CHANNEL_SERVICE",t.RESET_JOIN_CHANNEL_SERVICE_RECORDS="RESET_JOIN_CHANNEL_SERVICE_RECORDS",t.RESET_KEY_METRICS="RESET_KEY_METRICS",t.SET_USE_P2P="SET_USE_P2P",t.SET_TRANSPORT_TYPE="SET_TRANSPORT_TYPE",t}(ft||{});let Eu=function(t){return t.h264="h264",t.h265="h265",t.vp8="vp8",t.vp9="vp9",t.av1="av1",t}({});(function(t){t.opus="opus",t.pcma="pcma",t.pcmu="pcmu",t.g722="g722"})({});const DI=128,KG=96,PI=1e3,ca=10;let YG=0;var LI=(()=>{var t={8:(n,r,o)=>{o.r(r),o.d(r,{Parser:()=>j,Printer:()=>Kt,parse:()=>B,print:()=>X});const s=`
`,a="".concat("\r").concat(s),c=" ";let d;function l(x){return x>="0"&&x<="9"}function u(x){return x>="!"&&x<="~"}function h(x){return u(x)||x>="€"&&x<="ÿ"}function p(x){return x==="!"||x>="#"&&x<="'"||x>="*"&&x<="+"||x>="-"&&x<="."||x>="0"&&x<="9"||x>="A"&&x<="Z"||x>="^"&&x<="~"}function g(x){return x>="1"&&x<="9"}function m(x){return x>="A"&&x<="Z"||x>="a"&&x<="z"}function f(x){return x==="d"||x==="h"||x==="m"||x==="s"}function T(x){return x>""&&x<" "||x>"\v"&&x<"\f"||x>""&&x<"ÿ"}function R(x){return m(x)||l(x)||x==="+"||x==="/"}function A(x){return l(x)||m(x)||x==="+"||x==="/"||x==="-"||x==="_"}function N(x){return m(x)||l(x)||x==="+"||x==="/"}function O(x,E){var I=Object.keys(x);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(x);E&&(b=b.filter(function(F){return Object.getOwnPropertyDescriptor(x,F).enumerable})),I.push.apply(I,b)}return I}function w(x){for(var E=1;E<arguments.length;E++){var I=arguments[E]!=null?arguments[E]:{};E%2?O(Object(I),!0).forEach(function(b){L(x,b,I[b])}):Object.getOwnPropertyDescriptors?Object.defineProperties(x,Object.getOwnPropertyDescriptors(I)):O(Object(I)).forEach(function(b){Object.defineProperty(x,b,Object.getOwnPropertyDescriptor(I,b))})}return x}function L(x,E,I){return E in x?Object.defineProperty(x,E,{value:I,enumerable:!0,configurable:!0,writable:!0}):x[E]=I,x}(function(x){x.VERSION="v",x.ORIGIN="o",x.SESSION_NAME="s",x.INFORMATION="i",x.URI="u",x.EMAIL="e",x.PHONE="p",x.CONNECTION="c",x.BANDWIDTH="b",x.TIME="t",x.REPEAT="r",x.ZONE_ADJUSTMENTS="z",x.KEY="k",x.ATTRIBUTE="a",x.MEDIA="m"})(d||(d={}));class M{consumeText(E,I){let b=I;for(;b<E.length;){const F=E[b];if(F==="\0"||F==="\r"||F===s)break;b+=1}if(b-I==0)throw new Error("Invalid text, at ".concat(E));return b}consumeUnicastAddress(E,I,b){return this.consumeTill(E,I,c)}consumeOneOrMore(E,I,b){let F=I;for(;b(E[F]);)F++;if(F-I==0)throw new Error("Invalid rule at ".concat(I,"."));return F}consumeSpace(E,I){if(E[I]===c)return I+1;throw new Error("Invalid space at ".concat(I,"."))}consumeIP4Address(E,I){let b=I;for(let F=0;F<4;F++)if(b=this.consumeDecimalUChar(E,b),F!==3){if(E[b]!==".")throw new Error("Invalid IP4 address.");b++}return b}consumeDecimalUChar(E,I){let b=I;for(let ct=0;ct<3&&l(E[b]);ct++,b++);if(b-I==0)throw new Error("Invalid decimal uchar.");const F=parseInt(E.slice(I,b));if(F>=0&&F<=255)return b;throw new Error("Invalid decimal uchar")}consumeIP6Address(E,I){let b=this.consumeHexpart(E,I);return E[b]===":"&&(b+=1,b=this.consumeIP4Address(E,b)),b}consumeHexpart(E,I){let b=I;if(E[b]===":"&&E[b+1]===":"){b+=2;try{b=this.consumeHexseq(E,b)}catch(F){}return b}if(b=this.consumeHexseq(E,b),E[b]===":"&&E[b+1]===":"){b+=2;try{b=this.consumeHexseq(E,b)}catch(F){}return b}return b}consumeHexseq(E,I){let b=I;for(;b=this.consumeHex4(E,b),E[b]===":"&&E[b+1]!==":";)b+=1;return b}consumeHex4(E,I){let b=0;for(;b<4;b++)if(!((F=E[I+b])>="0"&&F<="9"||F>="a"&&F<="f"||F>="A"&&F<="F")){if(b===0)throw new Error("Invalid hex 4");break}var F;return I+b}consumeFQDN(E,I){let b=I;for(;l(E[b])||m(E[b])||E[b]==="-"||E[b]===".";)b+=1;if(b-I<4)throw new Error("Invalid FQDN");return b}consumeExtnAddr(E,I){return this.consumeOneOrMore(E,I,h)}consumeMulticastAddress(E,I,b){switch(b){case"IP4":case"ip4":return this.consumeIP4MulticastAddress(E,I);case"IP6":case"ip6":return this.consumeIP6MulticastAddress(E,I);default:try{return this.consumeFQDN(E,I)}catch(F){return this.consumeExtnAddr(E,I)}}}consumeIP6MulticastAddress(E,I){const b=this.consumeHexpart(E,I);return E[b]==="/"?this.consumeInteger(E,b+1):b}consumeIP4MulticastAddress(E,I){let b=I+3;const F=E.slice(I,b),ct=parseInt(F);if(ct<224||ct>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 Wt=0;Wt<3;Wt++){if(E[b]!==".")throw new Error("Invalid IP4 multicast address.");b+=1,b=this.consumeDecimalUChar(E,b)}return E[b]==="/"&&(b+=1),b=this.consumeTTL(E,b),E[b]==="/"&&(b=this.consumeInteger(E,b)),b}consumeInteger(E,I){if(!g(E[I]))throw new Error("Invalid integer.");for(I+=1;l(E[I]);)I+=1;return I}consumeTTL(E,I){if(E[I]==="0")return I+1;if(!g(E[I]))throw new Error("Invalid TTL.");I+=1;for(let b=0;b<2&&l(E[I]);b++)I+=1;return I}consumeToken(E,I){return this.consumeOneOrMore(E,I,p)}consumeTime(E,I){let b=I;if(E[b]==="0")return b+1;for(g(E[b])&&(b+=1);l(E[b]);)b++;if(b-I<10)throw new Error("Invalid time");return b}consumeAddress(E,I){return this.consumeTill(E,I,c)}consumeTypedTime(E,I){let b=I;return b=this.consumeOneOrMore(E,b,l),f(E[b])?b+1:b}consumeRepeatInterval(E,I){if(!g(E[I]))throw new Error("Invalid repeat interval");for(I+=1;l(E[I]);)I+=1;return f(E[I])&&(I+=1),I}consumePort(E,I){return this.consumeOneOrMore(E,I,l)}consume(E,I,b){for(let F=0;F<b.length;F++){if(I+F>=E.length)throw new Error("consume exceeding value length");if(E[I+F]!==b[F])throw new Error("consume ".concat(b," failed at ").concat(F))}return I+b.length}consumeTill(E,I,b){let F=I;for(;F<E.length&&(typeof b!="string"||E[F]!==b)&&(typeof b!="function"||!b(E[F]));)F++;return F}}class j extends M{constructor(){super(),L(this,"records",[]),L(this,"currentLine",0)}parse(E){const I=this.probeEOL(E);this.records=E.split(I).filter(Jr=>!!ni(Jr).call(Jr)).map(this.parseLine),this.currentLine=0;const b=this.parseVersion(),F=this.parseOrigin(),ct=this.parseSessionName(),Wt=this.parseInformation(),ye=this.parseUri(),mn=this.parseEmail(),jn=this.parsePhone(),Rd=this.parseConnection(),Ss=this.parseBandWidth(),Ga=this.parseTimeFields(),vh=this.parseKey(),Ch=this.parseSessionAttribute(),fn=this.parseMediaDescription();if(this.currentLine!==this.records.length)throw new Error("parsing failed, non exhaustive sdp lines.");return{version:b,origin:F,sessionName:ct,information:Wt,uri:ye,emails:mn,phones:jn,connection:Rd,bandwidths:Ss,timeFields:Ga,key:vh,attributes:Ch,mediaDescriptions:fn}}getCurrentRecord(){const E=this.records[this.currentLine];if(!E)throw new Error("Record doesn't exit.");return E}probeEOL(E){for(let I=0;I<E.length;I++)if(E[I]===s)return E[I-1]==="\r"?a:s;throw new Error("Invalid newline character.")}parseLine(E,I){if(E.length<2)throw new Error("Invalid sdp line, sdp line should be of form <type>=<value>.");const b=E[0];if(E[1]!=="=")throw new Error('Invalid sdp line, <type> should be a single character followed by an "=" sign.');return{type:b,value:E.slice(2),line:I,cur:0}}parseSessionAttribute(){const E=new ht;for(;this.currentLine<this.records.length;){const I=this.getCurrentRecord();if(I.type!==d.ATTRIBUTE)break;const b={attField:this.extractOneOrMore(I,F=>p(F)&&F!==":"),_cur:0};I.value[I.cur]===":"&&(I.cur+=1,b.attValue=this.extractOneOrMore(I,T)),E.parse(b),this.currentLine++}return E.digest()}parseMediaAttributes(E){const I=new lt(E);for(;this.currentLine<this.records.length;){const b=this.getCurrentRecord();if(b.type!==d.ATTRIBUTE)break;const F={attField:this.extractOneOrMore(b,ct=>p(ct)&&ct!==":"),_cur:0};b.value[b.cur]===":"&&(b.cur+=1,F.attValue=this.extractOneOrMore(b,T)),I.parse(F),this.currentLine++}return I.digest()}parseKey(){const E=this.getCurrentRecord();if(E.type===d.KEY){if(E.value==="prompt"||E.value==="clear:"||E.value==="base64:"||E.value==="uri:")return E.value;throw this.currentLine++,new Error("Invalid key.")}}parseZone(){const E=this.getCurrentRecord();if(E.type===d.ZONE_ADJUSTMENTS){const I=[];for(;;)try{const b=this.extract(E,this.consumeTime);this.consumeSpaceForRecord(E);let F=!1;E.value[E.cur]==="-"&&(F=!0,E.cur+=1);const ct=this.extract(E,this.consumeTypedTime);I.push({time:b,typedTime:ct,back:F})}catch(b){break}if(I.length===0)throw new Error("Invalid zone adjustments");return this.currentLine++,I}return[]}parseRepeat(){const E=[];for(;;){const I=this.getCurrentRecord();if(I.type!==d.REPEAT)break;{const b=this.extract(I,this.consumeRepeatInterval),F=this.parseTypedTime(I);E.push({repeatInterval:b,typedTimes:F}),this.currentLine++}}return E}parseTypedTime(E){const I=[];for(;;)try{this.consumeSpaceForRecord(E),I.push(this.extract(E,this.consumeTypedTime))}catch(b){break}if(I.length===0)throw new Error("Invalid typed time.");return I}parseTime(){const E=this.getCurrentRecord(),I=this.extract(E,this.consumeTime);this.consumeSpaceForRecord(E);const b=this.extract(E,this.consumeTime);return this.currentLine++,{startTime:I,stopTime:b}}parseBandWidth(){const E=[];for(;this.currentLine<this.records.length;){const I=this.getCurrentRecord();if(I.type!==d.BANDWIDTH)break;{const b=this.extractOneOrMore(I,p);if(I.value[I.cur]!==":")throw new Error("Invalid bandwidth field.");I.cur++;const F=this.extractOneOrMore(I,l);E.push({bwtype:b,bandwidth:F}),this.currentLine++}}return E}parseVersion(){const E=this.getCurrentRecord();if(E.type!==d.VERSION)throw new Error("first sdp record must be version");const I=E.value.slice(0,this.consumeOneOrMore(E.value,0,l));if(I.length!==E.value.length)throw new Error('invalid proto version, "v='.concat(E.value,'"'));return this.currentLine++,I}parseOrigin(){const E=this.getCurrentRecord();if(E.type!==d.ORIGIN)throw new Error("second line of sdp must be origin");const I=this.extractOneOrMore(E,h);this.consumeSpaceForRecord(E);const b=this.extractOneOrMore(E,l);this.consumeSpaceForRecord(E);const F=this.extractOneOrMore(E,l);this.consumeSpaceForRecord(E);const ct=this.extractOneOrMore(E,p);this.consumeSpaceForRecord(E);const Wt=this.extractOneOrMore(E,p);this.consumeSpaceForRecord(E);const ye=this.extract(E,this.consumeUnicastAddress);return this.currentLine++,{username:I,sessId:b,sessVersion:F,nettype:ct,addrtype:Wt,unicastAddress:ye}}parseSessionName(){const E=this.getCurrentRecord();if(E.type===d.SESSION_NAME){const I=this.extract(E,this.consumeText);return this.currentLine++,I}}parseInformation(){const E=this.getCurrentRecord();if(E.type!==d.INFORMATION)return;const I=this.extract(E,this.consumeText);return this.currentLine++,I}parseUri(){const E=this.getCurrentRecord();if(E.type===d.URI)return this.currentLine++,E.value}parseEmail(){const E=[];for(;;){const I=this.getCurrentRecord();if(I.type!==d.EMAIL)break;E.push(I.value),this.currentLine++}return E}parsePhone(){const E=[];for(;;){const I=this.getCurrentRecord();if(I.type!==d.PHONE)break;E.push(I.value),this.currentLine++}return E}parseConnection(){const E=this.getCurrentRecord();if(E.type===d.CONNECTION){const I=this.extractOneOrMore(E,p);this.consumeSpaceForRecord(E);const b=this.extractOneOrMore(E,p);this.consumeSpaceForRecord(E);const F=this.extract(E,this.consumeAddress);return this.currentLine++,{nettype:I,addrtype:b,address:F}}}parseMedia(){const E=this.getCurrentRecord(),I=this.extract(E,this.consumeToken);this.consumeSpaceForRecord(E);let b=this.extract(E,this.consumePort);E.value[E.cur]==="/"&&(E.cur+=1,b+=this.extract(E,this.consumeInteger)),this.consumeSpaceForRecord(E);const F=[];for(F.push(this.extract(E,this.consumeToken));E.value[E.cur]==="/";)E.cur+=1,F.push(this.extract(E,this.consumeToken));if(F.length===0)throw new Error("Invalid proto");const ct=this.parseFmt(E);return this.currentLine++,{mediaType:I,port:b,protos:F,fmts:ct}}parseTimeFields(){const E=[];for(;this.getCurrentRecord().type===d.TIME;){const I=this.parseTime(),b=this.parseRepeat(),F=this.parseZone();E.push({time:I,repeats:b,zones:F})}return E}parseMediaDescription(){const E=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===d.MEDIA;){const I=this.parseMedia(),b=this.parseInformation(),F=this.parseConnections(),ct=this.parseBandWidth(),Wt=this.parseKey(),ye=this.parseMediaAttributes(I);E.push({media:I,information:b,connections:F,bandwidths:ct,key:Wt,attributes:ye})}return E}parseConnections(){const E=[];for(;this.currentLine<this.records.length&&this.getCurrentRecord().type===d.CONNECTION;)E.push(this.parseConnection());return E}parseFmt(E){const I=[];for(;;)try{this.consumeSpaceForRecord(E),I.push(this.extract(E,this.consumeToken))}catch(b){break}if(I.length===0)throw new Error("Invalid fmts");return I}extract(E,I){for(var b=arguments.length,F=new Array(b>2?b-2:0),ct=2;ct<b;ct++)F[ct-2]=arguments[ct];const Wt=I.call(this,E.value,E.cur,...F),ye=E.value.slice(E.cur,Wt);return E.cur=Wt,ye}extractOneOrMore(E,I){const b=this.consumeOneOrMore(E.value,E.cur,I),F=E.value.slice(E.cur,b);return E.cur=b,F}consumeSpaceForRecord(E){if(E.value[E.cur]!==c)throw new Error("Invalid space at ".concat(E.cur,"."));E.cur+=1}}class H extends M{constructor(){super(...arguments),L(this,"attributes",void 0),L(this,"digested",!1)}extractOneOrMore(E,I,b){const F=this.consumeOneOrMore(E.attValue,E._cur,I),ct=E.attValue.slice(E._cur,F),[Wt,ye]=b||[];if(typeof Wt=="number"&&ct.length<Wt)throw new Error("error in length, should be more or equal than ".concat(Wt," characters."));if(typeof ye=="number"&&ct.length>ye)throw new Error("error in length, should be less or equal than ".concat(ye," characters."));return E._cur=F,ct}consumeAttributeSpace(E){if(E.attValue[E._cur]!==c)throw new Error("Invalid space at ".concat(E._cur,"."));E._cur+=1}extract(E,I){if(!E.attValue)throw new Error("Nothing to extract from attValue.");for(var b=arguments.length,F=new Array(b>2?b-2:0),ct=2;ct<b;ct++)F[ct-2]=arguments[ct];const Wt=I.call(this,E.attValue,E._cur,...F),ye=E.attValue.slice(E._cur,Wt);return E._cur=Wt,ye}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,I){if(!E.attValue)throw new Error;for(let b=0;b<I.length;b++)if(I[b]!==E.attValue[E._cur+b])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,R,[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,R,[22,256])}parseIceOptions(E){if(this.attributes.iceOptions)throw new Error("Invalid ice-options, should be only one 'ice-options' line");const I=[];for(;!this.atEnd(E);){I.push(this.extractOneOrMore(E,R));try{this.consumeAttributeSpace(E)}catch(b){if(this.atEnd(E))break;throw b}}this.attributes.iceOptions=I}parseFingerprint(E){const I=this.extract(E,this.consumeToken);this.consumeAttributeSpace(E);const b=this.extract(E,this.consumeTill);this.attributes.fingerprints.push({hashFunction:I,fingerprint:b})}parseExtmap(E){const I=this.extractOneOrMore(E,l);let b;this.peekChar(E)==="/"&&(this.extract(E,this.consume,"/"),b=this.extract(E,this.consumeToken)),this.consumeAttributeSpace(E);const F=this.extract(E,this.consumeTill,c),ct=w(w({entry:parseInt(I,10)},b&&{direction:b}),{},{extensionName:F});this.peekChar(E)===c&&(this.consumeAttributeSpace(E),ct.extensionAttributes=this.extract(E,this.consumeTill)),this.attributes.extmaps.push(ct)}parseSetup(E){if(this.attributes.setup)throw new Error("must only be one single 'a=setup' line.");const I=this.extract(E,this.consumeTill);if(I!=="active"&&I!=="passive"&&I!=="actpass"&&I!=="holdconn")throw new Error("role must be one of 'active', 'passive', 'actpass', 'holdconn'.");this.attributes.setup=I}}class ht extends H{constructor(){super(...arguments),L(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(I){throw console.error("parsing session attribute ".concat(E.attField,' error, "a=').concat(E.attField,":").concat(E.attValue,'"')),I}if(!E.ignored&&E.attValue&&!this.atEnd(E))throw new Error("attribute parsing error")}digest(){return this.digested=!0,this.attributes}parseGroup(E){const I=this.extract(E,this.consumeToken),b=[];for(;!this.atEnd(E)&&this.peekChar(E)===c;)this.consumeAttributeSpace(E),b.push(this.extract(E,this.consumeToken));this.attributes.groups.push({semantic:I,identificationTag:b})}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,A)}parseIdentity(E){const I=this.extractOneOrMore(E,N),b=[];for(;!this.atEnd(E)&&this.peekChar(E)===c;){this.consumeAttributeSpace(E);const F=this.extract(E,this.consumeToken);this.extract(E,this.consume,"=");const ct=this.extractOneOrMore(E,Wt=>Wt!==c&&T(Wt));b.push({name:F,value:ct})}this.attributes.identities.push({assertionValue:I,extensions:b})}parseMsidSemantic(E){this.peekChar(E)===c&&this.consumeAttributeSpace(E);const I={semantic:this.extract(E,this.consumeToken),identifierList:[]};for(;;){try{this.consumeAttributeSpace(E)}catch(b){break}if(this.peekChar(E)==="*"){this.extract(E,this.consume,"*"),I.applyForAll=!0;break}{const b=this.extract(E,this.consumeTill,c);I.identifierList.push(b)}}this.attributes.msidSemantic=I}}class lt extends H{constructor(E){super(),L(this,"attributes",void 0),E.protos.indexOf("RTP")!==-1||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(I){throw console.error("parsing media attribute ".concat(E.attField,' error, "a=').concat(E.attField,":").concat(E.attValue,'"')),I}if(!E.ignored&&E.attValue&&!this.atEnd(E))throw new Error("attribute parsing error")}parseCandidate(E){const I=this.extractOneOrMore(E,R,[1,32]);this.consumeAttributeSpace(E);const b=this.extractOneOrMore(E,l,[1,5]);this.consumeAttributeSpace(E);const F=this.extract(E,this.consumeToken);this.consumeAttributeSpace(E);const ct=this.extractOneOrMore(E,l,[1,10]);this.consumeAttributeSpace(E);const Wt=this.extract(E,this.consumeAddress);this.consumeAttributeSpace(E);const ye=this.extract(E,this.consumePort);this.consumeAttributeSpace(E),this.extract(E,this.consume,"typ"),this.consumeAttributeSpace(E);const mn={foundation:I,componentId:b,transport:F,priority:ct,connectionAddress:Wt,port:ye,type:this.extract(E,this.consumeToken),extension:{}};for(this.peek(E," raddr")&&(this.extract(E,this.consume," raddr"),this.consumeAttributeSpace(E),mn.relAddr=this.extract(E,this.consumeAddress)),this.peek(E," rport")&&(this.extract(E,this.consume," rport"),this.consumeAttributeSpace(E),mn.relPort=this.extract(E,this.consumePort));this.peekChar(E)===c;){this.consumeAttributeSpace(E);const jn=this.extract(E,this.consumeToken);this.consumeAttributeSpace(E),mn.extension[jn]=this.extractOneOrMore(E,u)}this.attributes.candidates.push(mn)}parseRemoteCandidate(E){const I=[];for(;;){const b=this.extractOneOrMore(E,l,[1,5]);this.consumeAttributeSpace(E);const F=this.extract(E,this.consumeAddress);this.consumeAttributeSpace(E);const ct=this.extract(E,this.consumePort);I.push({componentId:b,connectionAddress:F,port:ct});try{this.consumeAttributeSpace(E)}catch(Wt){break}}this.attributes.remoteCandidatesList.push(I)}parseEndOfCandidates(){if(this.attributes.endOfCandidates)throw new Error("must be only one line of end-of-candidates");this.attributes.endOfCandidates=!0}parseRtpmap(E){const I=this.extract(E,this.consumeToken);this.consumeAttributeSpace(E);const b=this.extract(E,this.consumeTill,"/");this.extract(E,this.consume,"/");const F={encodingName:b,clockRate:this.extractOneOrMore(E,l)};this.atEnd(E)||this.peekChar(E)!=="/"||(this.extract(E,this.consume,"/"),F.encodingParameters=parseInt(this.extract(E,this.consumeTill),10));const ct=this.attributes.payloads.find(Wt=>Wt.payloadType===parseInt(I,10));ct?ct.rtpMap=F:this.attributes.payloads.push({payloadType:parseInt(I,10),rtpMap:F,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 I=this.extractOneOrMore(E,l);this.consumeAttributeSpace(E);const b=this.extract(E,this.consumeTill,":");let F;this.peekChar(E)===":"&&(this.extract(E,this.consume,":"),F=this.extract(E,this.consumeTill));const ct=this.attributes.ssrcs.find(Wt=>Wt.ssrcId===parseInt(I,10));ct?ct.attributes[b]=F:this.attributes.ssrcs.push({ssrcId:parseInt(I,10),attributes:{[b]:F}})}parseFmtp(E){const I=this.extract(E,this.consumeTill,c);this.consumeAttributeSpace(E);const b=this.extract(E,this.consumeTill),F={};b.split(";").forEach(Wt=>{let[ye,mn]=Wt.split("=");ye=ni(ye).call(ye);const jn=typeof mn=="string"?ni(mn).call(mn):null;typeof ye=="string"&&ye.length>0&&(F[ye]=jn)});const ct=this.attributes.payloads.find(Wt=>Wt.payloadType===parseInt(I,10));ct?ct.fmtp={parameters:F}:this.attributes.payloads.push({payloadType:parseInt(I,10),rtcpFeedbacks:[],fmtp:{parameters:F}})}parseFmtParameters(E){const I={},b=this.extract(E,this.consumeTill,"=");E._cur++;const F=this.extract(E,this.consumeTill,";");for(I[b]=F;E.attValue[E._cur]===";";){const ct=this.extract(E,this.consumeTill,"=");E._cur++;const Wt=this.extract(E,this.consumeTill,";");I[ct]=Wt}return I}parseRtcpFb(E){let I="";I=this.peekChar(E)==="*"?this.extract(E,this.consume,"*"):this.extract(E,this.consumeTill,c),this.consumeAttributeSpace(E);const b=this.extract(E,this.consumeTill,c);let F;if(b==="trr-int")F={type:b,interval:this.extract(E,this.consumeTill)};else{const ct={type:b};this.peekChar(E)===c&&(this.consumeAttributeSpace(E),ct.parameter=this.extract(E,this.consumeToken),this.peekChar(E)===c&&(ct.additional=this.extract(E,this.consumeTill))),F=ct}if(I==="*")this.attributes.rtcpFeedbackWildcards.push(F);else{const ct=this.attributes.payloads.find(Wt=>Wt.payloadType===parseInt(I,10));ct?ct.rtcpFeedbacks.push(F):this.attributes.payloads.push({payloadType:parseInt(I,10),rtcpFeedbacks:[F]})}}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 I={port:this.extract(E,this.consumePort)};this.peekChar(E)===c&&(this.consumeAttributeSpace(E),I.netType=this.extractOneOrMore(E,p),this.consumeAttributeSpace(E),I.addressType=this.extractOneOrMore(E,p),this.consumeAttributeSpace(E),I.address=this.extract(E,this.consumeAddress)),this.attributes.rtcp=I}parseMsid(E){const I={id:this.extractOneOrMore(E,p,[1,64])};this.peekChar(E)===c&&(this.consumeAttributeSpace(E),I.appdata=this.extractOneOrMore(E,p,[1,64])),this.attributes.msids.push(I)}parseImageAttr(E){this.attributes.imageattr.push(E.attValue)}parseRid(E){const I=this.extractOneOrMore(E,F=>m(F)||l(F)||F==="_"||F==="-");this.consumeAttributeSpace(E);const b={id:I,direction:this.extract(E,this.consumeToken),params:[]};if(this.peekChar(E)===c){if(this.consumeAttributeSpace(E),this.peek(E,"pt=")){this.extract(E,this.consume,"pt=");const F=[];for(;;){const ct=this.extract(E,this.consumeToken);F.push(ct);try{this.extract(E,this.consume,",")}catch(Wt){break}}b.payloads=F,this.peekChar(E)===c&&this.extract(E,this.consume,c)}for(;;){const F=this.extract(E,this.consumeToken);switch(F){case"depend":{const ct={type:F,rids:this.extract(E,this.consume,"=").split(",")};b.params.push(ct);break}default:{const ct={type:F};this.peekChar(E)==="="&&(this.extract(E,this.consume,"="),ct.val=this.extract(E,this.consumeTill,";")),b.params.push(ct)}}try{this.extract(E,this.consume,";")}catch(ct){break}}}this.attributes.rids.push(b)}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,l,[1,5])}parseMaxMessageSize(E){this.attributes.maxMessageSize=this.extractOneOrMore(E,l,[1,void 0])}digest(){return this.digested=!0,this.attributes}parseMid(E){this.attributes.mid=this.extract(E,this.consumeToken)}parseSSRCGroup(E){const I=this.extract(E,this.consumeToken),b=[];for(;;)try{this.consumeAttributeSpace(E);const F=this.extract(E,this.consumeInteger);b.push(parseInt(F,10))}catch(F){break}this.attributes.ssrcGroups.push({semantic:I,ssrcIds:b})}}function rt(x,E,I){return E in x?Object.defineProperty(x,E,{value:I,enumerable:!0,configurable:!0,writable:!0}):x[E]=I,x}class Kt{constructor(){rt(this,"eol",a)}print(E,I){let b="";return I&&(this.eol=I),b+=this.printVersion(E.version),b+=this.printOrigin(E.origin),b+=this.printSessionName(E.sessionName),b+=this.printInformation(E.information),b+=this.printUri(E.uri),b+=this.printEmail(E.emails),b+=this.printPhone(E.phones),b+=this.printConnection(E.connection),b+=this.printBandwidth(E.bandwidths),b+=this.printTimeFields(E.timeFields),b+=this.printKey(E.key),b+=this.printSessionAttributes(E.attributes),b+=this.printMediaDescription(E.mediaDescriptions),b}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 I="";for(const b of E)I+="e=".concat(b).concat(this.eol);return I}printPhone(E){let I="";for(const b of E)I+="e=".concat(b).concat(this.eol);return I}printConnection(E){return E?"c=".concat(E.nettype," ").concat(E.addrtype," ").concat(E.address).concat(this.eol):""}printBandwidth(E){let I="";for(const b of E)I+="b=".concat(b.bwtype,":").concat(b.bandwidth).concat(this.eol);return I}printTimeFields(E){let I="";for(const b of E){I+="t=".concat(b.time.startTime," ").concat(b.time.startTime).concat(this.eol);for(const F of b.repeats)I+="r=".concat(F.repeatInterval," ").concat(F.typedTimes.join(" ")).concat(this.eol);b.zoneAdjustments&&(I+="z=",I+="z=".concat(b.zoneAdjustments.map(F=>"".concat(F.time," ").concat(F.back?"-":""," ").concat(F.typedTime)).join(" ")).concat(this.eol),I+=this.eol)}return I}printKey(E){return E?"k=".concat(E).concat(this.eol):""}printAttributes(E){let I="";for(const b of E)I+="a=".concat(b.attField).concat(b.attValue?":".concat(b.attValue):"").concat(this.eol);return I}printMediaDescription(E){let I="";for(const b of E)I+=this.printMedia(b.media),I+=this.printInformation(b.information),I+=this.printConnections(b.connections),I+=this.printBandwidth(b.bandwidths),I+=this.printKey(b.key),I+=this.printMediaAttributes(b);return I}printConnections(E){let I="";for(const b of E)I+=this.printConnection(b);return I}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 Ii(this.eol).print(E)}printMediaAttributes(E){return new U(this.eol).print(E)}}class Ft{constructor(E){rt(this,"eol",void 0),this.eol=E}printIceUfrag(E){return E===void 0?"":"a=ice-ufrag:".concat(E).concat(this.eol)}printIcePwd(E){return E===void 0?"":"a=ice-pwd:".concat(E).concat(this.eol)}printIceOptions(E){return E===void 0?"":"a=ice-options:".concat(E.join(c)).concat(this.eol)}printFingerprints(E){return E.length>0?E.map(I=>"a=fingerprint:".concat(I.hashFunction).concat(c).concat(I.fingerprint)).join(this.eol)+this.eol:""}printExtmap(E){return E.map(I=>"a=extmap:".concat(I.entry).concat(I.direction?"/".concat(I.direction):"").concat(c).concat(I.extensionName).concat(I.extensionAttributes?"".concat(c).concat(I.extensionAttributes):"").concat(this.eol)).join("")}printSetup(E){return E===void 0?"":"a=setup:".concat(E).concat(this.eol)}printUnrecognized(E){return E.map(I=>"a=".concat(I.attField).concat(I.attValue?":".concat(I.attValue):"").concat(this.eol)).join("")}}class Ii extends Ft{print(E){let I="";return I+=this.printGroups(E.groups),I+=this.printMsidSemantic(E.msidSemantic),I+=this.printIceLite(E.iceLite),I+=this.printIceUfrag(E.iceUfrag),I+=this.printIcePwd(E.icePwd),I+=this.printIceOptions(E.iceOptions),I+=this.printFingerprints(E.fingerprints),I+=this.printSetup(E.setup),I+=this.printTlsId(E.tlsId),I+=this.printIdentity(E.identities),I+=this.printExtmap(E.extmaps),I+=this.printUnrecognized(E.unrecognized),I}printGroups(E){let I="";return E.length>0&&(I+=E.map(b=>"a=group:".concat(b.semantic).concat(b.identificationTag.map(F=>"".concat(c).concat(F)).join("")).concat(this.eol)).join("")),I}printIceLite(E){return E===void 0?"":"a=ice-lite"+this.eol}printTlsId(E){return E?"a=tls-id:".concat(E).concat(this.eol):""}printIdentity(E){return E.length===0?"":E.map(I=>"a=identity:".concat(I.assertionValue).concat(I.extensions.map(b=>"".concat(c).concat(b.name).concat(b.value?"=".concat(b.value):"")))).join(this.eol)+this.eol}printMsidSemantic(E){if(!E)return"";let I="a=msid-semantic:".concat(E.semantic);return E.applyForAll?I+="".concat(c,"*"):E.identifierList.length>0&&(I+=E.identifierList.map(b=>"".concat(c).concat(b))),I+this.eol}}class U extends Ft{print(E){const I=E.attributes;let b="";return b+=this.printRTCP(I.rtcp),b+=this.printIceUfrag(I.iceUfrag),b+=this.printIcePwd(I.icePwd),b+=this.printIceOptions(I.iceOptions),b+=this.printCandidates(I.candidates),b+=this.printRemoteCandidatesList(I.remoteCandidatesList),b+=this.printEndOfCandidates(I.endOfCandidates),b+=this.printFingerprints(I.fingerprints),b+=this.printSetup(I.setup),b+=this.printMid(I.mid),b+=this.printExtmap(I.extmaps),b+=this.printRTPRelated(I),b+=this.printPtime(I.ptime),b+=this.printMaxPtime(I.maxPtime),b+=this.printDirection(I.direction),b+=this.printSSRCGroups(I.ssrcGroups),b+=this.printSSRC(I.ssrcs),b+=this.printRTCPMux(I.rtcpMux),b+=this.printRTCPMuxOnly(I.rtcpMuxOnly),b+=this.printRTCPRsize(I.rtcpRsize),b+=this.printMSId(I.msids),b+=this.printImageattr(I.imageattr),b+=this.printRid(I.rids),b+=this.printSimulcast(I.simulcast),b+=this.printSCTPPort(I.sctpPort),b+=this.printMaxMessageSize(I.maxMessageSize),b+=this.printUnrecognized(I.unrecognized),b}printCandidates(E){return E.map(I=>"a=candidate:".concat(I.foundation).concat(c).concat(I.componentId).concat(c).concat(I.transport).concat(c).concat(I.priority).concat(c).concat(I.connectionAddress).concat(c).concat(I.port).concat(c,"typ").concat(c).concat(I.type).concat(I.relAddr?"".concat(c,"raddr").concat(c).concat(I.relAddr):"").concat(I.relPort?"".concat(c,"rport").concat(c).concat(I.relPort):"").concat(Object.keys(I.extension).map(b=>"".concat(c).concat(b).concat(c).concat(I.extension[b])).join("")).concat(this.eol)).join("")}printRemoteCandidatesList(E){return E.map(I=>"a=remote-candidates:".concat(I.join(c)).concat(this.eol)).join("")}printEndOfCandidates(E){return E===void 0?"":"a=end-of-candidates"+this.eol}printRTPRelated(E){if(!E.payloads)return"";const I=E.payloads;let b="";b+=E.rtcpFeedbackWildcards.map(F=>this.printRTCPFeedback("*",F)).join("");for(const F of I)b+=this.printRtpMap(F.payloadType,F.rtpMap),b+=this.printFmtp(F.payloadType,F.fmtp),b+=F.rtcpFeedbacks.map(ct=>this.printRTCPFeedback(F.payloadType,ct)).join("");return b}printFmtp(E,I){if(!I)return"";const b=Object.keys(I.parameters);return b.length===1&&I.parameters[b[0]]===null?"a=fmtp:".concat(E).concat(c).concat(b[0]).concat(this.eol):"a=fmtp:".concat(E).concat(c).concat(Object.keys(I.parameters).map(F=>"".concat(F,"=").concat(I.parameters[F])).join(";")).concat(this.eol)}printRtpMap(E,I){return I?"a=rtpmap:".concat(E).concat(c).concat(I.encodingName,"/").concat(I.clockRate).concat(I.encodingParameters?"/".concat(I.encodingParameters):"").concat(this.eol):""}printRTCPFeedback(E,I){let b="a=rtcp-fb:".concat(E).concat(c),F=I;return F.type==="trr-int"?b+="ttr-int".concat(c).concat(F.interval):(b+="".concat(F.type),F.parameter&&(b+="".concat(c).concat(F.parameter),F.additional&&(b+="".concat(c).concat(F.additional)))),b+this.eol}printPtime(E){return E===void 0?"":"a=ptime:".concat(E).concat(this.eol)}printMaxPtime(E){return E===void 0?"":"a=maxptime:".concat(E).concat(this.eol)}printDirection(E){return E===void 0?"":"a=".concat(E).concat(this.eol)}printSSRC(E){return E.map(I=>Object.keys(I.attributes).map(b=>"a=ssrc:".concat(I.ssrcId.toString(10)).concat(c).concat(b).concat(I.attributes[b]?":".concat(I.attributes[b]):"").concat(this.eol)).join("")).join("")}printRTCPMux(E){return E===void 0?"":"a=rtcp-mux".concat(this.eol)}printRTCPMuxOnly(E){return E===void 0?"":"a=rtcp-mux-only".concat(this.eol)}printRTCPRsize(E){return E===void 0?"":"a=rtcp-rsize".concat(this.eol)}printRTCP(E){if(E===void 0)return"";let I="a=rtcp:".concat(E.port);return E.netType&&(I+="".concat(c).concat(E.netType)),E.addressType&&(I+="".concat(c).concat(E.addressType)),E.address&&(I+="".concat(c).concat(E.address)),I+this.eol}printMSId(E){return E.map(I=>"a=msid:".concat(I.id).concat(I.appdata?"".concat(c).concat(I.appdata):"").concat(this.eol)).join("")}printImageattr(E){return E.map(I=>"a=imageattr:".concat(I).concat(this.eol)).join("")}printRid(E){return E.map(I=>{let b="a=rid:".concat(I.id).concat(c).concat(I.direction);return I.payloads&&(b+="".concat(c,"pt=").concat(I.payloads.join(","))),I.params.length>0&&(b+="".concat(c).concat(I.params.map(F=>F.type==="depend"?"depend=".concat(F.rids.join(",")):"".concat(F.type,"=").concat(F.val)).join(";"))),b+this.eol}).join("")}printSimulcast(E){return E===void 0?"":"a=simulcast:".concat(E).concat(this.eol)}printSCTPPort(E){return E===void 0?"":"a=sctp-port:".concat(E).concat(this.eol)}printMaxMessageSize(E){return E===void 0?"":"a=max-message-size:".concat(E).concat(this.eol)}printMid(E){return E===void 0?"":"a=mid:".concat(E).concat(this.eol)}printSSRCGroups(E){return E.map(I=>"a=ssrc-group:".concat(I.semantic).concat(I.ssrcIds.map(b=>"".concat(c).concat(b.toString(10))).join("")).concat(this.eol)).join("")}}function B(x){return new j().parse(x)}function X(x,E){return new Kt().print(x,E)}}},e={};function i(n){if(e[n])return e[n].exports;var r=e[n]={exports:{}};return t[n](r,r.exports,i),r.exports}return i.d=(n,r)=>{for(var o in r)i.o(r,o)&&!i.o(n,o)&&Object.defineProperty(n,o,{enumerable:!0,get:r[o]})},i.o=(n,r)=>Object.prototype.hasOwnProperty.call(n,r),i.r=n=>{typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},i(8)})();function Ni(t){return LI.parse(t)}function mo(t,e){return LI.print(t,e)}var qG=Sn("Array","keys"),zG=no,XG=ti,JG=$e,QG=qG,QE=Array.prototype,ZG={DOMTokenList:!0,NodeList:!0},$G=function(t){var e=t.keys;return t===QE||JG(QE,t)&&e===QE.keys||XG(ZG,zG(t))?QG:e},Ji=Pt($G);function se(t,e,i){return(e=function(n){var r=function(o,s){if(typeof o!="object"||!o)return o;var a=o[Symbol.toPrimitive];if(a!==void 0){var c=a.call(o,"string");if(typeof c!="object")return c;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}(n);return typeof r=="symbol"?r:r+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function kI(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function ut(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?kI(Object(i),!0).forEach(function(n){se(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):kI(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}const MI=new class extends $t{constructor(){super(...arguments),se(this,"currentUploadLogID",0)}reportLogUploadError(t){const{errorRange:e}=t;e[e.length-1]&&e[e.length-1]>this.currentUploadLogID&&(this.currentUploadLogID=e[e.length-1],this.emit("REPORT_LOG_UPLOAD",t))}};class t3{constructor(e){se(this,"logger",void 0),se(this,"prefixLists",[]),this.logger=e}debug(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];this.logger.debug(...this.prefixLists,...i)}info(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];this.logger.info(...this.prefixLists,...i)}warning(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];this.logger.warning(...this.prefixLists,...i)}error(){for(var e=arguments.length,i=new Array(e),n=0;n<e;n++)i[n]=arguments[n];this.logger.error(...this.prefixLists,...i)}prefix(e){return this.prefixLists.push(e),this}popPrefix(){return this.prefixLists.pop(),this}}function ZE(){const t=new Date;return t.toTimeString().split(" ")[0]+":"+t.getMilliseconds()}function UI(){const t=new Date,e=/((\d+:){2}\d+)/.exec(new Date().toUTCString());return e?(e==null?void 0:e[0])+":"+t.getUTCMilliseconds():t.toTimeString().split(" ")[0]+":"+t.getMilliseconds()}const ln={DEBUG:0,INFO:1,WARNING:2,ERROR:3,NONE:4},mu=Date.now(),Mc=t=>{for(const e in ln)if(Object.prototype.hasOwnProperty.call(ln,e)&&ln[e]===t)return e;return"DEFAULT"},_=new class{constructor(){se(this,"proxyServerURL",void 0),se(this,"logLevel",ln.DEBUG),se(this,"uploadState","collecting"),se(this,"uploadLogWaitingList",[]),se(this,"uploadLogUploadingList",[]),se(this,"uploadErrorCount",0),se(this,"currentLogID",0),se(this,"url",void 0),se(this,"extLog",(t,e)=>{this.appendLogToWaitingList(t,...e)})}debug(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const n=[ln.DEBUG].concat(e);this.log.apply(this,n)}info(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const n=[ln.INFO].concat(e);this.log.apply(this,n)}warning(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const n=[ln.WARNING].concat(e);this.log.apply(this,n)}warn(){this.warning(...arguments)}error(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const n=[ln.ERROR].concat(e);this.log.apply(this,n)}upload(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const n=[ln.DEBUG].concat(e);this.uploadLog.apply(this,n)}setLogLevel(t){t=Math.min(Math.max(0,t),4),this.logLevel=t}enableLogUpload(){kt("UPLOAD_LOG",!0)}disableLogUpload(){kt("UPLOAD_LOG",!1),this.uploadLogUploadingList=[],this.uploadLogWaitingList=[]}setProxyServer(t){this.proxyServerURL=t}prefix(t){return new t3(this).prefix(t)}log(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];if(Date.now()-mu<100)return void setTimeout(()=>{this.log(...e)},Date.now()-mu);const n=Math.max(0,Math.min(4,e[0]));if(e[0]=ZE()+" Agora-SDK [".concat(Mc(n),"]:"),this.appendLogToWaitingList(n,...e),n<this.logLevel)return;const r=ZE()+" %cAgora-SDK [".concat(Mc(n),"]:");let o=[];if(!y("USE_NEW_LOG"))switch(n){case ln.DEBUG:o=[r,"color: #64B5F6;"].concat(e.slice(1)),console.log.apply(console,o);break;case ln.INFO:o=[r,"color: #1E88E5; font-weight: bold;"].concat(e.slice(1)),console.log.apply(console,o);break;case ln.WARNING:o=[r,"color: #FB8C00; font-weight: bold;"].concat(e.slice(1)),console.warn.apply(console,o);break;case ln.ERROR:o=[r,"color: #B00020; font-weight: bold;"].concat(e.slice(1)),console.error.apply(console,o)}}uploadLog(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];if(Date.now()-mu<100)return void setTimeout(()=>{this.uploadLog(...e)},Date.now()-mu);const n=Math.max(0,Math.min(4,e[0]));e[0]=ZE()+" Agora-SDK [".concat(Mc(n),"]:"),this.appendLogToWaitingList(n,...e)}appendLogToWaitingList(t){if(!y("UPLOAD_LOG"))return;for(var e=arguments.length,i=new Array(e>1?e-1:0),n=1;n<e;n++)i[n-1]=arguments[n];Array.isArray(i[0])?i[0][0]=UI()+" Agora-SDK [".concat(Mc(t),"]:"):i[0]=UI()+" Agora-SDK [".concat(Mc(t),"]:");let r="";i.forEach(o=>{typeof o=="object"&&(o=JSON.stringify(o)),r+="".concat(o," ")}),this.uploadLogWaitingList.push({payload_str:r,log_level:t,log_item_id:this.currentLogID++}),this.uploadState==="uploading"&&this.uploadLogUploadingList.length===0&&this.uploadLogInterval()}startUpload(){this.uploadState="uploading",this.uploadLogUploadingList.length===0&&this.uploadLogInterval()}uploadLogs(){return C(this,null,function*(){const t=this.uploadLogUploadingList,e={sdk_version:dn,process_id:y("PROCESS_ID"),payload:JSON.stringify(t)};return Jn(()=>C(this,null,function*(){const i=yield Ti.post(this.url||(this.proxyServerURL?"https://".concat(this.proxyServerURL,"/ls/?h=").concat(y("LOG_UPLOAD_SERVER"),"&p=443&d=upload/v1"):"https://".concat(y("LOG_UPLOAD_SERVER"),"/upload/v1")),e,{responseType:"text"});if(i.data!=="OK"){const n=new Error("unexpected upload log response");throw n.response=i,n}}),()=>(this.uploadLogUploadingList=[],!1),i=>{const n={status:-1,message:i.message,errorRange:t.map(r=>r.log_item_id)};return i.response?(n.status=i.response.status,n.data=i.response.data,n.headers=i.response.headers):i.request&&(n.status=i.request.status),MI.reportLogUploadError(n),!0},{timeout:y("UPLOAD_LOG_REQUEST_RETRY_INTERVAL"),maxRetryTimeout:y("UPLOAD_LOG_REQUEST_MAX_RETRY_INTERVAL")})})}uploadLogInterval(){this.uploadLogUploadingList.length===0&&this.uploadLogWaitingList.length===0||(this.uploadLogUploadingList.length===0&&(this.uploadLogUploadingList=this.uploadLogWaitingList.splice(0,y("UPLOAD_LOG_LENGTH_EACH_TIME"))),this.uploadLogs().then(()=>{this.uploadErrorCount=0,this.uploadLogWaitingList.length>0&&window.setTimeout(()=>this.uploadLogInterval(),y("UPLOAD_LOG_INTERVAL"))}).catch(t=>{this.uploadErrorCount+=1,this.uploadErrorCount<2?window.setTimeout(()=>this.uploadLogInterval(),y("UPLOAD_LOG_TWICE_RETRY_INTERVAL_V1")):window.setTimeout(()=>this.uploadLogInterval(),y("UPLOAD_LOG_RETRY_INTERVAL_V1"))}))}};var xI;function e3(t){return Me(t.reportId,"params.reportId",0,100,!1),Me(t.category,"params.category",0,100,!1),Me(t.event,"params.event",0,100,!1),Me(t.label,"params.label",0,100,!1),xt(t.value,"params.value",Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,!1),!0}(xI={}).FREE="free",xI.UPLOADING="uploading",function(t){t[t.MISC=0]="MISC",t[t.INTERNAL_EVENT=1]="INTERNAL_EVENT",t[t.PUBLIC_EVENT=2]="PUBLIC_EVENT",t[t.WEB_EVENT=3]="WEB_EVENT",t[t.INTERNAL_API=4]="INTERNAL_API",t[t.WEB_API=5]="WEB_API",t[t.PUBLIC_API=6]="PUBLIC_API"}({});const i3={sid:"",lts:0,success:null,cname:null,uid:null,peer:null,cid:null,elapse:null,extend:null,vid:0};let Oe=function(t){return t.PUBLISH="publish",t.SUBSCRIBE="subscribe",t.WS_COMPRESSOR_INIT="ws_compressor_init",t.SESSION_INIT="session_init",t.JOIN_CHOOSE_SERVER="join_choose_server",t.REQ_USER_ACCOUNT="req_user_account",t.JOIN_GATEWAY="join_gateway",t.REJOIN_GATEWAY="rejoin_gateway",t.STREAM_SWITCH="stream_switch",t.REQUEST_PROXY_WORKER_MANAGER="request_proxy_worker_manager",t.REQUEST_PROXY_APPCENTER="request_proxy_appcenter",t.FIRST_VIDEO_RECEIVED="first_video_received",t.FIRST_AUDIO_RECEIVED="first_audio_received",t.FIRST_VIDEO_DECODE="first_video_decode",t.FIRST_AUDIO_DECODE="first_audio_decode",t.ON_ADD_AUDIO_STREAM="on_add_audio_stream",t.ON_ADD_VIDEO_STREAM="on_add_video_stream",t.ON_UPDATE_STREAM="on_update_stream",t.ON_REMOVE_STREAM="on_remove_stream",t.USER_ANALYTICS="req_user_analytics",t.PC_STATS="pc_stats",t.UPDATE_REMOTE_RTPCAPABILITIES="update_remote_rtpCapabilities",t.AB_TEST="ab_test",t}({}),Jt=function(t){return t.SESSION="io.agora.pb.Wrtc.Session",t.JOIN_CHOOSE_SERVER="io.agora.pb.Wrtc.JoinChooseServer",t.REQ_USER_ACCOUNT="io.agora.pb.Wrtc.ReqUserAccount",t.JOIN_GATEWAY="io.agora.pb.Wrtc.JoinGateway",t.RE_JOIN_GATEWAY="io.agora.pb.Wrtc.ReJoinGateway",t.PUBLISH="io.agora.pb.Wrtc.Publish",t.SUBSCRIBE="io.agora.pb.Wrtc.Subscribe",t.WS_COMPRESSOR_INIT="io.agora.pb.Wrtc.WsCompressorInit",t.STREAM_SWITCH="io.agora.pb.Wrtc.StreamSwitch",t.AUDIO_SENDING_STOPPED="io.agora.pb.Wrtc.AudioSendingStopped",t.VIDEO_SENDING_STOPPED="io.agora.pb.Wrtc.VideoSendingStopped",t.REQUEST_PROXY_APPCENTER="io.agora.pb.Wrtc.RequestProxyAppCenter",t.REQUEST_PROXY_WORKER_MANAGER="io.agora.pb.Wrtc.RequestProxyWorkerManager",t.API_INVOKE="io.agora.pb.Wrtc.ApiInvoke",t.FIRST_VIDEO_RECEIVED="io.agora.pb.Wrtc.FirstVideoReceived",t.FIRST_AUDIO_RECEIVED="io.agora.pb.Wrtc.FirstAudioReceived",t.FIRST_VIDEO_DECODE="io.agora.pb.Wrtc.FirstVideoDecode",t.FIRST_AUDIO_DECODE="io.agora.pb.Wrtc.FirstAudioDecode",t.ON_ADD_AUDIO_STREAM="io.agora.pb.Wrtc.OnAddAudioStream",t.ON_ADD_VIDEO_STREAM="io.agora.pb.Wrtc.OnAddVideoStream",t.ON_UPDATE_STREAM="io.agora.pb.Wrtc.OnUpdateStream",t.ON_REMOVE_STREAM="io.agora.pb.Wrtc.OnRemoveStream",t.JOIN_CHANNEL_TIMEOUT="io.agora.pb.Wrtc.JoinChannelTimeout",t.PEER_PUBLISH_STATUS="io.agora.pb.Wrtc.PeerPublishStatus",t.WORKER_EVENT="io.agora.pb.Wrtc.WorkerEvent",t.AP_WORKER_EVENT="io.agora.pb.Wrtc.APWorkerEvent",t.JOIN_WEB_PROXY_AP="io.agora.pb.Wrtc.JoinWebProxyAP",t.WEBSOCKET_QUIT="io.agora.pb.Wrtc.WebSocketQuit",t.USER_ANALYTICS="io.agora.pb.Wrtc.UserAnalytics",t.AUTOPLAY_FAILED="io.agora.pb.Wrtc.AutoplayFailed",t.PC_STATS="io.agora.pb.Wrtc.PCStats",t.UPDATE_REMOTE_RTPCAPABILITIES="io.agora.pb.Wrtc.UpdateRemoteRTPCapabilities",t.AB_TEST="io.agora.pb.Wrtc.ABTest",t}({});(function(t){t[t.WORKER_EVENT=156]="WORKER_EVENT",t[t.AP_WORKER_EVENT=160]="AP_WORKER_EVENT"})({});let n3=function(t){return t[t.SESSION=26]="SESSION",t[t.JOIN_CHOOSE_SERVER=27]="JOIN_CHOOSE_SERVER",t[t.REQ_USER_ACCOUNT=196]="REQ_USER_ACCOUNT",t[t.JOIN_GATEWAY=28]="JOIN_GATEWAY",t[t.PUBLISH=30]="PUBLISH",t[t.SUBSCRIBE=29]="SUBSCRIBE",t[t.WS_COMPRESSOR_INIT=9430]="WS_COMPRESSOR_INIT",t[t.STREAM_SWITCH=32]="STREAM_SWITCH",t[t.AUDIO_SENDING_STOPPED=33]="AUDIO_SENDING_STOPPED",t[t.VIDEO_SENDING_STOPPED=34]="VIDEO_SENDING_STOPPED",t[t.REQUEST_PROXY_APPCENTER=35]="REQUEST_PROXY_APPCENTER",t[t.REQUEST_PROXY_WORKER_MANAGER=36]="REQUEST_PROXY_WORKER_MANAGER",t[t.API_INVOKE=41]="API_INVOKE",t[t.FIRST_VIDEO_RECEIVED=348]="FIRST_VIDEO_RECEIVED",t[t.FIRST_AUDIO_RECEIVED=349]="FIRST_AUDIO_RECEIVED",t[t.FIRST_VIDEO_DECODE=350]="FIRST_VIDEO_DECODE",t[t.FIRST_AUDIO_DECODE=351]="FIRST_AUDIO_DECODE",t[t.ON_ADD_AUDIO_STREAM=352]="ON_ADD_AUDIO_STREAM",t[t.ON_ADD_VIDEO_STREAM=353]="ON_ADD_VIDEO_STREAM",t[t.ON_UPDATE_STREAM=356]="ON_UPDATE_STREAM",t[t.ON_REMOVE_STREAM=355]="ON_REMOVE_STREAM",t[t.JOIN_CHANNEL_TIMEOUT=407]="JOIN_CHANNEL_TIMEOUT",t[t.PEER_PUBLISH_STATUS=408]="PEER_PUBLISH_STATUS",t[t.WORKER_EVENT=156]="WORKER_EVENT",t[t.AP_WORKER_EVENT=160]="AP_WORKER_EVENT",t[t.JOIN_WEB_PROXY_AP=700]="JOIN_WEB_PROXY_AP",t[t.WEBSOCKET_QUIT=671]="WEBSOCKET_QUIT",t[t.USER_ANALYTICS=1e4]="USER_ANALYTICS",t[t.AUTOPLAY_FAILED=9178]="AUTOPLAY_FAILED",t}({});function it(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function(e,i,n){const r=n.value;if(typeof r=="function"){const o=t.className||e.__className__||(e.constructor.name==="AgoraRTCClient"?"Client":e.constructor.name);n.value=function(){for(var s,a=arguments.length,c=new Array(a),d=0;d<a;d++)c[d]=arguments[d];let l=c;if(t.argsMap)try{l=t.argsMap(this,...c)}catch(h){_.warning(h),l=[]}try{JSON.stringify(l)}catch(h){_.warning("arguments for method ".concat(o,".").concat(String(i)," not serializable for apiInvoke.")),l=[]}const u=(t.report||Z).reportApiInvoke(this._sessionId||null,{id:this._clientId||((s=this.store)===null||s===void 0?void 0:s.clientId)||this._ID,name:"".concat(o,".").concat(String(i)),options:l,tag:oe.TRACER,reportResult:t.reportResult},t.throttleTime);try{const h=r.apply(this,c);return h instanceof K?h.then(p=>(u.onSuccess(t.reportResult&&p),p)).catch(p=>{throw u.onError(p),p}):(u.onSuccess(t.reportResult&&h),h)}catch(h){throw u.onError(h),h}}}return n}}const Z=new class{constructor(){se(this,"baseInfoMap",new Map),se(this,"proxyServer",void 0),se(this,"eventUploadTimer",void 0),se(this,"setSessionIdTimer",void 0),se(this,"url",void 0),se(this,"sids",new Set),se(this,"backupUrl",void 0),se(this,"_appId",void 0),se(this,"_aid",0),se(this,"keyEventUploadPendingItems",[]),se(this,"normalEventUploadPendingItems",[]),se(this,"apiInvokeUploadPendingItems",[]),se(this,"apiInvokeCount",0),se(this,"apiInvokeLoggedCount",0),se(this,"ltsList",[]),se(this,"lastSendNormalEventTime",Date.now()),se(this,"customReportCounterTimer",void 0),se(this,"customReportCount",0),se(this,"extApiInvoke",t=>C(this,null,function*(){for(const e of t){const i=ut(ut({},e),{},{sid:null,invokeId:++this.apiInvokeCount,tag:oe.TRACER});this.sendApiInvoke(i)}})),this.eventUploadTimer=window.setInterval(this.doSend.bind(this),y("EVENT_REPORT_SEND_INTERVAL")),this.setSessionIdTimer=window.setInterval(this.appendSessionId.bind(this),y("EVENT_REPORT_SEND_INTERVAL"))}getBaseInfoBySessionId(t){return this.baseInfoMap.get(t)}setAppId(t){this._appId=t,this._aid=parseInt(t.replace(/[a-fA-F0-9]{8}/g,e=>{let[i,n]=e;return i+n}),16)||0}reportApiInvoke(t,e,i){e.timeout=e.timeout||6e4,e.reportResult=e.reportResult===void 0||e.reportResult;const n=Date.now();this.apiInvokeCount+=1;const r=this.apiInvokeCount,o=!!y("SHOW_REPORT_INVOKER_LOG"),s=!!y("SHOW_REPORT_USER_INVOKER_LOG"),a=o||s&&e.id;a&&(this.apiInvokeLoggedCount+=1);const c=this.apiInvokeLoggedCount;function d(p,g){if(a){let m="[apiInvoke-".concat(c,"]");if(e.id&&(m+="[".concat(e.id,"]")),e.name&&(m+="[".concat(e.name,"]"),e.name===_e.JOIN))return _.info("".concat(m," ").concat(p));_.info("".concat(m," ").concat(p),p==="start"?e.options:g||"")}}const l=()=>({tag:e.tag,invokeId:r,sid:t,name:e.name,apiInvokeTime:n,options:e.options,states:e.states||null});d("start");let u=!1;Ue(e.timeout).then(()=>{u||(this.sendApiInvoke(ut(ut({},l()),{},{error:v.API_INVOKE_TIMEOUT,success:!1})),d("timeout"))});const h=new k(v.UNEXPECTED_ERROR,"".concat(e.name,": this api invoke is end"));return{onSuccess:p=>{const g=()=>{if(u)throw h;return u=!0,this.sendApiInvoke(ut(ut({},l()),{},{success:!0},e.reportResult&&{result:p})),d("onSuccess"),p};return i?mI(g,e.name+"Success",i,()=>u=!0):g()},onError:p=>{const g=()=>{if(u)throw p;u=!0,this.sendApiInvoke(ut(ut({},l()),{},{success:!1,error:p})),d("onFailure",p.toString())};return i?mI(g,e.name+"Error",i,()=>u=!0):g()}}}sessionInit(t,e){if(this.baseInfoMap.has(t))return;const i=Date.now(),n=this.createBaseInfo(t,i);n.cname=e.cname;const r=Object.assign({},{willUploadConsoleLog:y("UPLOAD_LOG"),maxTouchPoints:navigator.maxTouchPoints,areaVersion:qE?"global":"oversea",areas:y("AREAS")&&y("AREAS").join(",")},e.extend),{stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientRole:l}=e,u=Date.now(),h=ut(ut({},n),{},{eventType:Oe.SESSION_INIT,appid:e.appid,browser:navigator.userAgent,buildFormat:e.buildFormat,build:XE,lts:u,elapse:u-i,extend:JSON.stringify(r),mode:e.mode,process:y("PROCESS_ID"),appType:y("APP_TYPE"),success:!0,version:dn,stringUid:o,channelProfile:s,channelMode:a,isABTestSuccess:c,lsid:d,clientType:G(p=window.navigator.userAgent).call(p,"AgoraWebView")?42:20,clientRole:l,serviceId:y("PROCESS_ID"),extensionID:y("PLUGIN_INFO").join(",")||""});var p;this.send({type:Jt.SESSION,data:h},!0)}joinChooseServer(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut({},n),{},{role:e.role,eventType:Oe.JOIN_CHOOSE_SERVER,lts:r,eventElapse:e.elapse||r-e.lts,chooseServerAddr:e.csAddr,errorCode:e.ec,elapse:r-i.startTime,success:e.succ,chooseServerAddrList:JSON.stringify(e.serverList),uid:e.uid?parseInt(e.uid):null,cid:e.cid?parseInt(e.cid):null,chooseServerIp:e.csIp||"",opid:e.opid,unilbsServerIds:e.unilbsServerIds,extend:e.extend||void 0,isHttp3:e.isHttp3,corssRegionTagReq:e.corssRegionTagReq||void 0,corssRegionTagRes:e.corssRegionTagRes||void 0});this.send({type:Jt.JOIN_CHOOSE_SERVER,data:o},!0)}reqUserAccount(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut({},n),{},{eventType:Oe.REQ_USER_ACCOUNT,lts:r,success:e.success,serverAddress:e.serverAddr,stringUid:e.stringUid,uid:e.uid,errorCode:e.errorCode,elapse:e.elapse||r-i.startTime,eventElapse:r-e.lts,extend:JSON.stringify(e.extend)});this.send({type:Jt.REQ_USER_ACCOUNT,data:o},!0)}joinGateway(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info;e.vid&&(n.vid=e.vid),n.uid=e.uid,n.cid=e.cid;const r=Date.now(),{firstSuccess:o,addr:s,isProxy:a}=e,c=r-i.startTime,d=ut(ut({},n),{},{eventType:Oe.JOIN_GATEWAY,lts:r,gatewayAddr:e.addr,success:e.succ,errorCode:e.ec,errorMsg:e.errorMsg||"",elapse:c,eventElapse:r-e.lts,firstSuccess:o,signalChannel:e.signalChannel,preload:e.preload?1:0,installId:YE(),isABTestSuccess:e.isABTestSuccess?1:0}),l=d.success?1:0;if(e.succ&&(i.lastJoinSuccessTime=r),o)this.send({type:Jt.JOIN_GATEWAY,data:d},!0);else{let u;if(s)if(a){const p=s.match(/h=(\d{1,3}-){3}\d{1,3}/g),g=s.match(/p=[0-9]{1,6}/g);u={isSuccess:l,gatewayIp:p&&p.length?p[0].split("=")[1].replace(/-/g,"."):"",port:g&&g.length?g[0].split("=")[1]:"",isProxy:a?1:0}}else{const p=s.match(/wss:\/\/(\d{1,3}-){3}\d{1,3}/g),g=s.match(/(:|p=)[0-9]{1,6}/g);u={isSuccess:l,gatewayIp:p&&p.length?p[0].split("//")[1].replace(/-/g,"."):"",port:g&&g.length?g[0].split(/:|p=/g)[1]:"",isProxy:a?1:0}}else u={isSuccess:l,gatewayIp:"",port:"",isProxy:a?1:0};delete d.success,delete d.eventType,delete d.firstSuccess,d.vid=Number(d.vid);const h=Object.assign({},d,u,{eventType:Oe.REJOIN_GATEWAY});this.send({type:Jt.RE_JOIN_GATEWAY,data:h},!0)}}joinChannelTimeout(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=Date.now(),r=ut(ut({},i.info),{},{lts:n,timeout:e,elapse:n-i.startTime});this.send({type:Jt.JOIN_CHANNEL_TIMEOUT,data:r},!0)}publish(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut({},n),{},{eventType:Oe.PUBLISH,lts:r,eventElapse:e.eventElapse,elapse:r-i.startTime,success:e.succ,errorCode:e.ec,videoName:e.videoName,audioName:e.audioName,screenName:e.screenName,screenshare:e.screenshare,audio:e.audio,video:e.video,p2pid:e.p2pid,publishRequestid:e.publishRequestid});this.send({type:Jt.PUBLISH,data:o},!0)}subscribe(t,e,i){const n=this.baseInfoMap.get(t);if(!n)return;const r=n.info,o=Date.now(),s=ut(ut({},r),{},{eventType:Oe.SUBSCRIBE,lts:o,eventElapse:e.eventElapse,elapse:o-n.startTime,success:e.succ,errorCode:e.ec,video:e.video,audio:e.audio,subscribeRequestid:e.subscribeRequestid,p2pid:e.p2pid,preSsrc:e.preSsrc?1:0},i&&{extend:JSON.stringify({isMassSubscribe:!0})});typeof e.peerid=="string"?s.peerSuid=e.peerid:s.peer=e.peerid,this.send({type:Jt.SUBSCRIBE,data:s},!0)}wsCompressorInit(t){var e;const i=[...Ji(e=this.baseInfoMap).call(e)],n=i.length?i[0]:"UnableToGetSid",r=this.baseInfoMap.get(n);if(!r)return;const o=r.info,s=Date.now(),a=ut(ut({},o),{},{eventType:Oe.WS_COMPRESSOR_INIT,lts:s,eventElapse:t.eventElapse,elapse:s-r.startTime,status:t.status?1:2});this.send({type:Jt.WS_COMPRESSOR_INIT,data:a},!0)}firstRemoteVideoDecode(t,e,i,n){const r=this.baseInfoMap.get(t);if(!r)return;const o=r.info,s=Date.now(),a=ut(ut(ut({},o),n),{},{elapse:s-r.startTime,eventType:e,lts:s,firstDecodeFrame:Math.max((n.firstFrame||s)-r.startTime,0),apEnd:Math.max(n.apEnd-r.startTime,0),apStart:Math.max(n.apStart-r.startTime,0),joinGwEnd:Math.max(n.joinGwEnd-r.startTime,0),joinGwStart:Math.max(n.joinGwStart-r.startTime,0),pcEnd:Math.max(n.pcEnd-r.startTime,0),pcStart:Math.max(n.pcStart-r.startTime,0),subscriberEnd:Math.max(n.subscriberEnd-r.startTime,0),subscriberStart:Math.max(n.subscriberStart-r.startTime,0),videoAddNotify:Math.max(n.videoAddNotify-r.startTime,0)});this.send({type:i,data:a},!0)}firstRemoteFrame(t,e,i,n){const r=this.baseInfoMap.get(t);if(!r)return;const o=r.info,s=Date.now(),a=ut(ut(ut({},o),n),{},{elapse:s-r.startTime,eventType:e,lts:s});this.send({type:i,data:a},!0)}abTest(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut(ut({},n),e),{},{vid:n.vid===void 0?0:Number(n.vid),elapse:r-i.startTime,eventType:Oe.AB_TEST,lts:r});this.send({type:Jt.AB_TEST,data:o},!0)}pcStats(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut(ut({},n),e),{},{vid:n.vid===void 0?0:Number(n.vid),elapse:r-i.startTime,eventType:Oe.PC_STATS,lts:r,preallocation:e.preallocation?1:0});this.send({type:Jt.PC_STATS,data:o},!0)}updateRemoteRTPCapabilities(t,e){if(t){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut(ut({},n),e),{},{vid:n.vid===void 0?0:Number(n.vid),eventType:Oe.UPDATE_REMOTE_RTPCAPABILITIES,lts:r});this.send({type:Jt.UPDATE_REMOTE_RTPCAPABILITIES,data:o},!0)}}onGatewayStream(t,e,i,n){const r=this.baseInfoMap.get(t);if(!r)return;const o=r.info,s=Date.now(),a=ut(ut(ut({},o),n),{},{eventType:e,lts:s});this.send({type:i,data:a},!0)}streamSwitch(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut({},n),{},{eventType:Oe.STREAM_SWITCH,lts:r,isDual:e.isdual,elapse:r-i.startTime,success:e.succ});this.send({type:Jt.STREAM_SWITCH,data:o},!0)}requestProxyAppCenter(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut({},n),{},{eventType:Oe.REQUEST_PROXY_APPCENTER,lts:r,eventElapse:r-e.lts,elapse:r-i.startTime,APAddr:e.APAddr,workerManagerList:e.workerManagerList,response:e.response,errorCode:e.ec,success:e.succ});this.send({type:Jt.REQUEST_PROXY_APPCENTER,data:o},!0)}requestProxyWorkerManager(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut({},n),{},{eventType:Oe.REQUEST_PROXY_WORKER_MANAGER,lts:r,eventElapse:r-e.lts,elapse:r-i.startTime,workerManagerAddr:e.workerManagerAddr,response:e.response,errorCode:e.ec,success:e.succ});this.send({type:Jt.REQUEST_PROXY_WORKER_MANAGER,data:o},!0)}setProxyServer(t){this.proxyServer=t,t?_.debug("reportProxyServerurl: ".concat(t)):_.debug("disable reportProxyServerurl: ".concat(t))}peerPublishStatus(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut({},n),{},{subscribeElapse:e.subscribeElapse,peer:e.peer,peerPublishDuration:Math.max(e.audioPublishDuration,e.videoPublishDuration),audiotag:e.audioPublishDuration>0?1:-1,videotag:e.videoPublishDuration>0?1:-1,lts:r,elapse:r-i.startTime,joinChannelSuccessElapse:r-(i.lastJoinSuccessTime||r),peerPublishDurationVideo:e.videoPublishDuration,peerPublishDurationAudio:e.audioPublishDuration});this.send({type:Jt.PEER_PUBLISH_STATUS,data:o},!0)}workerEvent(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now();(function(o,s,a){const c=o[s];if(!c||typeof c!="string")return[o];o[s]="";const d=Er(JSON.stringify(o));let l=0;const u=[];let h=0;for(let p=0;p<c.length;p++)h+=c.charCodeAt(p)<=127?1:3,h<=a-d||(u[u.length]=z(z({},o),{},{[s]:c.substring(l,p)}),l=p,h=c.charCodeAt(p)<=127?1:3);return l!==c.length-1&&(u[u.length]=z(z({},o),{},{[s]:c.substring(l)})),u})(ut(ut(ut({},n),e),{},{elapse:r-i.startTime,lts:r,productType:"WebRTC"}),"payload",1300).forEach(o=>this.send({type:Jt.WORKER_EVENT,data:o},!0))}apworkerEvent(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut(ut({},n),e),{},{elapse:r-i.startTime,lts:r});this.send({type:Jt.AP_WORKER_EVENT,data:o},!0)}joinWebProxyAP(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut(ut({},n),e),{},{elapse:r-i.startTime,lts:r,extend:e.extend||void 0});this.send({type:Jt.JOIN_WEB_PROXY_AP,data:o},!0)}WebSocketQuit(t,e){const i=this.baseInfoMap.get(t);if(!i)return;const n=i.info,r=Date.now(),o=ut(ut(ut({},n),e),{},{elapse:r-i.startTime,lts:r});this.send({type:Jt.WEBSOCKET_QUIT,data:o},!0)}sendCustomReportMessage(t,e){return C(this,null,function*(){if(this.customReportCount+=e.length,this.customReportCount>y("CUSTOM_REPORT_LIMIT"))throw new k(v.CUSTOM_REPORT_FREQUENCY_TOO_HIGH);this.customReportCounterTimer||(this.customReportCounterTimer=window.setInterval(()=>{this.customReportCount=0},5e3));const i=Date.now(),n=e.map(r=>({type:Jt.USER_ANALYTICS,data:ut(ut({sid:t},r),{},{lts:i})}));try{y("NEW_REPORT_SERVER")?yield this.postDataToStatsCollector2(n):yield this.postDataToStatsCollector(n)}catch(r){throw _.error("send custom report message failed",r.toString()),new k(v.CUSTOM_REPORT_SEND_FAILED,r.message)}})}sendApiInvoke(t){const e=y("NOT_REPORT_EVENT");if(t.tag&&G(e)&&G(e).call(e,t.tag))return!1;if(t.sid===null)return this.apiInvokeUploadPendingItems.push(t),!1;const i=this.baseInfoMap.get(t.sid);if(!i)return this.apiInvokeUploadPendingItems.push(t),!1;const{cname:n,uid:r,cid:o}=i.info;let s;if(t.lts=t.lts||Date.now(),t.error)if(t.error instanceof k){const{code:c,message:d}=t.error;s=c||d||t.error.toString()}else s=t.error.toString();const a={invokeId:t.invokeId,sid:t.sid,cname:n,cid:o,uid:r,lts:t.lts,success:t.success,elapse:t.lts-i.startTime,execElapse:t.lts-t.apiInvokeTime,apiName:t.name,options:t.options?JSON.stringify(t.options):void 0,execStates:t.states?JSON.stringify(t.states):void 0,execResult:t.result?JSON.stringify(t.result):void 0,errorCode:t.error?s:void 0,errorMsg:t.error?JSON.stringify(t.error):void 0};return this.send({type:Jt.API_INVOKE,data:a},!1),!0}addSid(t){this.sids.add(t)}removeSid(t){this.sids.delete(t)}appendSessionId(){const t=this.apiInvokeUploadPendingItems;if(t.length===0)return;const e=Array.from(this.sids).find(i=>i!==null);e&&t.forEach(i=>{i&&(i.sid=e,this.sendApiInvoke(Object.assign({},i)))}),t.length=0}send(t,e){if(e)return this.keyEventUploadPendingItems.push(t),void this.sendItems(this.keyEventUploadPendingItems,!0);this.normalEventUploadPendingItems.push(t),this.normalEventUploadPendingItems.length>y("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(t,e){const i=[],n=[];for(;t.length;){const o=t.shift();i.length<20?i.push(o):n.push(o)}t.push(...n);for(const o of[...i]){var r;this.ltsList.indexOf(o.data.lts)!==-1?(o.data.lts=this.ltsList[this.ltsList.length-1]+1,this.ltsList.push(o.data.lts)):(this.ltsList.push(o.data.lts),jo(r=this.ltsList).call(r,(s,a)=>s-a))}return e||(this.lastSendNormalEventTime=Date.now()),y("ENABLE_EVENT_REPORT")&&i.length&&(y("NEW_REPORT_SERVER")?this.postDataToStatsCollector2(i):this.postDataToStatsCollector(i)).catch((o=>s=>{y("EVENT_REPORT_RETRY")&&(e?this.keyEventUploadPendingItems=this.keyEventUploadPendingItems.concat(o):(this.normalEventUploadPendingItems=this.normalEventUploadPendingItems.concat(o),this.normalEventUploadPendingItems.length>y("NORMAL_EVENT_QUEUE_CAPACITY")&&(this.normalEventUploadPendingItems.splice(0,this.normalEventUploadPendingItems.length-y("NORMAL_EVENT_QUEUE_CAPACITY")),_.warning("report: drop normal events"))))})(i)),t}postDataToStatsCollector2(t){return C(this,null,function*(){Ee.networkState===Fi.OFFLINE&&(yield K.race([Ee.onlineWaiter,Ue(2*ge.maxRetryTimeout)]));const e=r=>{let o=new Uint8Array;return r.forEach(s=>{const a=LE(JSON.stringify(s.data)),c=new ArrayBuffer(5),d=(u=>{let h=0;return Object.entries(Jt).forEach(p=>{let[g,m]=p;m===u.type&&(h=n3[g])}),h})(s),l=new DataView(c);l.setUint16(0,a.byteLength,!0),l.setUint8(2,255&d),l.setUint8(3,d>>>8&255),l.setUint8(4,d>>>16&255),o=aI(o,new Uint8Array(c)),o=aI(o,a)}),o},i="event";let n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(y("NEW_REPORT_SERVER_DOMAINS")[0],"&p=443&d=").concat(i):"https://".concat(y("NEW_REPORT_SERVER_DOMAINS")[0],"/").concat(i);for(let r=0;r<2;r+=1){r===1&&(n=this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(y("NEW_REPORT_SERVER_DOMAINS")[1],"&p=443&d=").concat(i):"https://".concat(y("NEW_REPORT_SERVER_DOMAINS")[1],"/").concat(i));try{yield jE(n,{timeout:1e4,data:e(t),headers:ut(ut({biz:"webrtc",sendts:Math.round(Date.now()/1e3),debug:"false"},this._appId&&{appid:this._appId}),{},{"Content-Type":"application/octet-stream"})},!0)}catch(o){if(r===1)throw o;continue}return}})}postDataToStatsCollector(e){return C(this,arguments,function*(t){let i=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const n=(c=>{const d=c&&c.data.sid&&this.baseInfoMap.get(c.data.sid);return d&&d.info.vid&&+d.info.vid||0})(t[0]),r=n?void 0:this._aid,o={msgType:"EventMessages",sentTs:Math.round(Date.now()/1e3),payloads:t.map(c=>JSON.stringify(c)),vid:n,aid:r};Ee.networkState===Fi.OFFLINE&&(yield K.race([Ee.onlineWaiter,Ue(2*ge.maxRetryTimeout)]));const s=i?"/events/proto-raws":"/events/messages";let a=this.url||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(y("EVENT_REPORT_DOMAIN"),"&p=").concat(y("STATS_COLLECTOR_PORT"),"&d=").concat(s):"https://".concat(y("EVENT_REPORT_DOMAIN"),":").concat(y("STATS_COLLECTOR_PORT")).concat(s));for(let c=0;c<2;c+=1){c===1&&(a=this.backupUrl||(this.proxyServer?"https://".concat(this.proxyServer,"/rs/?h=").concat(y("EVENT_REPORT_BACKUP_DOMAIN"),"&p=").concat(y("STATS_COLLECTOR_PORT"),"&d=").concat(s):"https://".concat(y("EVENT_REPORT_BACKUP_DOMAIN"),":").concat(y("STATS_COLLECTOR_PORT")).concat(s)));try{i?yield GG(a,{timeout:1e4,data:o}):yield jE(a,{timeout:1e4,data:o})}catch(d){if(c===1)throw d;continue}return}})}createBaseInfo(t,e){const i=Object.assign({},i3);return i.sid=t,this.baseInfoMap.set(t,{info:i,startTime:e}),i}reportResourceTiming(t,e){const i=performance.getEntriesByName(t),n=i[i.length-1];n&&this.reportApiInvoke(e,{name:"Client.resourceTiming",options:n,tag:oe.TRACER}).onSuccess()}};MI.on("REPORT_LOG_UPLOAD",t=>{t.networkState=Ee.networkState,Z.reportApiInvoke(null,{name:"logUploadError",options:t,tag:oe.TRACER}).onSuccess("logUploadError")});class P extends k{constructor(e){super(e,arguments.length>1&&arguments[1]!==void 0?arguments[1]:"",arguments.length>2?arguments[2]:void 0),se(this,"name","AgoraRTCException")}print(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"error";return super.print(e,_)}throw(){super.throw(_)}}const xe={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};function Ct(){return xe}function VI(){return"setSinkId"in HTMLAudioElement.prototype&&(!y("RESTRICTION_SET_PLAYBACK_DEVICE")||(xr()||Xy())&&!NE())}function FI(){return!xe.supportUnifiedPlan||y("CHROME_FORCE_PLAN_B")&&Vr()}let Ve=function(t){return t.IOS_15_16_INTERRUPTION_START="ios15_16-interruption-start",t.IOS_15_16_INTERRUPTION_END="ios15_16-interruption-end",t.IOS_INTERRUPTION_START="ios-interruption-start",t.IOS_INTERRUPTION_END="ios-interruption-end",t.STATE_CHANGE="state-change",t}({});function da(t,e,i){return{sampleRate:t,stereo:e,bitrate:i}}function yt(t,e,i,n,r){return{width:t,height:e,frameRate:i,bitrateMin:n,bitrateMax:r}}function On(t,e,i,n,r){return{width:{max:t},height:{max:e},frameRate:i,bitrateMin:n,bitrateMax:r}}function $E(t,e){return{numSpatialLayers:t,numTemporalLayers:e}}const r3={"90p":yt(160,90),"90p_1":yt(160,90),"120p":yt(160,120,15,30,65),"120p_1":yt(160,120,15,30,65),"120p_3":yt(120,120,15,30,50),"120p_4":yt(212,120),"180p":yt(320,180,15,30,140),"180p_1":yt(320,180,15,30,140),"180p_3":yt(180,180,15,30,100),"180p_4":yt(240,180,15,30,120),"240p":yt(320,240,15,40,200),"240p_1":yt(320,240,15,40,200),"240p_3":yt(240,240,15,40,140),"240p_4":yt(424,240,15,40,220),"360p":yt(640,360,15,80,400),"360p_1":yt(640,360,15,80,400),"360p_3":yt(360,360,15,80,260),"360p_4":yt(640,360,30,80,600),"360p_6":yt(360,360,30,80,400),"360p_7":yt(480,360,15,80,320),"360p_8":yt(480,360,30,80,490),"360p_9":yt(640,360,15,80,800),"360p_10":yt(640,360,24,80,800),"360p_11":yt(640,360,24,80,1e3),"480p":yt(640,480,15,100,500),"480p_1":yt(640,480,15,100,500),"480p_2":yt(640,480,30,100,1e3),"480p_3":yt(480,480,15,100,400),"480p_4":yt(640,480,30,100,750),"480p_6":yt(480,480,30,100,600),"480p_8":yt(848,480,15,100,610),"480p_9":yt(848,480,30,100,930),"480p_10":yt(640,480,10,100,400),"720p":yt(1280,720,15,120,1130),"720p_auto":yt(1280,720,30,900,3e3),"720p_1":yt(1280,720,15,120,1130),"720p_2":yt(1280,720,30,120,2e3),"720p_3":yt(1280,720,30,120,1710),"720p_5":yt(960,720,15,120,910),"720p_6":yt(960,720,30,120,1380),"1080p":yt(1920,1080,15,120,2080),"1080p_1":yt(1920,1080,15,120,2080),"1080p_2":yt(1920,1080,30,120,3e3),"1080p_3":yt(1920,1080,30,120,3150),"1080p_5":yt(1920,1080,60,120,4780),"1440p":yt(2560,1440,30,120,4850),"1440p_1":yt(2560,1440,30,120,4850),"1440p_2":yt(2560,1440,60,120,7350),"4k":yt(3840,2160,30,120,8910),"4k_1":yt(3840,2160,30,120,8910),"4k_3":yt(3840,2160,60,120,13500)},o3={"480p":On(640,480,5),"480p_1":On(640,480,5),"480p_2":On(640,480,30),"480p_3":On(640,480,15),"720p":On(1280,720,5),"720p_auto":yt(1280,720,30,900,3e3),"720p_1":On(1280,720,5),"720p_2":On(1280,720,30),"720p_3":On(1280,720,15),"1080p":On(1920,1080,5),"1080p_1":On(1920,1080,5),"1080p_2":On(1920,1080,30),"1080p_3":On(1920,1080,15)},s3={"1SL1TL":$E(1,1),"3SL3TL":$E(3,3),"2SL3TL":$E(2,3)};function Nn(t){return t||(t="480p_1"),typeof t=="string"?Object.assign({},r3[t]):t}function tm(t){return typeof t=="string"?Object.assign({},o3[t]):t}function fu(t){return typeof t=="string"?Object.assign({},s3[t]):t}const a3={speech_low_quality:da(16e3,!1),speech_standard:da(32e3,!1,18),music_standard:da(48e3,!1),standard_stereo:da(48e3,!0,56),high_quality:da(48e3,!1,128),high_quality_stereo:da(48e3,!0,192)};function gu(t){return typeof t=="string"?Object.assign({},a3[t]):t}const la=[];function BI(t){return Ae(t,"mediaSource",["screen","window","application"]),!0}let J=function(t){return t.NEED_RENEGOTIATE="@need_renegotiate",t.NEED_REPLACE_TRACK="@need_replace_track",t.NEED_REPLACE_MIXING_TRACK="@need_replace_mixing_track",t.NEED_CLOSE="@need_close",t.NEED_ENABLE_TRACK="@need_enable_track",t.NEED_DISABLE_TRACK="@need_disable_track",t.NEED_SESSION_ID="@need_sid",t.SET_OPTIMIZATION_MODE="@set_optimization_mode",t.GET_STATS="@get_stats",t.GET_RTC_STATS="@get_rtc_stats",t.GET_LOW_VIDEO_TRACK="@get_low_video_track",t.NEED_RESET_REMOTE_SDP="@need_reset_remote_sdp",t.NEED_UPDATE_VIDEO_ENCODER="@need_update_video_encoder",t.NEED_UPDATE_VIDEO_SEND_PARAMETERS="@need_update_video_send_parameters",t.NEED_MUTE_TRACK="@need_mute_track",t.NEED_UNMUTE_TRACK="@need_unmute_track",t}({}),Vt=function(t){return t.SCREEN_TRACK="screen_track",t.CUSTOM_TRACK="custome_track",t.LOW_STREAM="low_stream",t.SCREEN_LOW_TRACK="screen_low_track",t}({}),ua=function(t){return t[t.HIGH_STREAM=0]="HIGH_STREAM",t[t.LOW_STREAM=1]="LOW_STREAM",t}({}),c3=function(t){return t[t.HIGH_STREAM=0]="HIGH_STREAM",t[t.LOW_STREAM=1]="LOW_STREAM",t[t.HIGH_STREAM_LAYER1=4]="HIGH_STREAM_LAYER1",t[t.HIGH_STREAM_LAYER2=5]="HIGH_STREAM_LAYER2",t[t.HIGH_STREAM_LAYER3=6]="HIGH_STREAM_LAYER3",t[t.HIGH_STREAM_LAYER4=7]="HIGH_STREAM_LAYER4",t[t.HIGH_STREAM_LAYER5=8]="HIGH_STREAM_LAYER5",t[t.HIGH_STREAM_LAYER6=9]="HIGH_STREAM_LAYER6",t}({}),d3=function(t){return t[t.DISABLE=0]="DISABLE",t[t.LOW_STREAM=1]="LOW_STREAM",t[t.AUDIO_ONLY=2]="AUDIO_ONLY",t[t.HIGH_STREAM_LAYER1=3]="HIGH_STREAM_LAYER1",t[t.HIGH_STREAM_LAYER2=4]="HIGH_STREAM_LAYER2",t[t.HIGH_STREAM_LAYER3=5]="HIGH_STREAM_LAYER3",t[t.HIGH_STREAM_LAYER4=6]="HIGH_STREAM_LAYER4",t[t.HIGH_STREAM_LAYER5=7]="HIGH_STREAM_LAYER5",t[t.HIGH_STREAM_LAYER6=8]="HIGH_STREAM_LAYER6",t}({}),ts=function(t){return t.TRANSCEIVER_UPDATED="transceiver-updated",t.SEI_TO_SEND="sei-to-send",t.SEI_RECEIVED="sei-received",t.TRACK_UPDATED="track-updated",t}({}),ha=function(t){return t.SOURCE_STATE_CHANGE="source-state-change",t.TRACK_ENDED="track-ended",t.BEAUTY_EFFECT_OVERLOAD="beauty-effect-overload",t.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",t.CLOSED="closed",t}({}),pa=function(t){return t.FIRST_FRAME_DECODED="first-frame-decoded",t.VIDEO_ELEMENT_VISIBLE_STATUS="video-element-visible-status",t.VIDEO_STATE_CHANGED="video-state-changed",t}({}),_a=function(t){return t.AUDIO="audio",t.VIDEO="video",t.DATA="data",t}({}),Qi=function(t){return t.AUDIO_SOURCE_STATE_CHANGE="audio_source_state_change",t.RECEIVE_TRACK_BUFFER="receive_track_buffer",t.ON_AUDIO_BUFFER="on_audio_buffer",t.UPDATE_SOURCE="update_source",t}({});(function(t){t.UPDATE_TRACK_SOURCE="update-track-source"})({});const em={sendVolumeLevel:0,sendBitrate:0,sendBytes:0,sendPackets:0,sendPacketsLost:0,sendJitterMs:0,sendRttMs:0,currentPacketLossRate:0},im={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},jI={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},l3={uplinkNetworkQuality:0,downlinkNetworkQuality:0},GI={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 ui=function(t){return t.ON_TRACK="on_track",t.ON_NODE="on_node",t}({}),Zi=function(t){return t.REQUEST_UPDATE_CONSTRAINTS="request_update_constraints",t.REQUEST_CONSTRAINTS="request_constraints",t}({}),Uc=function(t){return t.IDLE="IDLE",t.INITING="INITING",t.INITEND="INITEND",t}({}),es=function(t){return t.STATE_CHANGE="state_change",t.RECORDING_DEVICE_CHANGED="recordingDeviceChanged",t.PLAYOUT_DEVICE_CHANGED="playoutDeviceChanged",t.CAMERA_DEVICE_CHANGED="cameraDeviceChanged",t}({}),ii=function(t){return t.NONE="none",t.INIT="init",t.CANPLAY="canplay",t.PLAYING="playing",t.PAUSED="paused",t.SUSPEND="suspend",t.STALLED="stalled",t.WAITING="waiting",t.ERROR="error",t.DESTROYED="destroyed",t.ABORT="abort",t.ENDED="ended",t.EMPTIED="emptied",t.LOADEDDATA="loadeddata",t}({}),fr=function(t){return t[t.VideoStateStopped=0]="VideoStateStopped",t[t.VideoStateStarting=1]="VideoStateStarting",t[t.VideoStateDecoding=2]="VideoStateDecoding",t[t.VideoStateFrozen=3]="VideoStateFrozen",t}({});const nm={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 Su=function(t){return t.OPEN="open",t.MESSAGE="message",t.CLOSE="close",t.CLOSING="closing",t.ERROR="error",t}({});function gt(t,e,i,n,r){var o,s,a={};return Object.keys(n).forEach(function(c){a[c]=n[c]}),a.enumerable=!!a.enumerable,a.configurable=!!a.configurable,("value"in a||a.initializer)&&(a.writable=!0),a=Tn(o=bg(s=i.slice()).call(s)).call(o,function(c,d){return d(t,e,c)||c},a),r&&a.initializer!==void 0&&(a.value=a.initializer?a.initializer.call(r):void 0,a.initializer=void 0),a.initializer===void 0?(Object.defineProperty(t,e,a),null):a}function D(t,e,i){return(e=function(n){var r=function(o,s){if(typeof o!="object"||!o)return o;var a=o[Symbol.toPrimitive];if(a!==void 0){var c=a.call(o,"string");if(typeof c!="object")return c;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(o)}(n);return typeof r=="symbol"?r:r+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function WI(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Qt(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?WI(Object(i),!0).forEach(function(n){D(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):WI(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}class HI extends $t{set _mediaStreamTrack(e){e!==this.mediaStreamTrack&&(this.safeEmit(ts.TRACK_UPDATED,e),this.mediaStreamTrack=e)}get _mediaStreamTrack(){return this.mediaStreamTrack}constructor(e,i){super(),D(this,"trackMediaType",void 0),D(this,"_ID",void 0),D(this,"_rtpTransceiver",void 0),D(this,"_lowRtpTransceiver",void 0),D(this,"_hints",[]),D(this,"_isClosed",!1),D(this,"_originMediaStreamTrack",void 0),D(this,"mediaStreamTrack",void 0),D(this,"_external",{}),this._ID=i||Gt(8,"track-"),this._originMediaStreamTrack=e,this.mediaStreamTrack=e,function(n){G(la).call(la,n)||la.push(n)}(this)}toString(){return this._ID}getTrackId(){return this._ID}getMediaStreamTrack(e){return e||_o(()=>{var i;Z.reportApiInvoke(null,{name:_e.GET_MEDIA_STREAM_TRACK,options:[],tag:oe.TRACER}).onSuccess(((i=this._mediaStreamTrack)===null||i===void 0?void 0:i.label)||"")},this.mediaStreamTrack.id||this.getTrackId()),this._mediaStreamTrack}getRTCRtpTransceiver(e){return e===ua.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 i=la.indexOf(e);i!==-1&&la.splice(i,1)}(this),this.emit(ha.CLOSED),this.removeAllListeners(ts.SEI_RECEIVED)}_updateRtpTransceiver(e,i){if(i===ua.LOW_STREAM){if(this._lowRtpTransceiver===e)return;this._lowRtpTransceiver=e}else{if(this._rtpTransceiver===e)return;this._rtpTransceiver=e}this.emit(ts.TRANSCEIVER_UPDATED,e,i)}}class Ea extends HI{get isExternalTrack(){return this._isExternalTrack}get muted(){return this._muted}get enabled(){return this._enabled}get processorContext(){return this._processorContext}constructor(e,i){super(e,i),D(this,"_enabled",!0),D(this,"_muted",!1),D(this,"_isExternalTrack",!1),D(this,"_isClosed",!1),D(this,"_enabledMutex",void 0),D(this,"processor",void 0),D(this,"_processorContext",void 0),D(this,"_handleTrackEnded",()=>{this.onTrackEnded()}),this._enabledMutex=new qe("".concat(this.getTrackId())),e.addEventListener("ended",this._handleTrackEnded)}getTrackLabel(){var e,i;return(e=(i=this._originMediaStreamTrack)===null||i===void 0?void 0:i.label)!==null&&e!==void 0?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,_.debug("[".concat(this.getTrackId(),"] close")),this.emit(J.NEED_CLOSE),super.close())}_updateOriginMediaStreamTrack(n,r){return C(this,arguments,function*(e,i){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2];this._isExternalTrack=o,e!==this._originMediaStreamTrack&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),i&&this._originMediaStreamTrack.stop()),e.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=e,this._muted&&(this._originMediaStreamTrack.enabled=!1),this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),yield Bt(this,J.NEED_REPLACE_TRACK,this),this.processor&&this._processorContext&&this.processor.updateInput({track:this._originMediaStreamTrack,context:this._processorContext}))})}_getDefaultPlayerConfig(){return{}}onTrackEnded(){_.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(ha.TRACK_ENDED)}stateCheck(e,i){if(_.debug("check track state, [muted: ".concat(this._muted,", enabled: ").concat(this._enabled,"] to [").concat(e,": ").concat(i,"]")),Fr(i,e),this._enabled&&this._muted&&e==="enabled"&&i===!1)throw new k(v.TRACK_STATE_UNREACHABLE,"cannot set enabled while the track is muted").print("error",_);if(!this._enabled&&!this._muted&&e==="muted"&&i===!0)throw new k(v.TRACK_STATE_UNREACHABLE,"cannot set muted while the track is disabled").print("error",_)}getProcessorStats(){return this._processorContext&&this._processorContext.gatherStats()||[]}getProcessorUsage(){return this._processorContext?this._processorContext.gatherUsage():K.resolve([])}}const KI=window.AudioContext||window.webkitAudioContext;let $i=null;const Mt=new class extends $t{constructor(){super(...arguments),D(this,"prevState",void 0),D(this,"curState",void 0),D(this,"currentTime",void 0),D(this,"currentTimeStuckAt",void 0),D(this,"interruptDetectorTrack",void 0),D(this,"onLocalAudioTrackMute",()=>{_.info("ios15-interruption-start"),this.emit(Ve.IOS_15_16_INTERRUPTION_START)}),D(this,"onLocalAudioTrackUnmute",()=>C(this,null,function*(){_.info("ios15-interruption-end"),this.curState!=="running"||this.duringInterruption?_.info("ios15-interruption-end-canceled"):($i&&(yield $i.suspend()),this.emit(Ve.IOS_15_16_INTERRUPTION_END))}))}get duringInterruption(){return this.prevState==="running"&&this.curState==="interrupted"}bindInterruptDetectorTrack(t){_.debug("webaudio bindInterruptDetectorTrack ".concat(t.getTrackId())),this.interruptDetectorTrack||(this.interruptDetectorTrack=t,this.interruptDetectorTrack._mediaStreamTrack.onmute=this.onLocalAudioTrackMute,this.interruptDetectorTrack._mediaStreamTrack.onunmute=this.onLocalAudioTrackUnmute)}unbindInterruptDetectorTrack(t){_.debug("webaudio unbindInterruptDetectorTrack ".concat(t.getTrackId())),this.interruptDetectorTrack&&this.interruptDetectorTrack===t&&(this.interruptDetectorTrack._mediaStreamTrack&&(this.interruptDetectorTrack._mediaStreamTrack.onmute=null,this.interruptDetectorTrack._mediaStreamTrack.onunmute=null),this.interruptDetectorTrack=void 0)}};function ma(){if(!$i){if(function(){if(!KI)return void _.error("your browser is not support web audio");_.info("create audio context");const t=Qt({},y("WEBAUDIO_INIT_OPTIONS"));_.debug("audio context init option:",JSON.stringify(t)),$i=new KI(t),Mt.curState=$i.state,$i.onstatechange=()=>{Mt.prevState=Mt.curState,Mt.curState=$i?$i.state:void 0;const{prevState:e,curState:i}=Mt,n=i==="running",r=i==="interrupted",o=e==="running",s=e==="suspended",a=e==="interrupted",c=vt().osVersion;(li()||bn())&&o&&r&&(_.info("ios".concat(c,"-interruption-start")),Mt.emit(Ve.IOS_INTERRUPTION_START)),(li()||bn())&&(s||a)&&n&&(_.info("ios".concat(c,"-interruption-end")),Mt.emit(Ve.IOS_INTERRUPTION_END)),e!==i&&Mt.emit(Ve.STATE_CHANGE,i,e)},setInterval(()=>{var e;const i=(e=$i)===null||e===void 0?void 0:e.currentTime;Mt.currentTime!==i?(Mt.currentTimeStuckAt&&(_.debug("AudioContext current time resume at ".concat(i)),Mt.currentTimeStuckAt=void 0),Mt.currentTime=i):(i!==Mt.currentTimeStuckAt&&(Z.reportApiInvoke(null,{name:"WEB_AUDIO_CURRENT_TIME_STUCK",options:{currentTime:i},tag:oe.TRACER}).onSuccess(),_.warning("AudioContext current time stuck at ".concat(i))),Mt.currentTimeStuckAt=i)},5e3),function(e){return C(this,null,function*(){const i=["click","contextmenu","auxclick","dblclick","mousedown","mouseup","touchend","keydown","keyup"];let n,r=!1,o=!1,s=!1;function a(m){e.state==="running"?c(!1):li()||bn()?e.state==="suspended"&&(c(!0),m&&e.resume().then(d,d)):e.state!=="closed"&&(c(!0),m&&e.resume().then(d,d))}function c(m){if(r!==m){r=m;for(let f=0,T=i;f<T.length;f+=1){const R=T[f];m?window.addEventListener(R,l,{capture:!0,passive:!0}):window.removeEventListener(R,l,{capture:!0,passive:!0})}}}function d(){a(!1)}function l(){a(!0)}function u(m){if(!s)if(n.paused)if(m){let f;h(!1),s=!0;try{f=n.play(),f?f.then(p,p):(n.addEventListener("playing",p),n.addEventListener("abort",p),n.addEventListener("error",p))}catch(T){p()}}else h(!0);else h(!1)}function h(m){if(o!==m){o=m;for(let f=0,T=i;f<T.length;f++){const R=T[f];m?window.addEventListener(R,g,{capture:!0,passive:!0}):window.removeEventListener(R,g,{capture:!0,passive:!0})}}}function p(){n.removeEventListener("playing",p),n.removeEventListener("abort",p),n.removeEventListener("error",p),s=!1,u(!1)}function g(){u(!0)}if(li()){const m=e.createMediaStreamDestination(),f=document.createElement("div");f.innerHTML="<audio x-webkit-airplay='deny'></audio>",n=f.children.item(0),n.controls=!1,n.disableRemotePlayback=!0,n.preload="auto",n.srcObject=m.stream,u(!0)}Mt.on(Ve.STATE_CHANGE,function(){a(!0)}),a(!1)})}($i)}(),!$i)throw new k(v.NOT_SUPPORTED,"can not create audio context");return $i}return $i}function is(t){if(function(){if(rm!==null)return rm;const n=ma(),r=n.createBufferSource(),o=n.createGain(),s=n.createGain();r.connect(o),r.connect(s),r.disconnect(o);let a=!1;try{r.disconnect(o)}catch(c){a=!0}return r.disconnect(),rm=a,a}())return;const e=t.connect,i=t.disconnect;t.connect=(n,r,o)=>{var s;return t._inputNodes||(t._inputNodes=[]),G(s=t._inputNodes).call(s,n)||(n instanceof AudioNode?(t._inputNodes.push(n),e.call(t,n,r,o)):e.call(t,n,r)),t},t.disconnect=(n,r,o)=>{i.call(t),n?cu(t._inputNodes,n):t._inputNodes=[];for(const s of t._inputNodes)e.call(t,s)}}let rm=null;function om(t,e){let i=!1;const n=1/e;if(y("DISABLE_WEBAUDIO")){const r=window.setInterval(()=>{i?window.clearInterval(r):t(performance.now()/1e3)},1e3*n)}else{const r=ma();let o=r.createGain();o.gain.value=0,o.connect(r.destination);const s=()=>{if(i)return void(o=null);const a=r.createOscillator();a.onended=s,a.connect(o),a.start(0),a.stop(r.currentTime+n),t(r.currentTime)};s()}return()=>{i=!0}}class YI{constructor(){D(this,"context",void 0),D(this,"analyserNode",void 0),D(this,"sourceNode",void 0),this.context=ma(),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(i){}this.sourceNode=e,e==null||e.connect(this.analyserNode)}}getVolumeLevel(){if(!this.sourceNode||(!this.context||li()||bn()||this.context.state!=="running"&&this.context.resume(),!this.analyserNode))return 0;const e=new Float32Array(this.analyserNode.fftSize);if(this.analyserNode.getFloatTimeDomainData)this.analyserNode.getFloatTimeDomainData(e);else{const n=new Uint8Array(this.analyserNode.fftSize);this.analyserNode.getByteTimeDomainData(n);for(let r=0;r<e.length;++r)e[r]=n[r]/128-1}const i=Tn(e).call(e,(n,r)=>n+r*r,0)/e.length;return Math.max(10*Math.log10(i)+100,0)/100}getAnalyserNode(){return this.analyserNode}rebuildAnalyser(){try{var e,i;(e=this.sourceNode)===null||e===void 0||e.disconnect(this.analyserNode),this.analyserNode=this.context.createAnalyser(),this.analyserNode.fftSize=2048,this.analyserNode.smoothingTimeConstant=.4,(i=this.sourceNode)===null||i===void 0||i.connect(this.analyserNode)}catch(n){_.warning("rebuild analyser node failed.")}}destroy(){this.updateSource(void 0)}}class qI extends $t{get processSourceNode(){return this.sourceNode}set processedNode(e){var i;if(!this.isDestroyed&&this._processedNode!==e){try{var n;(n=this.sourceNode)===null||n===void 0||n.disconnect(this.outputNode)}catch(r){}(i=this._processedNode)===null||i===void 0||i.disconnect(),this._processedNode=e,this.connect()}}get processedNode(){return this._processedNode}constructor(){super(),D(this,"outputNode",void 0),D(this,"outputTrack",void 0),D(this,"isPlayed",!1),D(this,"sourceNode",void 0),D(this,"context",void 0),D(this,"audioBufferNode",void 0),D(this,"destNode",void 0),D(this,"audioOutputLevel",0),D(this,"volumeLevelAnalyser",void 0),D(this,"_processedNode",void 0),D(this,"playNode",void 0),D(this,"isDestroyed",!1),D(this,"onNoAudioInput",void 0),D(this,"isNoAudioInput",!1),D(this,"_noAudioInputCount",0),this.context=ma(),this.playNode=this.context.destination,this.outputNode=this.context.createGain(),is(this.outputNode),this.volumeLevelAnalyser=new YI}startGetAudioBuffer(e){this.audioBufferNode||(this.audioBufferNode=this.context.createScriptProcessor(e),this.outputNode.connect(this.audioBufferNode),this.audioBufferNode.connect(this.context.destination),this.audioBufferNode.onaudioprocess=i=>{this.emit(Qi.ON_AUDIO_BUFFER,function(n){for(let r=0;r<n.outputBuffer.numberOfChannels;r+=1){const o=n.outputBuffer.getChannelData(r);for(let s=0;s<o.length;s+=1)o[s]=0}return n.inputBuffer}(i))})}stopGetAudioBuffer(){this.audioBufferNode&&(this.audioBufferNode.onaudioprocess=null,this.outputNode.disconnect(this.audioBufferNode),this.audioBufferNode=void 0)}createOutputTrack(){if(!Ct().webAudioMediaStreamDest)throw new k(v.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){this.context.state!=="running"&&du(()=>{Mt.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()}checkHasAudioInput(){return C(this,arguments,function*(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;if(e>5)return this.isNoAudioInput=!0,this.onNoAudioInput&&this.onNoAudioInput(),!1;li()||bn()?this.context.state==="suspended"&&this.context.resume():this.context.state!=="running"&&this.context.resume();const i=this.volumeLevelAnalyser.getAnalyserNode();let n;i.getFloatTimeDomainData?(n=new Float32Array(i.fftSize),i.getFloatTimeDomainData(n)):(n=new Uint8Array(i.fftSize),i.getByteTimeDomainData(n));let r=!1;for(let o=0;o<n.length;o++)n[o]!==0&&(r=!0);return r?(this.isNoAudioInput=!1,!0):(yield Ue(200),(yield this.checkHasAudioInput(e?e+1:1))&&r)})}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,i;(e=this.processedNode)===null||e===void 0||e.disconnect(),(i=this.sourceNode)===null||i===void 0||i.disconnect(),this.outputNode&&this.outputNode.disconnect()}connect(){var e;this.processedNode?(e=this.processedNode)===null||e===void 0||e.connect(this.outputNode):this.sourceNode&&this.sourceNode.connect(this.outputNode),this.volumeLevelAnalyser.updateSource(this.outputNode)}}class zI extends qI{get isFreeze(){return!1}constructor(e,i,n){var r;if(super(),D(this,"sourceNode",void 0),D(this,"track",void 0),D(this,"clonedTrack",void 0),D(this,"audioElement",void 0),D(this,"isCurrentTrackCloned",!1),D(this,"isRemoteTrack",!1),D(this,"originVolumeLevelAnalyser",void 0),D(this,"rebuildWebAudio",()=>C(this,null,function*(){if(_.debug("ready to rebuild web audio, state:",this.context.state),this.isNoAudioInput&&(yield this.checkHasAudioInput()),!this.isNoAudioInput||this.isDestroyed)return document.body.removeEventListener("click",this.rebuildWebAudio,!0),void _.debug("rebuild web audio success, current volume status",this.getAccurateVolumeLevel());this.context.resume().then(()=>_.info("resume success")),_.debug("rebuild web audio because of ios 12 bugs"),this.disconnect();const a=this.track;this.track=this.track.clone(),this.isCurrentTrackCloned?a.stop():this.isCurrentTrackCloned=!0;const c=new MediaStream([this.track]);this.sourceNode=this.context.createMediaStreamSource(c),is(this.sourceNode),this.volumeLevelAnalyser.rebuildAnalyser();const d=this.outputNode.gain.value;this.outputNode=this.context.createGain(),this.outputNode.gain.setValueAtTime(d,this.context.currentTime),is(this.outputNode),this.emit(Qi.UPDATE_SOURCE),this.connect(),this.audioElement.srcObject=c,this.isPlayed&&this.play(this.playNode),this.checkHasAudioInput()})),e.kind!=="audio")throw new k(v.UNEXPECTED_ERROR);this.track=e;const o=new MediaStream([this.track]);if(this.isRemoteTrack=!!i,this.sourceNode=this.context.createMediaStreamSource(o),is(this.sourceNode),n){const a=n.clone();a.enabled=!0,this.clonedTrack=a,_.debug("create an unmuted track ".concat(a.id," from the original track ").concat(n.id," to get the volume"));const c=this.context.createMediaStreamSource(new MediaStream([a]));is(c),this.originVolumeLevelAnalyser=new YI,this.originVolumeLevelAnalyser.updateSource(c)}this.connect(),this.audioElement=document.createElement("audio"),this.audioElement.srcObject=o;const s=vt();i&&s.os===we.IOS&&Number((r=s.osVersion)===null||r===void 0?void 0:r.split(".")[0])<15&&(Mt.on(Ve.STATE_CHANGE,()=>{this.context.state==="suspended"?document.body.addEventListener("click",this.rebuildWebAudio,!0):this.context.state==="running"&&this.rebuildWebAudio()}),this.checkHasAudioInput().then(a=>{a||document.body.addEventListener("click",this.rebuildWebAudio,!0)}))}updateTrack(e){this.sourceNode.disconnect(),this.track=e,this.isCurrentTrackCloned=!1;const i=new MediaStream([e]);this.sourceNode=this.context.createMediaStreamSource(i),is(this.sourceNode),this.processedNode||this.sourceNode.connect(this.outputNode),this.emit(Qi.UPDATE_SOURCE),this.audioElement.srcObject=i}destroy(){var e;this.audioElement.srcObject=null,this.audioElement.remove(),Mt.off("state-change",this.rebuildWebAudio),(e=this.originVolumeLevelAnalyser)===null||e===void 0||e.destroy(),this.clonedTrack=void 0,super.destroy()}createMediaStreamSourceNode(e){return this.context.createMediaStreamSource(new MediaStream([e]))}updateOriginTrack(e){const i=e.clone();i.enabled=!0,this.clonedTrack&&(this.clonedTrack.stop(),this.clonedTrack=i),_.debug("create an unmuted track ".concat(i.id," from the original track ").concat(e.id," to get the volume"));const n=this.context.createMediaStreamSource(new MediaStream([i]));is(n),this.originVolumeLevelAnalyser&&this.originVolumeLevelAnalyser.updateSource(n)}getOriginVolumeLevel(){return this.originVolumeLevelAnalyser?this.originVolumeLevelAnalyser.getVolumeLevel():this.getAccurateVolumeLevel()}}function XI(t,e,i){return C(this,null,function*(){const n=(o,s)=>o?typeof o!="number"?o.max||o.exact||o.ideal||o.min||s:o:s,r={audio:!!i&&{mandatory:{chromeMediaSource:"desktop"}},video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:t,maxHeight:n(e.height,1080),maxWidth:n(e.width,1920)}}};return e.frameRate&&typeof e.frameRate!="number"?(r.video.mandatory.maxFrameRate=e.frameRate.max,r.video.mandatory.minFrameRate=e.frameRate.min):typeof e.frameRate=="number"&&(r.video.mandatory.maxFrameRate=e.frameRate),yield navigator.mediaDevices.getUserMedia(r)})}function u3(t,e){return C(this,null,function*(){const i=yield JI(t.mediaSource),{sourceId:n,audio:r}=yield function(o){let s=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new K((a,c)=>{const d=document.createElement("div");d.innerText="share screen",d.setAttribute("style","text-align: center; height: 25px; line-height: 25px; border-radius: 4px 4px 0 0; background: #D4D2D4; border-bottom: solid 1px #B9B8B9;");const l=document.createElement("div");l.setAttribute("style","width: 100%; height: 500px; padding: 15px 25px ; box-sizing: border-box;");const u=document.createElement("div");u.innerText="Agora Web Screensharing wants to share the contents of your screen with webdemo.agorabeckon.com. Choose what you'd like to share.",u.setAttribute("style","height: 12%;");const h=document.createElement("div");h.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 p=document.createElement("div");p.setAttribute("style","display: flex; justify-content: space-between; padding: 16px 0;");const g=document.createElement("button");g.innerHTML="cancel",g.setAttribute("style","width: 85px;"),g.onclick=()=>{document.body.removeChild(T);const R=new Error("NotAllowedError");R.name="NotAllowedError",c(R)};let m=s;const f=document.createElement("div");if(s){const R=document.createElement("input");R.setAttribute("type","checkbox");const A=document.createElement("span");R.setAttribute("style","margin-right: 6px;"),A.innerText="Share audio",R.checked=m,R.onchange=()=>{m=R.checked},f.appendChild(R),f.appendChild(A)}p.appendChild(f),p.appendChild(g),l.appendChild(u),l.appendChild(h),l.appendChild(p);const T=document.createElement("div");T.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%);"),T.appendChild(d),T.appendChild(l),document.body.appendChild(T),o.map(R=>{if(R.id){const A=document.createElement("div");A.setAttribute("style","width: 30%; height: 160px; padding: 20px 0; text-align: center;box-sizing: content-box;");let N=R.thumbnail;try{const{width:O}=N.getSize();O>1920&&(N=N.resize({width:1920}))}catch(O){throw O&&O.message.startsWith("Illegal invocation")&&console.error("Operate thumbnail error, please try to set contextIsolation: false. (https://github.com/electron/electron/issues/34953)"),O}A.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='+N.toDataURL()+' /></div><span style=" height: 40px; line-height: 40px; display: inline-block; width: 70%; word-break: keep-all; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">'+R.name.replace(/[\u00A0-\u9999<>\&]/g,function(O){return"&#"+O.charCodeAt(0)+";"})+"</span>",A.onclick=()=>{document.body.removeChild(T),a({sourceId:R.id,audio:m})},h.appendChild(A)}})})}(i,e);return yield XI(n,t,r)})}function JI(t){return C(this,null,function*(){let e=["window","screen"];t!=="application"&&t!=="window"||(e=["window"]),t==="screen"&&(e=["screen"]);const i=cI();if(!i)throw console.error("failed to fetch electron, please mount it to window"),new k(v.ELECTRON_IS_NULL);let n=null;try{var r;n=((r=i.desktopCapturer)===null||r===void 0?void 0:r.getSources({types:e}))||i.ipcRenderer.invoke("DESKTOP_CAPTURER_GET_SOURCES",{types:e})}catch(o){n=null}n&&n.then||(n=new K((o,s)=>{i.desktopCapturer.getSources({types:e},(a,c)=>{a?s(a):o(c)})}));try{return yield n}catch(o){throw new k(v.ELECTRON_DESKTOP_CAPTURER_GET_SOURCES_ERROR,o.toString())}})}const sm=new qe("safari");let QI=!1,ZI=!1;function tn(t,e){return C(this,null,function*(){let i=0,n=null;for(;i<2;)try{n=yield h3(t,e,i>0);break}catch(r){if(r instanceof k)throw _.error("[".concat(e,"] ").concat(r.toString())),r;const o=Tu(r.name||r.code||r,r.message);if(o.code===v.MEDIA_OPTION_INVALID){_.debug("[".concat(e,"] detect media option invalid, retry")),i+=1,yield Ue(500);continue}throw _.error("[".concat(e,"] ").concat(o.toString())),o}if(!n)throw new k(v.UNEXPECTED_ERROR,"can not find stream after getUserMedia");return n})}function h3(t,e,i){return C(this,null,function*(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new k(v.NOT_SUPPORTED,"can not find getUserMedia");i&&(t.video&&(delete t.video.width,delete t.video.height),t.screen&&(delete t.screen.width,delete t.screen.height));const n=Ct(),r=new MediaStream;if(t.audioSource&&r.addTrack(t.audioSource),t.videoSource&&r.addTrack(t.videoSource),!t.audio&&!t.video&&!t.screen)return _.debug("Using Video Source/ Audio Source"),r;if(t.screen)if(cI())t.screen.sourceId?fa(r,yield XI(t.screen.sourceId,t.screen,!!t.screenAudio)):fa(r,yield u3(t.screen,!!t.screenAudio));else if(xr()&&t.screen.extensionId&&t.screen.mandatory){if(!n.getStreamFromExtension)throw new k(v.NOT_SUPPORTED,"This browser does not support screen sharing");_.debug("[".concat(e,'] Screen access on chrome stable, looking for extension"'));const h=yield(s=t.screen.extensionId,a=e,new K((p,g)=>{try{chrome.runtime.sendMessage(s,{getStream:!0},m=>{if(!m||!m.streamId)return _.error("[".concat(a,"] No response from Chrome Plugin. Plugin not installed properly"),m),void g(new k(v.CHROME_PLUGIN_NO_RESPONSE,"No response from Chrome Plugin. Plugin not installed properly"));p(m.streamId)})}catch(m){_.error("[".concat(a,"] AgoraRTC screensharing plugin is not accessible(").concat(s,")"),m.toString()),g(new k(v.CHROME_PLUGIN_NOT_INSTALL))}}));t.screen.mandatory.chromeMediaSourceId=h,fa(r,yield navigator.mediaDevices.getUserMedia({video:{mandatory:t.screen.mandatory}}))}else if(n.getDisplayMedia){var o;t.screen.mediaSource&&BI(t.screen.mediaSource);const h={width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate,displaySurface:(o=t.screen.displaySurface)!==null&&o!==void 0?o:t.screen.mediaSource==="screen"?"monitor":t.screen.mediaSource},{selfBrowserSurface:p,surfaceSwitching:g,systemAudio:m,preferCurrentTab:f}=t.screen,T={selfBrowserSurface:p,surfaceSwitching:g,systemAudio:m,preferCurrentTab:f};!p&&delete T.selfBrowserSurface,!g&&delete T.surfaceSwitching,!m&&delete T.systemAudio,!f&&delete T.preferCurrentTab,_.debug("[".concat(e,"] getDisplayMedia:"),JSON.stringify({video:h,audio:t.screenAudio,controls:T})),fa(r,yield navigator.mediaDevices.getDisplayMedia(Qt({video:h,audio:t.screenAudio},T)))}else{if(!ne())throw _.error("[".concat(e,"] This browser does not support screenSharing")),new k(v.NOT_SUPPORTED,"This browser does not support screen sharing");{t.screen.mediaSource&&BI(t.screen.mediaSource);const h={video:{mediaSource:t.screen.mediaSource,width:t.screen.width,height:t.screen.height,frameRate:t.screen.frameRate}};_.debug("[".concat(e,"] getUserMedia: ").concat(JSON.stringify(h))),fa(r,yield navigator.mediaDevices.getUserMedia(h))}}var s,a;if(!t.video&&!t.audio)return r;let c={video:t.video,audio:t.audio},d=y("MEDIA_DEVICE_CONSTRAINTS");if(d)try{typeof d=="string"&&(d=JSON.parse(d)),c=UE(c,d)}catch(h){}_.debug("[".concat(e,"] GetUserMedia"),JSON.stringify(c)),vt();let l,u=null;(je()||li()||su())&&(u=yield sm.lock());try{l=yield navigator.mediaDevices.getUserMedia(c)}catch(h){throw u&&u(),h}return c.audio&&(QI=!0),c.video&&(ZI=!0),fa(r,l),u&&u(),r})}function Tu(t,e){switch(t){case"Starting video failed":case"OverconstrainedError":case"TrackStartError":return new k(v.MEDIA_OPTION_INVALID,"".concat(t,": ").concat(e));case"NotFoundError":case"DevicesNotFoundError":return new k(v.DEVICE_NOT_FOUND,"".concat(t,": ").concat(e));case"NotSupportedError":return new k(v.NOT_SUPPORTED,"".concat(t,": ").concat(e));case"NotReadableError":return new k(v.NOT_READABLE,"".concat(t,": ").concat(e));case"InvalidStateError":case"NotAllowedError":case"PERMISSION_DENIED":case"PermissionDeniedError":return new k(v.PERMISSION_DENIED,"".concat(t,": ").concat(e));case"ConstraintNotSatisfiedError":return new k(v.CONSTRAINT_NOT_SATISFIED,"".concat(t,": ").concat(e));default:return _.error("getUserMedia unexpected error",t),new k(v.UNEXPECTED_ERROR,"".concat(t,": ").concat(e))}}function fa(t,e){const i=t.getVideoTracks()[0],n=t.getAudioTracks()[0],r=e.getVideoTracks()[0],o=e.getAudioTracks()[0];o&&(n&&t.removeTrack(n),t.addTrack(o)),r&&(i&&t.removeTrack(i),t.addTrack(r))}const en=new class extends $t{get state(){return this._state}set state(t){t!==this._state&&(this.emit(es.STATE_CHANGE,t),this._state=t)}constructor(){super(),D(this,"_state",Uc.IDLE),D(this,"isAccessMicrophonePermission",!1),D(this,"isAccessCameraPermission",!1),D(this,"lastAccessMicrophonePermission",!1),D(this,"lastAccessCameraPermission",!1),D(this,"checkdeviceMatched",!1),D(this,"deviceInfoMap",new Map),this.init().then(()=>{navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",this.updateDevicesInfo.bind(this)),window.setInterval(()=>{(y("ENUMERATE_DEVICES_INTERVAL")||(au()||ou()===we.HARMONY_OS)&&Vr())&&this.updateDevicesInfo()},y("ENUMERATE_DEVICES_INTERVAL_TIME"))}).catch(t=>_.error(t.toString()))}enumerateDevices(i,n){return C(this,arguments,function*(t,e){let r=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)return new k(v.NOT_SUPPORTED,"enumerateDevices() not supported.").throw();const o=yield navigator.mediaDevices.enumerateDevices(),s=this.checkMediaDeviceInfoIsOk(o);let a=!this.isAccessMicrophonePermission&&t,c=!this.isAccessCameraPermission&&e;s.audio&&(a=!1),s.video&&(c=!1);let d=null,l=null,u=null;if(!r&&(a||c)){if(sm.isLocked&&(_.debug("[device manager] wait GUM lock"),(yield sm.lock())(),_.debug("[device manager] GUM unlock")),QI&&(a=!1,this.isAccessMicrophonePermission=!0),ZI&&(c=!1,this.isAccessCameraPermission=!0),_.debug("[device manager] check media device permissions",t,e,a,c),a&&c){try{u=yield navigator.mediaDevices.getUserMedia({audio:!0,video:!0})}catch(h){const p=Tu(h.name||h.code||h,h.message);if(p.code===v.PERMISSION_DENIED)throw p;_.warning("getUserMedia failed in getDevices",p)}this.isAccessCameraPermission=!0,this.isAccessMicrophonePermission=!0}else if(a){try{d=yield navigator.mediaDevices.getUserMedia({audio:t})}catch(h){const p=Tu(h.name||h.code||h,h.message);if(p.code===v.PERMISSION_DENIED)throw p;_.warning("getUserMedia failed in getDevices",p)}this.isAccessMicrophonePermission=!0}else if(c){try{l=yield navigator.mediaDevices.getUserMedia({video:e})}catch(h){const p=Tu(h.name||h.code||h,h.message);if(p.code===v.PERMISSION_DENIED)throw p;_.warning("getUserMedia failed in getDevices",p)}this.isAccessCameraPermission=!0}_.debug("[device manager] mic permission",t,"cam permission",e)}try{const h=yield navigator.mediaDevices.enumerateDevices();return d&&d.getTracks().forEach(p=>p.stop()),l&&l.getTracks().forEach(p=>p.stop()),u&&u.getTracks().forEach(p=>p.stop()),d=null,l=null,u=null,h}catch(h){return d&&d.getTracks().forEach(p=>p.stop()),l&&l.getTracks().forEach(p=>p.stop()),u&&u.getTracks().forEach(p=>p.stop()),d=null,l=null,u=null,new k(v.ENUMERATE_DEVICES_FAILED,h.toString()).throw()}})}getRecordingDevices(){return C(this,arguments,function*(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(yield this.enumerateDevices(!0,!1,t)).filter(e=>e.kind==="audioinput")})}getCamerasDevices(){return C(this,arguments,function*(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(yield this.enumerateDevices(!1,!0,t)).filter(e=>e.kind==="videoinput")})}getSpeakers(){return C(this,arguments,function*(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return(yield this.enumerateDevices(!0,!1,t)).filter(e=>e.kind==="audiooutput")})}searchDeviceIdByName(t){let e=null;return this.deviceInfoMap.forEach(i=>{i.device.label===t&&(e=i.device.deviceId)}),e}getDeviceById(t){return C(this,null,function*(){const e=(yield this.enumerateDevices(!0,!0,!0)).find(i=>i.deviceId===t);if(!e)throw new k(v.DEVICE_NOT_FOUND,"deviceId: ".concat(t));return e})}init(){return C(this,null,function*(){this.state=Uc.INITING;try{yield this.updateDevicesInfo(),this.state=Uc.INITEND}catch(t){throw _.warning("Device Detection functionality cannot start properly.",t.toString()),this.state=Uc.IDLE,(typeof isSecureContext=="boolean"?isSecureContext:location.protocol==="https:"||location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"||location.hostname==="::1")||new k(v.WEB_SECURITY_RESTRICT,"Your context is limited by web security, please try using https protocol or localhost.").throw(),t}})}updateDevicesInfo(){return C(this,null,function*(){const t=yield this.enumerateDevices(!0,!0,!0),e=Date.now(),i=[];if(t[0]&&t[0].label&&this.checkdeviceMatched===!1){this.checkdeviceMatched=!0;const r=t.find(s=>s.kind==="audioinput"&&s.deviceId==="default"),o=t.find(s=>s.kind==="audiooutput"&&s.deviceId==="default");r&&o?o.groupId===r.groupId?_.debug("[device-check] default input ".concat(r.label," and output ").concat(o.label," is the same group")):_.debug("[device-check] default input ".concat(r.label," and output ").concat(o.label," is not the same group")):_.debug("[device-check] default input or output not found")}const n=this.checkMediaDeviceInfoIsOk(t);if(t.forEach(r=>{if(!r.deviceId)return;const o=this.deviceInfoMap.get("".concat(r.kind,"_").concat(r.deviceId));if((o?o.state:"INACTIVE")!=="ACTIVE"){const s={initAt:e,updateAt:e,device:r,state:"ACTIVE"};this.deviceInfoMap.set("".concat(r.kind,"_").concat(r.deviceId),s),i.push(s)}o&&(o.updateAt=e)}),this.deviceInfoMap.forEach((r,o)=>{r.state==="ACTIVE"&&r.updateAt!==e&&(r.state="INACTIVE",i.push(r))}),this.state!==Uc.INITEND)return n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),void(n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0));i.forEach(r=>{switch(r.device.kind){case"audioinput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(es.RECORDING_DEVICE_CHANGED,r);break;case"videoinput":this.lastAccessCameraPermission&&this.isAccessCameraPermission&&this.emit(es.CAMERA_DEVICE_CHANGED,r);break;case"audiooutput":this.lastAccessMicrophonePermission&&this.isAccessMicrophonePermission&&this.emit(es.PLAYOUT_DEVICE_CHANGED,r)}}),n.audio&&(this.lastAccessMicrophonePermission=!0,this.isAccessMicrophonePermission=!0),n.video&&(this.lastAccessCameraPermission=!0,this.isAccessCameraPermission=!0)})}checkMediaDeviceInfoIsOk(t){const e=t.filter(r=>r.kind==="audioinput"),i=t.filter(r=>r.kind==="videoinput"),n={audio:!1,video:!1};for(const r of e)if(r.label&&r.deviceId){n.audio=!0;break}for(const r of i)if(r.label&&r.deviceId){n.video=!0;break}return n}};let am=!1;const nn=new class extends $t{constructor(){super(...arguments),D(this,"onAutoplayFailed",void 0),D(this,"onAudioAutoplayFailed",void 0)}};function $I(){if(vt(),!am){const t=e=>{e.preventDefault(),am=!1,bc()?document.body.removeEventListener("click",t,!0):(document.body.removeEventListener("touchstart",t,!0),document.body.removeEventListener("mousedown",t,!0))};am=!0,bc()?document.body.addEventListener("click",t,!0):(document.body.addEventListener("touchstart",t,!0),document.body.addEventListener("mousedown",t,!0)),_.info("detect media autoplay failed, document: https://docs.agora.io/cn/Voice/autoplay_policy_web_ng?platform=Web"),nn.onAutoplayFailed?nn.onAutoplayFailed():nn.onAudioAutoplayFailed?_.warning(`AgoraRTC.onAudioAutoplayFailed has been deprecated in favor of AgoraRTC.onAutoplayFailed.
Please refer to the Agora document to migrate the newer API, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .`):_.warning(`We have detected a media autoplay failed event, and found out that you haven't implemented AgoraRTC.onAutoplayFailed callback yet.
It will cause audio/video element not playing automatically on some browsers without user interaction, possibly hurting user experiences.
Please refer to the Agora document to properly handle autoplay failed event, https://docs.agora.io/en/Voice/autoplay_policy_web_ng?platform=Web .`),nn.emit("autoplay-failed")}}function tA(t,e,i,n){if(!t)return;const r=Z.getBaseInfoBySessionId(t);if(!r)return;const o=r.info,s=Date.now(),a=Qt(Qt({},o),{},{vid:o.vid===void 0?0:Number(o.vid),lts:s,elapse:s-r.startTime,cbRegistered:nn.onAutoplayFailed||nn.onAudioAutoplayFailed?1:-1,errorMsg:i,mediaType:e,trackId:n,extend:void 0});Z.send({type:Jt.AUTOPLAY_FAILED,data:a},!0)}const p3=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","error"],Ri=new class{constructor(){D(this,"onAutoplayFailed",void 0),D(this,"elementMap",new Map),D(this,"elementStateMap",new Map),D(this,"elementsNeedToResume",[]),D(this,"sinkIdMap",new Map),D(this,"autoResumeAfterInterruption",t=>{Array.from(this.elementMap.entries()).forEach(e=>{let[i,n]=e;const r=this.elementStateMap.get(i),o=n.srcObject.getAudioTracks()[0],s=o&&o.readyState;if(_.debug("resume after interrupted, ele: ".concat(r," audio: ").concat(s," ").concat(t)),s==="live"){if(t)return n.pause(),void n.play();if(Mt.curState==="running")return na()?(n.pause(),void n.play()):void(r&&r==="paused"&&n.play())}})}),D(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{Array.from(this.elementMap.entries()).forEach(t=>{let[e,i]=t;const n=i.srcObject.getAudioTracks()[0];n&&n.readyState==="live"&&(_.debug("auto resume after interruption inside autoResumeAfterInterruptionOnIOS15"),i.pause(),i.play())})}),this.autoResumeAudioElement(),Mt.on(Ve.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Mt.on(Ve.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),Mt.on(Ve.STATE_CHANGE,()=>{li()&&Mt.prevState==="suspended"&&Mt.curState==="running"&&this.autoResumeAfterInterruption()})}setSinkID(t,e){return C(this,null,function*(){const i=this.elementMap.get(t);if(this.sinkIdMap.set(t,e),i)try{yield i.setSinkId(e)}catch(n){throw new k(v.PERMISSION_DENIED,"can not set sink id: "+n.toString())}})}play(t,e,i,n){if(this.elementMap.has(e))return;const r=document.createElement("audio");r.autoplay=!0,r.srcObject=new MediaStream([t]),this.bindAudioElementEvents(e,r),this.elementMap.set(e,r),this.elementStateMap.set(e,ii.INIT),this.setVolume(e,i);const o=this.sinkIdMap.get(e);if(o)try{r.setSinkId(o).catch(a=>{_.warning("[".concat(e,"] set sink id failed"),a.toString())})}catch(a){_.warning("[".concat(e,"] set sink id failed"),a.toString())}const s=r.play();s&&s.then&&s.catch(a=>{n&&tA(n,"audio",a.message,e),_.warning("audio element play warning",a.toString()),this.elementMap.has(e)&&a.name==="NotAllowedError"&&(_.warning("detected audio element autoplay failed"),this.elementsNeedToResume.push(r),du(()=>{this.onAutoplayFailed&&this.onAutoplayFailed(),$I()}))})}updateTrack(t,e){const i=this.elementMap.get(t);i&&(i.srcObject=new MediaStream([e]))}isPlaying(t){return this.elementMap.has(t)&&this.elementStateMap.get(t)==="playing"}setVolume(t,e){const i=this.elementMap.get(t);i&&(e=Math.max(0,Math.min(100,e)),i.volume=e/100)}stop(t){const e=this.elementMap.get(t);if(this.sinkIdMap.delete(t),!e)return;const i=this.elementsNeedToResume.indexOf(e);this.elementsNeedToResume.splice(i,1),e.srcObject=null,e.remove(),this.elementMap.delete(t),this.elementStateMap.delete(t)}bindAudioElementEvents(t,e){p3.forEach(i=>{e.addEventListener(i,n=>{const r=this.elementStateMap.get(t),o=n.type==="pause"?"paused":n.type;if(_.debug("[".concat(t,"] audio-element-status change ").concat(r," => ").concat(o)),n.type==="error"){const s=e==null?void 0:e.error;s&&_.error("[".concat(t,"] media error, code: ").concat(s.code,", message: ").concat(s.message))}this.elementStateMap.set(t,o)})})}getPlayerState(t){return this.elementStateMap.get(t)||"uninit"}autoResumeAudioElement(){const t=()=>{this.elementsNeedToResume.forEach(e=>{e.play().then(i=>{_.debug("Auto resume audio element success")}).catch(i=>{_.warning("Auto resume audio element failed!",i)})}),this.elementsNeedToResume=[]};new K(e=>{document.body?e():window.addEventListener("load",()=>e())}).then(()=>{bc()?document.body.addEventListener("click",t,!0):(document.body.addEventListener("touchstart",t,!0),document.body.addEventListener("mousedown",t,!0))})}};function le(){return function(t,e,i){const n=i.value;return typeof n=="function"&&(i.value=function(){this._isClosed&&new k(v.INVALID_OPERATION,"[".concat(this.getTrackId(),"] cannot operate a closed track")).print("warning",_);for(var r=arguments.length,o=new Array(r),s=0;s<r;s++)o[s]=arguments[s];const a=n.apply(this,o);return a instanceof K?new K((c,d)=>{a.then(c).catch(d)}):a}),i}}class eA extends $t{constructor(e){super(),D(this,"name","VideoProcessorDestination"),D(this,"ID","0"),D(this,"_source",void 0),D(this,"videoContext",void 0),D(this,"inputTrack",void 0),this.videoContext=e}get kind(){return"video"}get enabled(){return!0}pipe(){throw new k(v.NOT_SUPPORTED,"VideoProcessor cannot pipe to any other Processor")}unpipe(){throw new k(v.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.
Probably you are making pipeline like this:
videoTrack1.pipe(processor).pipe(videoTrack2.processorDestination).`);e.track&&e.track!==this.inputTrack&&(this.videoContext.chained=!0,this.inputTrack=e.track,this.emit(ui.ON_TRACK,e.track))}reset(){this.inputTrack=void 0,this.videoContext.chained=!1,this.emit(ui.ON_TRACK,void 0)}}class iA extends $t{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,i){super(),D(this,"constraintsMap",new Map),D(this,"statsRegistry",[]),D(this,"usageRegistry",[]),D(this,"trackId",void 0),D(this,"direction",void 0),D(this,"_chained",!1),this.trackId=e,this.direction=i}getConstraints(){return C(this,null,function*(){return yield We(this,Zi.REQUEST_CONSTRAINTS)})}requestApplyConstraints(e,i){return C(this,null,function*(){var n;return _.info("processor ".concat(i.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(i,e),Bt(this,Zi.REQUEST_UPDATE_CONSTRAINTS,Array.from(Ui(n=this.constraintsMap).call(n)))})}requestRevertConstraints(e){return C(this,null,function*(){var i;if(this.constraintsMap.has(e))return _.info("processor ".concat(e.name," requestRevertConstraints for ").concat(this.trackId)),this.constraintsMap.delete(e),Bt(this,Zi.REQUEST_UPDATE_CONSTRAINTS,Array.from(Ui(i=this.constraintsMap).call(i)))})}registerStats(e,i,n){this.statsRegistry.find(r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===i)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:i,cb:n})}unregisterStats(e,i){const n=this.statsRegistry.findIndex(r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===i);n!==-1&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const{processorID:i,processorName:n,type:r,cb:o}of this.statsRegistry)try{const s=o();e.push({processorID:i,processorName:n,type:r,stats:s})}catch(s){_.error(new k(v.UNEXPECTED_ERROR,s.message))}return e}registerUsage(e,i){this.usageRegistry.find(n=>n.processorID===e.ID&&n.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:i})}unregisterUsage(e){const i=this.usageRegistry.findIndex(n=>n.processorID===e.ID&&n.processorName===e.name);i!==-1&&this.usageRegistry.splice(i,1)}gatherUsage(){return C(this,null,function*(){const e=[];if(!this.chained)return[];for(const{cb:i}of this.usageRegistry)try{let n=i();n instanceof K&&(n=yield n),e.push(Qt(Qt({},n),{},{direction:this.direction}))}catch(n){_.error("gather extension usage error",n)}return e})}getDirection(){return this.direction}}class nA extends $t{constructor(e){super(),D(this,"name","AudioProcessorDestination"),D(this,"ID","0"),D(this,"inputTrack",void 0),D(this,"inputNode",void 0),D(this,"audioProcessorContext",void 0),D(this,"_source",void 0),this.audioProcessorContext=e}get kind(){return"audio"}get enabled(){return!0}pipe(){throw new k(v.NOT_SUPPORTED,"AudioProcessorDestination cannot pipe to any other Processor")}unpipe(){throw new k(v.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(ui.ON_TRACK,void 0),this.emit(ui.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.
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(ui.ON_TRACK,this.inputTrack)),e.node&&this.inputNode!==e.node&&(this.audioProcessorContext.chained=!0,this.inputNode=e.node,this.emit(ui.ON_NODE,this.inputNode))}}class rA extends $t{set chained(e){this._chained=e}get chained(){return this._chained}constructor(e,i,n){super(),D(this,"constraintsMap",new Map),D(this,"statsRegistry",[]),D(this,"audioContext",void 0),D(this,"trackId",void 0),D(this,"direction",void 0),D(this,"usageRegistry",[]),D(this,"_chained",!1),this.audioContext=e,this.trackId=i,this.direction=n}getConstraints(){return C(this,null,function*(){return We(this,Zi.REQUEST_CONSTRAINTS)})}getAudioContext(){return this.audioContext}requestApplyConstraints(e,i){return C(this,null,function*(){var n;return _.info("processor ".concat(i.name," requestApplyConstraints for ").concat(this.trackId)),e&&this.constraintsMap.set(i,e),Bt(this,Zi.REQUEST_UPDATE_CONSTRAINTS,Array.from(Ui(n=this.constraintsMap).call(n)))})}requestRevertConstraints(e){return C(this,null,function*(){var i;if(this.constraintsMap.has(e))return this.constraintsMap.delete(e),Bt(this,Zi.REQUEST_UPDATE_CONSTRAINTS,Array.from(Ui(i=this.constraintsMap).call(i)))})}registerStats(e,i,n){this.statsRegistry.find(r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===i)||this.statsRegistry.push({processorName:e.name,processorID:e.ID,type:i,cb:n})}unregisterStats(e,i){const n=this.statsRegistry.findIndex(r=>r.processorID===e.ID&&r.processorName===e.name&&r.type===i);n!==-1&&this.statsRegistry.splice(n,1)}gatherStats(){const e=[];for(const{processorID:i,processorName:n,type:r,cb:o}of this.statsRegistry)try{const s=o();e.push({processorID:i,processorName:n,type:r,stats:s})}catch(s){_.error(new k(v.UNEXPECTED_ERROR,s.message))}return e}registerUsage(e,i){this.usageRegistry.find(n=>n.processorID===e.ID&&n.processorName===e.name)||this.usageRegistry.push({processorID:e.ID,processorName:e.name,cb:i})}unregisterUsage(e){const i=this.usageRegistry.findIndex(n=>n.processorID===e.ID&&n.processorName===e.name);i!==-1&&this.usageRegistry.splice(i,1)}gatherUsage(){return C(this,null,function*(){const e=[];if(!this.chained)return[];for(const{cb:i}of this.usageRegistry)try{let n=i();n instanceof K&&(n=yield n),e.push(Qt(Qt({},n),{},{direction:this.direction}))}catch(n){_.error("gather extension usage error",n)}return e})}getDirection(){return this.direction}}class cm extends $t{get isPlayed(){return!0}get isFreeze(){return!1}constructor(){super(),D(this,"context",void 0),D(this,"processSourceNode",void 0),D(this,"outputTrack",void 0),D(this,"processedNode",void 0),D(this,"clonedTrack",void 0),D(this,"outputNode",void 0),this.outputNode=new _3}setVolume(){}createOutputTrack(){throw new k(v.NOT_SUPPORTED,"can not create output MediaStreamTrack when WebAudio disabled")}getOriginVolumeLevel(){return 0}getAccurateVolumeLevel(){return 0}stopGetAudioBuffer(){}startGetAudioBuffer(){}play(){}stop(){}destroy(){}updateTrack(){}updateOriginTrack(){}createMediaStreamSourceNode(){}}class _3{disconnect(){}connect(){}}function oA(t){return new K((e,i)=>{let n=!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=li()?"canplay":"playing";r.addEventListener(o,()=>{const s=r.videoWidth,a=r.videoHeight;!s&&ne()||(n=!0,r.srcObject=null,r.remove(),e([s,a]))}),r.srcObject=new MediaStream([t]),r.play().catch(lu),setTimeout(()=>{n||(r.srcObject=null,r.remove(),e([r.videoWidth,r.videoHeight]))},4e3)})}function Ru(t){const e={};t.facingMode&&(e.facingMode=t.facingMode),t.cameraId&&(e.deviceId={exact:t.cameraId});const i=Nn(t.encoderConfig);return i.width!=null&&(e.width=i.width),i.height!=null&&(e.height=i.height),!nI()&&i.frameRate&&(e.frameRate=i.frameRate),Xy()&&typeof e.frameRate=="object"&&(e.frameRate.max=60),ne()&&(e.frameRate={ideal:30,max:30}),e}function sA(t){const e={};return nI()||(t.AGC!==void 0&&(e.autoGainControl=t.AGC),t.AEC!==void 0&&(e.echoCancellation=t.AEC),t.ANS!==void 0&&(e.noiseSuppression=t.ANS,xr()&&t.ANS&&(e.googHighpassFilter=t.ANS))),e}function aA(t){const e=sA(t);if(t.encoderConfig){const i=gu(t.encoderConfig);e.channelCount=i.stereo?2:1,e.sampleRate=i.sampleRate,e.sampleSize=i.sampleSize}return t.microphoneId&&(e.deviceId={exact:t.microphoneId}),au()&&(e.sampleRate=void 0),e}const E3=t=>{const e=t._encoderConfig;if(!e)return;const{frameRate:i,width:n,height:r}=t.getMediaStreamTrackSettings();let{frameRate:o=i,width:s=n,height:a=r}=e;if(!o||!s||!a)return;s=xE(s),a=xE(a),o=xE(o);const{max:c,min:d}=function(p,g,m){const f=200*Math.pow(m/15,.6)*Math.pow(p*g/640/360,.75);return{min:Math.floor(f),max:Math.floor(4*f)}}(s,a,o),{bitrateMax:l,bitrateMin:u}=e||{};l||_.debug("calculate bitrate: [w: ".concat(s,", h: ").concat(a,", fps: ").concat(o,"] => [brMax: ").concat(l,", brMin: ").concat(u,"]"));const{maxFramerate:h}=y("ENCODER_CONFIG_LIMIT");return h&&typeof h=="number"&&(o=Math.min(o,h)),{frameRate:o,bitrateMax:l||c,bitrateMin:u||d,scaleResolutionDownBy:1,scale:0}},cA=(t,e,i)=>C(this,null,function*(){return yield((n,r,o)=>C(this,null,function*(){const s=function(d){const l=[];for(let u=0;u<d.length;u+=2)l.push(parseInt(d.slice(u,u+2),16));return Uint8Array.from(l)}(SI(""+r+o)).slice(0,16),a=s.slice(0,12),c=yield window.crypto.subtle.importKey("raw",s,"AES-GCM",!0,["encrypt"]);return new Uint8Array(yield window.crypto.subtle.encrypt({name:"AES-GCM",iv:a},c,n))}))(t.buffer,e,i)}),dm=t=>{const e=document.createElement("canvas");return e.width=2,e.height=2,new K((i,n)=>{e.toBlob(r=>C(this,null,function*(){if(e.remove(),r){const o=yield dA(r);i({buffer:o,width:e.width,height:e.height})}else n(new k(v.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),t,1)})},dA=t=>C(this,null,function*(){const e=yield t.arrayBuffer();return new Uint8Array(e)});var lA,uA,hA,pA,_A,EA,mA,fA,gA,SA,TA,RA,vA,CA,yA,IA,AA,bA,ee,wA,OA,NA,DA,PA,LA,gr,kA,MA,UA,xA,VA,FA,BA,jA,GA,WA,HA,KA,YA,Ke;let ae=(lA=it({argsMap:(t,e)=>[t.getTrackId(),e],throttleTime:300}),uA=it({argsMap:(t,e)=>[t.getTrackId(),e]}),hA=le(),pA=sa("LocalAudioTrack","_enabledMutex"),_A=it({argsMap:(t,e)=>[t.getTrackId(),e]}),EA=le(),mA=sa("LocalAudioTrack","_enabledMutex"),fA=it({argsMap:(t,e)=>[t.getTrackId(),e]}),gA=le(),SA=le(),TA=le(),RA=it({argsMap:t=>[t.getTrackId()]}),vA=le(),CA=it({argsMap:t=>[t.getTrackId()]}),yA=le(),IA=it({argsMap:t=>[t.getTrackId()]}),AA=it({argsMap:(t,e)=>[t.getTrackId(),e.name]}),bA=it({argsMap:t=>[t.getTrackId()]}),gt((ee=class extends Ea{get _source(){return this.initWebAudio()}set _source(t){this._trackSource=t}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?Ri.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"LocalAudioTrack"}constructor(t,e,i,n){super(t,i),D(this,"trackMediaType",_a.AUDIO),D(this,"_encoderConfig",void 0),D(this,"_trackSource",void 0),D(this,"metadata",[]),D(this,"_enabled",!0),D(this,"_volume",100),D(this,"_useAudioElement",!0),D(this,"_bypassWebAudio",!1),D(this,"processor",void 0),D(this,"_processorContext",void 0),D(this,"_processorDestination",void 0),D(this,"_getOriginVolumeLevel",void 0),this._encoderConfig=e,this._getOriginVolumeLevel=!!n,this._trackSource=new cm,y("DISABLE_WEBAUDIO")&&(this._bypassWebAudio=!0),y("LOCAL_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1),je()&&!$i?setTimeout(()=>this.initWebAudio()):this.initWebAudio()}setVolume(t){xt(t,"volume",0,1e3),this._volume=t,this._source.setVolume(t/100),this._useAudioElement&&Ri.setVolume(this.getTrackId(),t);try{if(this._bypassWebAudio)return void _.debug("[".concat(this.getTrackId(),"] setVolume returned because no pass through WebAudio."));const e=this._source.createOutputTrack();this._mediaStreamTrack!==e&&(this._mediaStreamTrack=e,Bt(this,J.NEED_REPLACE_TRACK,this).then(()=>{_.debug("[".concat(this.getTrackId(),"] replace web audio track success"))}).catch(i=>{_.warning("[".concat(this.getTrackId(),"] replace web audio track failed"),i)}))}catch(e){}}getVolumeLevel(){return this._muted&&this.enabled&&this._getOriginVolumeLevel?this._source.getOriginVolumeLevel():this._source.getAccurateVolumeLevel()}setPlaybackDevice(t){return C(this,null,function*(){if(!this._useAudioElement||!VI())throw new k(v.NOT_SUPPORTED,"your browser does not support setting the audio output device");yield Ri.setSinkID(this.getTrackId(),t)})}setEnabled(t,e,i){return C(this,null,function*(){return this._setEnabled(t,e,i)})}_setEnabled(t,e,i){return C(this,null,function*(){if(!i){if(t===this._enabled)return;this.stateCheck("enabled",t)}if(_.info("[".concat(this.getTrackId(),"] start setEnabled"),t),t){this._originMediaStreamTrack.enabled=!0;try{i||(this._enabled=!0),yield Bt(this,J.NEED_ENABLE_TRACK,this),_.info("[".concat(this.getTrackId(),"] setEnabled to ").concat(t," success"))}catch(n){throw i||(this._enabled=!1),_.error("[".concat(this.getTrackId(),"] setEnabled to true error"),n.toString()),n}}else{this._originMediaStreamTrack.enabled=!1,i||(this._enabled=!1);try{yield Bt(this,J.NEED_DISABLE_TRACK,this)}catch(n){throw i||(this._enabled=!0),_.error("[".concat(this.getTrackId(),"] setEnabled to false error"),n.toString()),n}}})}setMuted(t){return C(this,null,function*(){t!==this._muted&&(this.stateCheck("muted",t),this._muted=t,this._originMediaStreamTrack.enabled=!t,_.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(t)),t?yield Bt(this,J.NEED_MUTE_TRACK,this):yield Bt(this,J.NEED_UNMUTE_TRACK,this))})}getStats(){return _o(()=>{_.warning("[deprecated] LocalAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalAudioStats instead")},"localAudioTrackGetStatsWarning"),zi(this,J.GET_STATS)||Qt({},em)}setAudioFrameCallback(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:4096;if(!t)return this._source.removeAllListeners(Qi.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(e),this._source.removeAllListeners(Qi.ON_AUDIO_BUFFER),this._source.on(Qi.ON_AUDIO_BUFFER,i=>t(i))}play(){_.debug("[".concat(this.getTrackId(),"] start audio playback")),this._useAudioElement?(_.debug("[".concat(this.getTrackId(),"] start audio playback in element")),Ri.play(this._mediaStreamTrack,this.getTrackId(),this._volume)):this._source.play()}stop(){_.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._useAudioElement?Ri.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._source.destroy()}_updatePlayerSource(){let t=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];_.debug("[".concat(this.getTrackId(),"] update player source track")),t&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Ri.updateTrack(this.getTrackId(),this._mediaStreamTrack)}_updateOriginMediaStreamTrack(t,e){return C(this,null,function*(){this._originMediaStreamTrack!==t&&(this._originMediaStreamTrack&&(this._originMediaStreamTrack.removeEventListener("ended",this._handleTrackEnded),e&&this._originMediaStreamTrack.stop()),t.addEventListener("ended",this._handleTrackEnded),this._originMediaStreamTrack=t,this._muted&&(this._originMediaStreamTrack.enabled=!1),this.processor&&this._processorContext&&this.processor.updateInput({track:t,context:this._processorContext}),this._mediaStreamTrack!==this._source.outputTrack?(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),yield Bt(this,J.NEED_REPLACE_TRACK,this)):this._source.updateTrack(this._originMediaStreamTrack),this._getOriginVolumeLevel&&this._source.updateOriginTrack(t))})}renewMediaStreamTrack(t){return K.resolve(void 0)}pipe(t){if(this._bypassWebAudio)throw new k(v.INVALID_OPERATION,"Can not process AudioTrack when bypassWebAudio set to true.");if(this.processor===t)return t;if(t._source)throw new k(v.INVALID_OPERATION,"Processor ".concat(t.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=t,this.processor._source=this,t.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),t}unpipe(){var t;if(!this.processor)return;const e=this.processor;(t=this._source.processSourceNode)===null||t===void 0||t.disconnect(),this.processor._source=!1,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(t){t.on(ui.ON_TRACK,e=>C(this,null,function*(){e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(e),yield Bt(this,J.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),yield Bt(this,J.NEED_REPLACE_TRACK,this))})),t.on(ui.ON_NODE,e=>{this._source.processedNode=e})}unbindProcessorDestinationEvents(t){t.removeAllListeners(ui.ON_TRACK),t.removeAllListeners(ui.ON_NODE)}bindProcessorContextEvents(t){t.on(Zi.REQUEST_CONSTRAINTS,e=>C(this,null,function*(){e(this._originMediaStreamTrack.getSettings())}))}unbindProcessorContextEvents(t){t.removeAllListeners(Zi.REQUEST_CONSTRAINTS)}initWebAudio(){return this._trackSource instanceof cm&&(this._trackSource=new zI(this._mediaStreamTrack,!1,this._getOriginVolumeLevel?this._mediaStreamTrack:void 0)),this._trackSource}initProcessor(){const t=new rA(this._source.context,this.getTrackId(),"local"),e=new nA(t);return this._processorContext=t,this._processorDestination=e,this.bindProcessorContextEvents(t),this.bindProcessorDestinationEvents(e),this._source.on(Qi.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:t})}),this._useAudioElement&&(this._useAudioElement=!1,this.isPlaying&&(Ri.stop(this.getTrackId()),this._source.play()),Bt(this,J.NEED_REPLACE_MIXING_TRACK,this).then(()=>{_.debug("[".concat(this.getTrackId(),"] replace from origin track to web audio track success"))}).catch(i=>{_.warning("[".concat(this.getTrackId(),"] replace from origin track to web audio track failed"),i)})),{processorContext:t,processorDestination:e}}}).prototype,"setVolume",[lA],Object.getOwnPropertyDescriptor(ee.prototype,"setVolume"),ee.prototype),gt(ee.prototype,"setPlaybackDevice",[uA,hA],Object.getOwnPropertyDescriptor(ee.prototype,"setPlaybackDevice"),ee.prototype),gt(ee.prototype,"setEnabled",[pA,_A,EA],Object.getOwnPropertyDescriptor(ee.prototype,"setEnabled"),ee.prototype),gt(ee.prototype,"setMuted",[mA,fA,gA],Object.getOwnPropertyDescriptor(ee.prototype,"setMuted"),ee.prototype),gt(ee.prototype,"getStats",[SA],Object.getOwnPropertyDescriptor(ee.prototype,"getStats"),ee.prototype),gt(ee.prototype,"setAudioFrameCallback",[TA],Object.getOwnPropertyDescriptor(ee.prototype,"setAudioFrameCallback"),ee.prototype),gt(ee.prototype,"play",[RA,vA],Object.getOwnPropertyDescriptor(ee.prototype,"play"),ee.prototype),gt(ee.prototype,"stop",[CA,yA],Object.getOwnPropertyDescriptor(ee.prototype,"stop"),ee.prototype),gt(ee.prototype,"close",[IA],Object.getOwnPropertyDescriptor(ee.prototype,"close"),ee.prototype),gt(ee.prototype,"pipe",[AA],Object.getOwnPropertyDescriptor(ee.prototype,"pipe"),ee.prototype),gt(ee.prototype,"unpipe",[bA],Object.getOwnPropertyDescriptor(ee.prototype,"unpipe"),ee.prototype),ee),xc=(wA=it({argsMap:(t,e)=>[t.getTrackId(),e]}),OA=le(),NA=sa("MicrophoneAudioTrack","_enabledMutex"),DA=it({argsMap:(t,e,i)=>[t.getTrackId(),e,i]}),PA=le(),LA=it({argsMap:t=>[t.getTrackId()]}),gt((gr=class t extends ae{get __className__(){return"MicrophoneAudioTrack"}constructor(e,i,n,r){super(e,i.encoderConfig?gu(i.encoderConfig):{},r,y("GET_VOLUME_OF_MUTED_AUDIO_TRACK")),D(this,"_config",void 0),D(this,"_deviceName","default"),D(this,"_constraints",void 0),D(this,"_originalConstraints",void 0),D(this,"_enabled",!0),this._config=i,this._constraints=n,this._originalConstraints=n,this._deviceName=e.label,typeof i.bypassWebAudio=="boolean"&&(this._bypassWebAudio=i.bypassWebAudio),(na()||OE())&&Mt.bindInterruptDetectorTrack(this)}setDevice(e){return C(this,null,function*(){if(_.info("[".concat(this.getTrackId(),"] start set device to ").concat(e)),this._enabled)try{const i=yield en.getDeviceById(e),n={};n.audio=Qt({},this._constraints),n.audio.deviceId={exact:e},this._originMediaStreamTrack.stop();let r=null;try{r=yield tn(n,this.getTrackId())}catch(o){throw _.error("[".concat(this.getTrackId(),"] setDevice failed"),o.toString()),r=yield tn({audio:this._constraints},this.getTrackId()),yield this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),o}yield this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!1),this._deviceName=i.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(i){throw _.error("[".concat(this.getTrackId(),"] setDevice error"),i.toString()),i}else try{const i=yield en.getDeviceById(e);this._deviceName=i.label,this._config.microphoneId=e,this._constraints.deviceId={exact:e}}catch(i){throw _.error("[".concat(this.getTrackId(),"] setDevice error"),i.toString()),i}_.info("[".concat(this.getTrackId(),"] set device to ").concat(e," success"))})}setEnabled(e,i,n){return C(this,null,function*(){if(i)return _.debug("[".concat(this.getTrackId(),"] setEnabled false (do not close microphone)")),yield Uf(t.prototype,this,"_setEnabled").call(this,e);if(!n){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(_.info("[".concat(this.getTrackId(),"] start setEnabled"),e),y("AUTO_RESET_AUDIO_ROUTE")&&(li()||bn())){const a=navigator.audioSession;a&&(e||(a.type="playback"),a.type="auto")}if(!e){var r;this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop(),(r=this._source.clonedTrack)===null||r===void 0||r.stop(),n||(this._enabled=!1);try{yield Bt(this,J.NEED_DISABLE_TRACK,this)}catch(a){throw _.error("[".concat(this.getTrackId(),"] setEnabled false failed"),a.toString()),a}return}const o=Qt({},this._constraints),s=en.searchDeviceIdByName(this._deviceName);s&&!o.deviceId&&(o.deviceId=s);try{n||(this._enabled=!0);const a=yield tn({audio:this._constraints},this.getTrackId());yield this._updateOriginMediaStreamTrack(a.getAudioTracks()[0],!1),yield Bt(this,J.NEED_ENABLE_TRACK,this)}catch(a){throw n||(this._enabled=!1),_.error("[".concat(this.getTrackId(),"] setEnabled true failed"),a.toString()),a}_.info("[".concat(this.getTrackId(),"] setEnabled success"))})}close(){super.close(),(na()||OE())&&Mt.unbindInterruptDetectorTrack(this)}onTrackEnded(){if((li()||bn())&&this._enabled&&!this._isClosed&&Mt.duringInterruption){const e=()=>C(this,null,function*(){Mt.off(Ve.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(_.debug("[".concat(this.getTrackId(),"] try capture microphone media device for interrupted iOS device.")),yield this.setEnabled(!1),yield this.setEnabled(!0))});Mt.on(Ve.IOS_INTERRUPTION_END,e)}else _.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(ha.TRACK_ENDED)}renewMediaStreamTrack(e){return C(this,null,function*(){const i=e||this._constraints,n=en.searchDeviceIdByName(this._deviceName);if(n&&!i.deviceId&&(i.deviceId=n),this._constraints=i,this._enabled){this._originMediaStreamTrack.stop();const r=yield tn({audio:this._constraints},this.getTrackId());yield this._updateOriginMediaStreamTrack(r.getAudioTracks()[0],!0)}})}bindProcessorContextEvents(e){super.bindProcessorContextEvents(e),e.on(Zi.REQUEST_UPDATE_CONSTRAINTS,(i,n,r)=>C(this,null,function*(){try{const o=Object.assign({},this._originalConstraints,...i);yield this.renewMediaStreamTrack(o),n()}catch(o){r(o)}}))}unbindProcessorContextEvents(e){super.unbindProcessorContextEvents(e),e.removeAllListeners(Zi.REQUEST_UPDATE_CONSTRAINTS)}}).prototype,"setDevice",[wA,OA],Object.getOwnPropertyDescriptor(gr.prototype,"setDevice"),gr.prototype),gt(gr.prototype,"setEnabled",[NA,DA,PA],Object.getOwnPropertyDescriptor(gr.prototype,"setEnabled"),gr.prototype),gt(gr.prototype,"close",[LA],Object.getOwnPropertyDescriptor(gr.prototype,"close"),gr.prototype),gr),m3=(kA=it({argsMap:(t,e)=>[t.getTrackId(),e,t.duration]}),MA=le(),UA=it({argsMap:t=>[t.getTrackId()]}),xA=le(),VA=it({argsMap:t=>[t.getTrackId()]}),FA=le(),BA=it({argsMap:t=>[t.getTrackId()]}),jA=le(),GA=it({argsMap:t=>[t.getTrackId()]}),WA=le(),HA=it({argsMap:t=>[t.getTrackId()]}),KA=it({argsMap:t=>[t.getTrackId()]}),YA=le(),gt((Ke=class extends ae{get __className__(){return"BufferSourceAudioTrack"}constructor(t,e,i,n){super(e.createOutputTrack(),i,n),D(this,"source",void 0),D(this,"_bufferSource",void 0),this._useAudioElement=!1,this.source=t,this._bufferSource=e,this._bufferSource.on(Qi.AUDIO_SOURCE_STATE_CHANGE,r=>{this.safeEmit(ha.SOURCE_STATE_CHANGE,r)});try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(r){}}get currentState(){return this._bufferSource.currentState}get duration(){return this._bufferSource.duration}get playbackSpeed(){return this._bufferSource.playbackSpeed}getCurrentTime(){return this._bufferSource.currentTime}startProcessAudioBuffer(t){t&&this._bufferSource.updateOptions(t),this._bufferSource.startProcessAudioBuffer()}pauseProcessAudioBuffer(){this._bufferSource.pauseProcessAudioBuffer()}seekAudioBuffer(t){this._bufferSource.seekAudioBuffer(t)}resumeProcessAudioBuffer(){this._bufferSource.resumeProcessAudioBuffer()}stopProcessAudioBuffer(){this._bufferSource.stopProcessAudioBuffer()}close(){this.source=null,this._bufferSource.destroy(),super.close()}setAudioBufferPlaybackSpeed(t){xt(t,"speed",0),this._bufferSource.setAudioBufferPlaybackSpeed(t)}}).prototype,"startProcessAudioBuffer",[kA,MA],Object.getOwnPropertyDescriptor(Ke.prototype,"startProcessAudioBuffer"),Ke.prototype),gt(Ke.prototype,"pauseProcessAudioBuffer",[UA,xA],Object.getOwnPropertyDescriptor(Ke.prototype,"pauseProcessAudioBuffer"),Ke.prototype),gt(Ke.prototype,"seekAudioBuffer",[VA,FA],Object.getOwnPropertyDescriptor(Ke.prototype,"seekAudioBuffer"),Ke.prototype),gt(Ke.prototype,"resumeProcessAudioBuffer",[BA,jA],Object.getOwnPropertyDescriptor(Ke.prototype,"resumeProcessAudioBuffer"),Ke.prototype),gt(Ke.prototype,"stopProcessAudioBuffer",[GA,WA],Object.getOwnPropertyDescriptor(Ke.prototype,"stopProcessAudioBuffer"),Ke.prototype),gt(Ke.prototype,"close",[HA],Object.getOwnPropertyDescriptor(Ke.prototype,"close"),Ke.prototype),gt(Ke.prototype,"setAudioBufferPlaybackSpeed",[KA,YA],Object.getOwnPropertyDescriptor(Ke.prototype,"setAudioBufferPlaybackSpeed"),Ke.prototype),Ke);class ve extends ae{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=ma().createMediaStreamDestination();super(e.stream.getAudioTracks()[0],void 0,Gt(8,"track-mix-")),D(this,"trackList",void 0),D(this,"destNode",void 0),this._useAudioElement=!1;try{this._mediaStreamTrack=this._source.createOutputTrack()}catch(i){}this.destNode=e,this.trackList=[]}hasAudioTrack(e){return this.trackList.indexOf(e)!==-1}addAudioTrack(e){this.trackList.indexOf(e)===-1?(_.debug("add ".concat(e.getTrackId()," to mixing track")),e._source.outputNode.connect(this.destNode),this.trackList.push(e),this.updateEncoderConfig()):_.debug("track ".concat(e.getTrackId()," is already added"))}removeAudioTrack(e){if(this.trackList.indexOf(e)!==-1){_.debug("remove ".concat(e.getTrackId()," from mixing track"));try{e._source.outputNode.disconnect(this.destNode)}catch(i){}cu(this.trackList,e),this.updateEncoderConfig()}}updateEncoderConfig(){const e={};this.trackList.forEach(i=>{i._encoderConfig&&((i._encoderConfig.bitrate||0)>(e.bitrate||0)&&(e.bitrate=i._encoderConfig.bitrate),(i._encoderConfig.sampleRate||0)>(e.sampleRate||0)&&(e.sampleRate=i._encoderConfig.sampleRate),(i._encoderConfig.sampleSize||0)>(e.sampleSize||0)&&(e.sampleSize=i._encoderConfig.sampleSize),i._encoderConfig.stereo&&(e.stereo=!0))}),this._encoderConfig=e}_updateRtpTransceiver(e){this._rtpTransceiver!==e&&(this._rtpTransceiver=e,this.trackList.forEach(i=>{i instanceof ve?i.emit(ts.TRANSCEIVER_UPDATED,e):i._updateRtpTransceiver(e)}))}}class f3 extends qI{set currentState(e){e!==this._currentState&&(this._currentState=e,this.safeEmit(Qi.AUDIO_SOURCE_STATE_CHANGE,this._currentState))}get currentState(){return this._currentState}constructor(e){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),D(this,"audioBuffer",void 0),D(this,"sourceNode",void 0),D(this,"startPlayTime",0),D(this,"startPlayOffset",0),D(this,"pausePlayTime",0),D(this,"options",void 0),D(this,"currentLoopCount",0),D(this,"currentPlaybackSpeed",100),D(this,"_currentState","stopped"),this.audioBuffer=e,this.options=i,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?this.currentState==="stopped"?0:this.currentState==="paused"?this.pausePlayTime:((this.context.currentTime-this.startPlayTime)*(this.playbackSpeed/100)+this.startPlayOffset)%this.audioBuffer.duration:0}updateOptions(e){this.currentState==="stopped"?(this.options=e,this.startPlayOffset=this.options.startPlayTime||0):_.warning("can not set audio source options")}startProcessAudioBuffer(){this.sourceNode&&this.stopProcessAudioBuffer(),this.sourceNode=this.createSourceNode(),this.startSourceNode(),this.currentState="playing"}pauseProcessAudioBuffer(){this.sourceNode&&this.currentState==="playing"&&(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,this.currentState==="playing"&&this.sourceNode.stop(),this.sourceNode=this.createSourceNode(),this.currentState==="playing"?(this.startPlayOffset=e,this.startSourceNode()):this.currentState==="paused"&&(this.pausePlayTime=e))}resumeProcessAudioBuffer(){this.currentState==="paused"&&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&&(this.currentState==="playing"&&(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 qA=new Map;function zA(t,e){if(t.length===0||e.length===0)return 1/0;const i=VE(t),n=VE(e);return Math.floor(n/i)}class lm{get rendFrameRate(){const e=Math.max(1,zA(this._render_interframe_delays_sizes,this._render_interframe_delays));return Math.floor(1e3/e)}get videoElementStatus(){return this._videoElementStatus}set videoElementStatus(e){e!==this._videoElementStatus&&(_.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 i;e!==this._videoState&&(this._videoState=e,(i=this.onVideoStateChanged)===null||i===void 0||i.call(this,this.videoState))}constructor(e){D(this,"trackId",void 0),D(this,"config",void 0),D(this,"onFirstVideoFrameDecoded",void 0),D(this,"onVideoStateChanged",void 0),D(this,"freezeTimeCounterList",[]),D(this,"renderFreezeAccTime",0),D(this,"renderFreezeAccTime2",0),D(this,"isKeepLastFrame",!1),D(this,"timeUpdatedCount",0),D(this,"freezeTime",0),D(this,"playbackTime",0),D(this,"lastTimeUpdatedTime",0),D(this,"autoplayFailed",!1),D(this,"videoTrack",void 0),D(this,"videoElement",void 0),D(this,"cacheVideoElement",void 0),D(this,"_render_interframe_delays",[]),D(this,"_render_interframe_delays_sizes",[]),D(this,"_videoState",fr.VideoStateStopped),D(this,"videoElementCheckInterval",void 0),D(this,"videoElementFreezeTimeout",void 0),D(this,"_videoElementStatus",ii.NONE),D(this,"isGettingVideoDimensions",!1),D(this,"startGetVideoDimensions",()=>{const i=()=>{if(this.isGettingVideoDimensions=!0,this.videoElement.videoWidth*this.videoElement.videoHeight>4)return _.debug("[".concat(this.trackId,"] current video dimensions:"),this.videoElement.videoWidth,this.videoElement.videoHeight),void(this.isGettingVideoDimensions=!1);setTimeout(i,500)};!this.isGettingVideoDimensions&&i()}),D(this,"autoResumeAfterInterruption",()=>{this.videoTrack&&this.videoTrack.readyState==="live"&&Mt.curState==="running"&&(_.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(zy())),eI()?(this.videoElement.srcObject=null,this.videoElement.srcObject=new MediaStream([this.videoTrack]),this.videoElement.play()):(this.videoElement.pause(),this.videoElement.play()))}),D(this,"handleVideoEvents",i=>{switch(i.type){case"play":case"playing":this.startGetVideoDimensions(),this.videoElementStatus=ii.PLAYING;break;case"loadeddata":if(this.videoState=fr.VideoStateStarting,this.onFirstVideoFrameDecoded&&this.onFirstVideoFrameDecoded(),this.cacheVideoElement){try{this.cacheVideoElement.srcObject=null,this.cacheVideoElement.remove()}catch(n){}this.cacheVideoElement=void 0}break;case"canplay":this.videoElementStatus=ii.CANPLAY;break;case"stalled":this.videoElementStatus=ii.STALLED;break;case"suspend":this.videoElementStatus=ii.SUSPEND;break;case"pause":this.videoElementStatus=ii.PAUSED,li()||bn()||je()&&this.autoplayFailed||!this.videoTrack||this.videoTrack.readyState!=="live"||(_.debug("[track-".concat(this.trackId,"] video element paused, auto resume")),this.videoElement.play());break;case"waiting":this.videoElementStatus=ii.WAITING;break;case"abort":this.videoElementStatus=ii.ABORT;break;case"ended":this.videoElementStatus=ii.ENDED;break;case"emptied":this.videoElementStatus=ii.EMPTIED;break;case"error":{const n=this.videoElement.error;n&&(this.videoElementStatus=ii.ERROR,_.error("[".concat(this.trackId,"] media error: ").concat(n.message," (").concat(n.code,")")));break}case"timeupdate":{const n=performance.now();if(this.timeUpdatedCount+=1,this.timeUpdatedCount<10)return void(this.lastTimeUpdatedTime=n);const r=n-this.lastTimeUpdatedTime,o=this.lastTimeUpdatedTime;if(this.lastTimeUpdatedTime=n,Sr.lastVisibleTime<Sr.lastHiddenTime||o<Sr.lastHiddenTime||o<Sr.lastVisibleTime)return;for(r>y("VIDEO_FREEZE_DURATION")&&(this.freezeTime+=r),this.playbackTime+=r;this.playbackTime>=6e3;){this.playbackTime-=6e3;const s=Math.min(6e3,this.freezeTime);this.freezeTimeCounterList.push(s),this.freezeTime=Math.max(0,this.freezeTime-6e3)}break}}}),D(this,"autoResumeAfterInterruptionOnIOS15_16",()=>{this.videoTrack&&this.videoTrack.readyState==="live"&&(_.debug("[track-".concat(this.trackId,"] video element paused, auto resume for ").concat(zy())),eI()?(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"),Mt.on(Ve.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Mt.on(Ve.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16)}getVideoElement(){return this.videoElement}getContainerElement(){var e;return(e=this.videoElement.parentElement)!==null&&e!==void 0?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 i=this.videoElement.play();i&&i.catch&&i.catch(r=>{e&&tA(e,"video",r.message,this.trackId),r.name==="NotAllowedError"?(_.warning("detected video element autoplay failed",r),this.autoplayFailed=!0,this.handleAutoPlayFailed()):_.warning("[".concat(this.trackId,"] play warning: "),r)});const n=vt();if((n.name==="Safari"&&Number(n.version)===15||na())&&i&&i.then){const r=()=>{this.config.mirror&&(this.videoElement.style.transform="rotateY(180deg)")};i.then(r).catch(r)}}getCurrentFrame(){const e=document.createElement("canvas");e.width=this.videoElement.videoWidth,e.height=this.videoElement.videoHeight;const i=e.getContext("2d");if(!i)return _.error("create canvas context failed!"),new ImageData(2,2);i.drawImage(this.videoElement,0,0,e.width,e.height);const n=i.getImageData(0,0,e.width,e.height);return e.remove(),n}getCurrentFrameToUint8Array(i){return C(this,arguments,function*(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;const r=document.createElement("canvas");r.width=this.videoElement.videoWidth,r.height=this.videoElement.videoHeight;const o=r.getContext("2d");return o?(o.drawImage(this.videoElement,0,0,r.width,r.height),new K((s,a)=>{r.toBlob(c=>C(this,null,function*(){if(r.remove(),c){const d=yield dA(c);s({buffer:d,width:r.width,height:r.height})}else a(new k(v.CONVERTING_VIDEO_FRAME_TO_BLOB_FAILED))}),e,n<0?.1:n>1?1:n)})):yield dm(e)})}destroy(){Mt.off(Ve.IOS_INTERRUPTION_END,this.autoResumeAfterInterruption),Mt.off(Ve.IOS_15_16_INTERRUPTION_END,this.autoResumeAfterInterruptionOnIOS15_16),this.videoElement.srcObject=null,this.resetVideoElement(),this.freezeTimeCounterList=[],this.videoState=fr.VideoStateStopped}initVideoElement(){if(this.videoElementStatus=ii.INIT,!this.videoElementCheckInterval&&(XA.forEach(o=>{this.videoElement.addEventListener(o,this.handleVideoEvents)}),this.videoElementCheckInterval=window.setInterval(()=>{(function(o){return o!==document.body&&document.body.contains(o)})(this.videoElement)||(this.videoElementStatus=ii.DESTROYED)},1e3),y("ENABLE_VIDEO_FRAME_CALLBACK"))){var e,i;let o;const s=()=>{document.visibilityState==="visible"&&(document.removeEventListener("visibilitychange",s),this.videoElementFreezeTimeout=window.setTimeout(a,y("VIDEO_FREEZE_DURATION")))},a=()=>{this.videoElementFreezeTimeout=void 0,this.videoState===fr.VideoStateDecoding&&(document.visibilityState==="visible"?this.videoState=fr.VideoStateFrozen:document.addEventListener("visibilitychange",s))},c=(d,l)=>{if(this.videoElementStatus===ii.PLAYING){if(o){const p=l.presentationTime-o.presentationTime,g=l.presentedFrames-o.presentedFrames;this._render_interframe_delays_sizes.push(g),this._render_interframe_delays.push(p);const m=VE(this._render_interframe_delays_sizes),f=m-this._render_interframe_delays_sizes[0];if(m>30&&f>5&&(this._render_interframe_delays_sizes.shift(),this._render_interframe_delays.shift()),this.videoState===fr.VideoStateStarting&&(this.videoState=fr.VideoStateDecoding),this.videoState===fr.VideoStateDecoding&&this.onVideoStateChanged&&(this.videoElementFreezeTimeout&&window.clearTimeout(this.videoElementFreezeTimeout),this.videoElementFreezeTimeout=window.setTimeout(a,y("VIDEO_FREEZE_DURATION"))),p<y("VIDEO_FREEZE_DURATION")&&this.videoState===fr.VideoStateFrozen&&(this.videoState=fr.VideoStateDecoding),p>y("VIDEO_FREEZE_DURATION")&&Sr.lastVisibleTime>=Sr.lastHiddenTime&&o.timestamp>Sr.lastVisibleTime&&o.timestamp>Sr.lastHiddenTime){const T=Math.min(66,zA(this._render_interframe_delays_sizes,this._render_interframe_delays)),R=Math.max(0,p-(g-1)*T);this.renderFreezeAccTime2+=R>T?R:0,this.renderFreezeAccTime+=p}}o=Qt(Qt({},l),{},{timestamp:d})}var u,h;y("ENABLE_VIDEO_FRAME_CALLBACK")&&((u=(h=this.videoElement).requestVideoFrameCallback)===null||u===void 0||u.call(h,c))};(e=(i=this.videoElement).requestVideoFrameCallback)===null||e===void 0||e.call(i,c)}this.videoElement.controls=!1,this.videoElement.setAttribute("playsinline",""),au()&&!y("HIDE_NO_POSTER")&&(this.videoElement.poster="noposter");const n=vt();n.name==="Safari"&&Number(n.version)===15||na()||!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,ne()&&this.videoElement.load()):(this.videoElement.srcObject=this.videoTrack?new MediaStream([this.videoTrack]):null,ne()&&this.videoElement.load());const r=this.videoElement.play();r!==void 0&&r.catch(o=>{_.debug("[".concat(this.trackId,"] playback interrupted"),o.toString())})}resetVideoElement(){XA.forEach(e=>{this.videoElement&&this.videoElement.removeEventListener(e,this.handleVideoEvents)}),this.videoElementCheckInterval&&(window.clearInterval(this.videoElementCheckInterval),this.videoElementCheckInterval=void 0),this.videoElementStatus=ii.NONE}handleAutoPlayFailed(){const e=i=>{i.preventDefault(),this.videoElement.play().then(()=>{_.debug("[".concat(this.trackId,"] Video element for trackId:").concat(this.trackId," autoplay resumed."))}).catch(n=>{_.error(n)}),this.autoplayFailed=!1,bc()?document.body.removeEventListener("click",e,!0):(document.body.removeEventListener("touchstart",e,!0),document.body.removeEventListener("mousedown",e,!0))};bc()?document.body.addEventListener("click",e,!0):(document.body.addEventListener("touchstart",e,!0),document.body.addEventListener("mousedown",e,!0)),$I()}}const XA=["play","playing","loadeddata","canplay","pause","stalled","suspend","waiting","abort","emptied","ended","timeupdate","error"];class vu extends lm{constructor(e){super(e),D(this,"container",void 0),D(this,"slot",void 0),this.slot=e.element,this.updateConfig(e)}updateConfig(e){this.config=e,this.trackId=e.trackId;const i=e.element;i!==this.slot&&(this.destroy(),this.slot=i),this.createElements()}updateVideoTrack(e){this.videoTrack!==e&&(this.videoTrack=e,this.createElements())}play(e){var i;(i=this.container)!==null&&i!==void 0&&i.contains(this.videoElement)&&super.play(e)}getCurrentFrame(){var e;return(e=this.container)!==null&&e!==void 0&&e.contains(this.videoElement)?super.getCurrentFrame():new ImageData(2,2)}getCurrentFrameToUint8Array(i){return C(this,arguments,function*(e){var n;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;return(n=this.container)!==null&&n!==void 0&&n.contains(this.videoElement)?yield Uf(vu.prototype,this,"getCurrentFrameToUint8Array").call(this,e,r):yield dm(e)})}destroy(){if(super.destroy(),this.videoElement.remove(),this.videoElement=document.createElement("video"),this.container){try{this.container.remove(),this.slot.removeChild(this.container)}catch(e){}this.container=void 0}}createElements(){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",y("KEEP_LAST_FRAME")&&this.isKeepLastFrame&&this.videoElement.paused&&this.resetVideoElement(),this.mountedVideoElement()):this.unmountedVideoElement(),this.slot.appendChild(this.container)}mountedVideoElement(){var e;!this.container||(e=this.container)!==null&&e!==void 0&&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((e=this.container)!==null&&e!==void 0&&e.contains(this.videoElement)){super.resetVideoElement();try{this.container&&this.container.removeChild(this.videoElement)}catch(i){}this.videoElement=document.createElement("video")}}resetVideoElement(){var e;(e=this.container)!==null&&e!==void 0&&e.contains(this.videoElement)&&(super.resetVideoElement(),this.cacheVideoElement=this.videoElement,this.videoElement=document.createElement("video"))}getContainerElement(){return this.container}}var JA,QA,ZA,$A,tb,eb,ib,nb,rb,ob,sb,ab,cb,db,lb,ub,hb,pb,_b,Eb,mb,fb,gb,Sb,Tb,Rb,Et,vb,Cb,yb,Ib,Ab,bb,wb,Ob,rn;let Yt=(JA=it({argsMap:(t,e,i)=>[t.getTrackId(),typeof e=="string"?e:e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),QA=le(),ZA=it({argsMap:t=>[t.getTrackId()]}),$A=sa("LocalVideoTrack","_enabledMutex"),tb=it({argsMap:(t,e)=>[t.getTrackId(),e]}),eb=le(),ib=sa("LocalVideoTrack","_enabledMutex"),nb=it({argsMap:(t,e)=>[t.getTrackId(),e]}),rb=le(),ob=it({argsMap:(t,e)=>[t.getTrackId(),e,t._saveEncodeBitrateRatio]}),sb=le(),ab=it({argsMap:(t,e)=>[t.getTrackId(),e]}),cb=le(),db=le(),lb=it({argsMap:(t,e,i)=>[t.getTrackId(),e,i]}),ub=le(),hb=le(),pb=le(),_b=le(),Eb=le(),mb=le(),fb=le(),gb=it({argsMap:(t,e)=>[t.getTrackId(),e.name]}),Sb=it({argsMap:t=>[t.getTrackId()]}),Tb=it({argsMap:t=>[t.getTrackId()]}),Rb=it({argsMap:(t,e,i)=>[t.getTrackId(),e.label,i]}),Et=class ZN extends Ea{get videoHeight(){if(je()){const{height:e}=this._mediaStreamTrack.getSettings();return this._videoHeight=e,this._videoHeight}return this._videoHeight}get videoWidth(){if(je()){const{width:e}=this._mediaStreamTrack.getSettings();return this._videoWidth=e,this._videoWidth}return this._videoWidth}get isPlaying(){return!(!this._player||this._player.videoElementStatus!==ii.PLAYING)}get processorDestination(){return this._processorDestination}get processorContext(){return this._processorContext}set processorContext(e){this._processorContext=e}get __className__(){return"LocalVideoTrack"}constructor(e,i,n,r,o,s){if(super(e,o),D(this,"trackMediaType",_a.VIDEO),D(this,"_player",void 0),D(this,"isUseScaleResolutionDownBy",!1),D(this,"_videoVisibleTimer",null),D(this,"_previousVideoVisibleStatus",void 0),D(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),D(this,"_encoderConfig",void 0),D(this,"_scalabilityMode",{numSpatialLayers:1,numTemporalLayers:1}),D(this,"_optimizationMode",void 0),D(this,"_saveEncodeBitrateRatio",1),D(this,"_videoHeight",void 0),D(this,"_videoWidth",void 0),D(this,"_forceBitrateLimit",void 0),D(this,"_enabled",!0),D(this,"_processorDestination",void 0),D(this,"_processorContext",void 0),je()){const{width:a,height:c}=e.getSettings();this._videoWidth=a,this._videoHeight=c}else this.updateMediaStreamTrackResolution();if(this._scalabilityMode=n,this._optimizationMode=r,this._hints=s||[],i&&this._hints.indexOf(Vt.CUSTOM_TRACK)!==-1?this._encoderConfig=te(i):this._encoderConfig=i,this._hints.indexOf(Vt.SCREEN_TRACK)===-1)this.updateBitrateFromProfile();else if(AE(It.CHROME,115)&&ou().indexOf("Windows")!==-1){const a=function(c,d){if("VideoFrame"in window&&"TransformStream"in window&&Ct().supportWebRTCInsertableStream){const l=new MediaStreamTrackProcessor(c),u=new MediaStreamTrackGenerator({kind:"video"});let h,p,g=Date.now();const m=()=>{f&&(clearInterval(f),f=void 0),h&&(h.close(),h=void 0),c.stop(),p=void 0,u.removeEventListener("ended",m)};let f=window.setInterval(()=>{if(p&&h&&Date.now()-g>1e3)try{u.readyState==="live"?p.enqueue(h.clone()):m()}catch(R){m()}},1e3);const T=new TransformStream({transform:(R,A)=>{u.readyState==="live"?(p=A,g=Date.now(),h===void 0?(h=R,A.enqueue(R.clone())):(A.enqueue(h),h=R)):R.close()}});return u.addEventListener("ended",m),l.readable.pipeThrough(T).pipeTo(u.writable),u}}(e);a&&(_.info("local screen video track begin to inject frame"),this._mediaStreamTrack=a)}i&&this._hints.indexOf(Vt.CUSTOM_TRACK)!==-1&&this.setEncoderConfiguration(i),this._processorContext=new iA(this.getTrackId(),"local"),this._processorDestination=new eA(this.processorContext),this.bindProcessorDestinationEvents()}play(e){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(typeof e=="string"){const r=document.getElementById(e);r?e=r:(_.warning("[".concat(this.getTrackId(),'] can not find "#').concat(e,'" element, use document.body')),e=document.body)}_.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(i));const n=Qt(Qt(Qt({},this._getDefaultPlayerConfig()),i),{},{trackId:this.getTrackId(),element:e});this._player?this._player.updateConfig(n):(e instanceof HTMLVideoElement?this._player=new lm(n):this._player=new vu(n),this._player.updateVideoTrack(this._mediaStreamTrack)),this._player.play(),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const r=this.getVideoElementVisibleStatus();this.safeEmit(ha.VIDEO_ELEMENT_VISIBLE_STATUS,r)}catch(r){}},y("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,_.debug("[".concat(this.getTrackId(),"] stop video playback")))}setEnabled(e,i){return C(this,null,function*(){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(_.info("[".concat(this.getTrackId(),"] start setEnabled"),e),!e){this._originMediaStreamTrack.enabled=!1;try{yield Bt(this,J.NEED_DISABLE_TRACK,this)}catch(n){throw _.error("[".concat(this.getTrackId(),"] setEnabled to false error"),n.toString()),n}return i||(this._enabled=!1),void _.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}this._originMediaStreamTrack.enabled=!0;try{yield Bt(this,J.NEED_ENABLE_TRACK,this)}catch(n){throw _.error("[".concat(this.getTrackId(),"] setEnabled to true error"),n.toString()),n}_.info("[".concat(this.getTrackId(),"] setEnabled to true success")),i||(this._enabled=!0)})}setMuted(e){return C(this,null,function*(){e!==this._muted&&(this.stateCheck("muted",e),this._muted=e,this._originMediaStreamTrack.enabled=!e,_.debug("[".concat(this.getTrackId(),"] start set muted: ").concat(e)),e?yield Bt(this,J.NEED_MUTE_TRACK,this):yield Bt(this,J.NEED_UNMUTE_TRACK,this))})}setSaveEncodeBitrateRatio(){return C(this,arguments,function*(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this._saveEncodeBitrateRatio;if(this._saveEncodeBitrateRatio!==1&&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),_.debug("[".concat(this.getTrackId(),"] set save encode bitrate ratio, ").concat(e)),this._saveEncodeBitrateRatio=1;try{yield Bt(this,J.NEED_UPDATE_VIDEO_ENCODER,this)}catch(i){return i.throw(_)}}})}setEncoderConfiguration(e,i){return C(this,null,function*(){if(!this._enabled)throw new k(v.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");if(e=Nn(e),y("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 n=Ru({encoderConfig:e});(je()||li()||bn())&&(n.deviceId=void 0),_.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(n));try{yield this._originMediaStreamTrack.applyConstraints(n),this.updateMediaStreamTrackResolution()}catch(r){const o=new k(v.UNEXPECTED_ERROR,r.toString());throw _.error("[".concat(this.getTrackId(),"] applyConstraints error"),o.toString()),o}}this._encoderConfig=e,this._hints.indexOf(Vt.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{yield Bt(this,J.NEED_UPDATE_VIDEO_ENCODER,this)}catch(n){return n.throw(_)}})}getStats(){return _o(()=>{_.warning("[deprecated] LocalVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getLocalVideoStats instead")},"localVideoTrackGetStatsWarning"),zi(this,J.GET_STATS)||Qt({},im)}setBeautyEffect(e){return C(this,null,function*(){_.error("LocalVideoTrack.setBeautyEffect was deprecated, please migrate to agora-extension-beauty-effect")})}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}getCurrentFrameImage(i){return C(this,arguments,function*(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;return this._player?this._player.getCurrentFrameToUint8Array(e,n):yield dm(e)})}setBitrateLimit(e){return C(this,null,function*(){_.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))})}setOptimizationMode(e){return C(this,null,function*(){if(e!=="motion"&&e!=="detail"&&e!=="balanced")return void _.error(v.INVALID_PARAMS,"optimization mode must be motion, detail or balanced");const i=this._optimizationMode;try{this._optimizationMode=e,yield Bt(this,J.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this)}catch(n){throw this._optimizationMode=i,_.error("[".concat(this.getTrackId(),"] set optimization mode failed"),n.toString()),n}_.info("[".concat(this.getTrackId(),"] set optimization mode success (").concat(e,")"))})}setScalabiltyMode(e){if(e.numSpatialLayers===1&&e.numTemporalLayers!==1)return _.error(v.INVALID_PARAMS,"scalability mode currently not supported, no SVC."),void(this._scalabilityMode={numSpatialLayers:1,numTemporalLayers:1});this._scalabilityMode=e,_.info("[".concat(this.getTrackId(),"] set scalability mode success (").concat(e,")"))}updateMediaStreamTrackResolution(){oA(this._originMediaStreamTrack).then(e=>{let[i,n]=e;this._videoHeight=n,this._videoWidth=i}).catch(lu)}_updatePlayerSource(){this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}_getDefaultPlayerConfig(){return{fit:"contain"}}setSenderConfiguration(e){return C(this,null,function*(){if(!this._enabled)throw new k(v.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");_.debug("[".concat(this.getTrackId(),"] setSenderConfiguration applyConstraints"),JSON.stringify(e)),e=Nn(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,this._hints.indexOf(Vt.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{yield Bt(this,J.NEED_UPDATE_VIDEO_ENCODER,this)}catch(i){return i.throw(_)}})}updateBitrateFromProfile(){if(!this._encoderConfig)return;const{width:e,height:i,frameRate:n}=this.getMediaStreamTrackSettings();if(!e||!i||!n)return;const{bitrateMax:r,bitrateMin:o}=this._encoderConfig;if(o==null||r==null){const{max:s,min:a}=function(c,d,l,u,h){const p=y("BITRATE_ADAPTER_TYPE");if(p==="DEFAULT_BITRATE")return{min:u,max:h};if(h===void 0){const g=Math.floor(200*Math.pow(l/15,.6)*Math.pow(c*d/640/360,.75));h=p==="STANDARD_BITRATE"?4*g:2*g,u=u!=null?u:g}else u=u!=null?u:Math.floor(h/10);return{min:u,max:h}}(e,i,n,o,r);if(this._encoderConfig.bitrateMin=a,this._encoderConfig.bitrateMax=s,y("VIDEO_STANDARD_BITRATE_VERSION")&&o==null&&r==null){const[c,d]=function(l,u,h){const p=4*Math.floor(2e5*Math.pow(h/15,.6)*Math.pow(l*u/230400,.75)),g=l*u,m=new Map([[19200,.9],[230400,.85],[518400,.75],[921600,.7],[2073600,.6],[3686400,.5]]),f=new Map([[230400,.95],[518400,.9],[921600,.85],[2073600,.8]]);let T=Ui(m).call(m).next().value,R=1;if(m.has(g))T=m.get(g);else{var A;const H=jo(A=Array.from(m.entries())).call(A,(lt,rt)=>{let[Kt]=lt,[Ft]=rt;return Kt-Ft}),ht=H.find(lt=>{let[rt]=lt;return rt>g});if(ht){const lt=H.indexOf(ht);if(lt>0){const rt=H[lt-1],Kt=(g-rt[0])/(ht[0]-rt[0]);T=rt[1]+Kt*(ht[1]-rt[1])}else T=ht[1]}else T=H[H.length-1][1]}if(f.has(g))R=f.get(g);else{var N;const H=jo(N=Array.from(f.entries())).call(N,(lt,rt)=>{let[Kt]=lt,[Ft]=rt;return Kt-Ft}),ht=H.find(lt=>{let[rt]=lt;return rt>g});if(ht){const lt=H.indexOf(ht);if(lt>0){const rt=H[lt-1],Kt=(g-rt[0])/(ht[0]-rt[0]);R=rt[1]+Kt*(ht[1]-rt[1])}else R=ht[1]}else R=H[H.length-1][1]}const O=y("VIDEO_NEW_BITRATE_RATIO");O&&O>0&&(T=O/100);const w=Math.floor(p*T),L=Math.floor(65e4*Math.pow(l*u/230400,.5)*Math.pow(h/15,.69));let M=w;const j=y("VIDEO_STANDARD_BITRATE_VERSION");return j&&j>0&&(j===1?M=p:j===2?M=w:j===3&&(M=L)),[Math.floor(M/1e3),R]}(e,i,n);this._encoderConfig.bitrateMax=c,this._encoderConfig.bitrateMin=a?Math.min(a,c):c,this._saveEncodeBitrateRatio=d,_.debug("[".concat(this.getTrackId(),"] update new bitrate from profile, [w: ").concat(e,", h: ").concat(i,", fps: ").concat(n,"] => [brMax: ").concat(this._encoderConfig.bitrateMax,", brMin: ").concat(this._encoderConfig.bitrateMin,", save_bitrate_ratio: ").concat(this._saveEncodeBitrateRatio,"]"))}else _.debug("[".concat(this.getTrackId(),"] update bitrate from profile, [w: ").concat(e,", h: ").concat(i,", fps: ").concat(n,"] => [brMax: ").concat(s,", brMin: ").concat(a,"]")),this._saveEncodeBitrateRatio=1}}getVideoElementVisibleStatus(){try{var e,i;const n=this==null||(e=this._player)===null||e===void 0?void 0:e.getContainerElement(),r={track:this,element:this==null||(i=this._player)===null||i===void 0?void 0:i.getVideoElement(),slot:n==null?void 0:n.parentElement},{element:o,slot:s}=r;if(this.isPlaying&&o instanceof HTMLVideoElement&&s instanceof HTMLElement){const a=sI.checkOneElementVisible(o),c=Object.assign({},a);if(c.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=c.visible;const d=Z.reportApiInvoke(null,{tag:oe.TRACER,name:_e.LOCAL_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});c.visible?d.onSuccess("Video is visible"):d.onSuccess("Invisible because of ".concat(c.reason))}return c}return}catch(n){throw new k(v.GET_VIDEO_ELEMENT_VISIBLE_ERROR,n.message)}}renewMediaStreamTrack(e){return C(this,null,function*(){})}pipe(e){if(this.processor===e)return e;if(e._source)throw new k(v.INVALID_OPERATION,"Processor ".concat(e.name," already piped, please call unpipe beforehand."));return this.unpipe(),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,e.reset()}close(){super.close(),this.unbindProcessorDestinationEvents(),this.unbindProcessorContextEvents(),this.unpipe(),this.processorDestination._source&&this.processorDestination._source.unpipe()}clone(e){let i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],n=this._encoderConfig;e&&(n=Qt(Qt({},n),Nn(e))),n=Jo(n);const r=Gt(8,"track-video-cloned-"),o=new ZN(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,n,Jo(this._scalabilityMode),this._optimizationMode,r,Jo(this._hints));return e&&n&&o.setEncoderConfiguration(n),_.debug("clone video track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(i)),o}replaceTrack(e,i){return C(this,null,function*(){if(!(e instanceof MediaStreamTrack))throw new k(v.INVALID_PARAMS,"track should be an instance of MediaStreamTrack");if(e.kind!=="video")throw new k(v.INVALID_PARAMS,"track should be a video MediaStreamTrack");yield this._updateOriginMediaStreamTrack(e,i,!0),this.updateMediaStreamTrackResolution()})}sendSeiData(e){if(_o(()=>{Z.reportApiInvoke(null,{name:_e.LOCAL_VIDEO_SEND_SEI_DATA,options:[],tag:oe.TRACER}).onSuccess("")},this._mediaStreamTrack.id||this.getTrackId()),!y("ENABLE_VIDEO_SEI")||!y("ENABLE_ENCODED_TRANSFORM"))return void _.warning('To send/receive SEI, please call AgoraRTC.setParameter("ENABLE_VIDEO_SEI", true) before instantiate IAgoraRtcClient');if(e instanceof Uint8Array==0)return new k(v.INVALID_PARAMS,"Invalid argument type, ILocalVideoTrack.sendSeiData() only accept Uint8Array argument.").throw();const i=this.getRTCRtpTransceiver();if(!i)return void _.warning("Video track is not published, SEI can not be send");const n=i.sender.getParameters();if(n.codecs.length===0)return;const r=n.codecs[0].mimeType.toLocaleLowerCase();r==="video/h264"?this.safeEmit("sei-to-send",e):_.warning("SEI is not supported by ".concat(r))}bindProcessorDestinationEvents(){this.processorDestination.on(ui.ON_TRACK,e=>C(this,null,function*(){e?e!==this._mediaStreamTrack&&(this._mediaStreamTrack=e,this._updatePlayerSource(),yield Bt(this,J.NEED_REPLACE_TRACK,this)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource(),yield Bt(this,J.NEED_REPLACE_TRACK,this))}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(ui.ON_TRACK)}unbindProcessorContextEvents(){this.processorContext.removeAllListeners(Zi.REQUEST_UPDATE_CONSTRAINTS),this.processorContext.removeAllListeners(Zi.REQUEST_CONSTRAINTS)}},gt(Et.prototype,"play",[JA,QA],Object.getOwnPropertyDescriptor(Et.prototype,"play"),Et.prototype),gt(Et.prototype,"stop",[ZA],Object.getOwnPropertyDescriptor(Et.prototype,"stop"),Et.prototype),gt(Et.prototype,"setEnabled",[$A,tb,eb],Object.getOwnPropertyDescriptor(Et.prototype,"setEnabled"),Et.prototype),gt(Et.prototype,"setMuted",[ib,nb,rb],Object.getOwnPropertyDescriptor(Et.prototype,"setMuted"),Et.prototype),gt(Et.prototype,"setSaveEncodeBitrateRatio",[ob,sb],Object.getOwnPropertyDescriptor(Et.prototype,"setSaveEncodeBitrateRatio"),Et.prototype),gt(Et.prototype,"setEncoderConfiguration",[ab,cb],Object.getOwnPropertyDescriptor(Et.prototype,"setEncoderConfiguration"),Et.prototype),gt(Et.prototype,"getStats",[db],Object.getOwnPropertyDescriptor(Et.prototype,"getStats"),Et.prototype),gt(Et.prototype,"setBeautyEffect",[lb,ub],Object.getOwnPropertyDescriptor(Et.prototype,"setBeautyEffect"),Et.prototype),gt(Et.prototype,"getCurrentFrameData",[hb],Object.getOwnPropertyDescriptor(Et.prototype,"getCurrentFrameData"),Et.prototype),gt(Et.prototype,"getCurrentFrameImage",[pb],Object.getOwnPropertyDescriptor(Et.prototype,"getCurrentFrameImage"),Et.prototype),gt(Et.prototype,"setBitrateLimit",[_b],Object.getOwnPropertyDescriptor(Et.prototype,"setBitrateLimit"),Et.prototype),gt(Et.prototype,"setOptimizationMode",[Eb],Object.getOwnPropertyDescriptor(Et.prototype,"setOptimizationMode"),Et.prototype),gt(Et.prototype,"setScalabiltyMode",[mb],Object.getOwnPropertyDescriptor(Et.prototype,"setScalabiltyMode"),Et.prototype),gt(Et.prototype,"updateMediaStreamTrackResolution",[fb],Object.getOwnPropertyDescriptor(Et.prototype,"updateMediaStreamTrackResolution"),Et.prototype),gt(Et.prototype,"pipe",[gb],Object.getOwnPropertyDescriptor(Et.prototype,"pipe"),Et.prototype),gt(Et.prototype,"unpipe",[Sb],Object.getOwnPropertyDescriptor(Et.prototype,"unpipe"),Et.prototype),gt(Et.prototype,"close",[Tb],Object.getOwnPropertyDescriptor(Et.prototype,"close"),Et.prototype),gt(Et.prototype,"replaceTrack",[Rb],Object.getOwnPropertyDescriptor(Et.prototype,"replaceTrack"),Et.prototype),Et),um=(vb=it({argsMap:(t,e)=>[t.getTrackId(),e]}),Cb=le(),yb=sa("CameraVideoTrack","_enabledMutex"),Ib=it({argsMap:(t,e)=>[t.getTrackId(),e]}),Ab=le(),bb=it({argsMap:(t,e)=>[t.getTrackId(),e]}),wb=le(),Ob=it({argsMap:t=>[t.getTrackId()]}),rn=class $N extends Yt{get __className__(){return"CameraVideoTrack"}constructor(e,i,n,r,o,s){super(e,Nn(i.encoderConfig),r,o,s),D(this,"_config",void 0),D(this,"_originalConstraints",void 0),D(this,"_constraints",void 0),D(this,"_enabled",!0),D(this,"_deviceName","default"),D(this,"tryResumeVideoForIOS15_16WeChat",()=>C(this,null,function*(){(na()||OE())&&!function(){const a=vt();if(a.os!==we.IOS||!a.osVersion)return!1;const c=a.osVersion.split(".");return Number(c[0])===15&&Number(c[1])>=2}()&&iI()&&this._enabled&&!this._isClosed&&(_.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS 15 device on WeChat.")),yield this.renewMediaStreamTrack())})),this._config=i,this._originalConstraints=n,this._constraints=n,this._deviceName=e.label,this._encoderConfig=Nn(this._config.encoderConfig),Mt.on(Ve.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Mt.on(Ve.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),this.bindProcessorContextEvents()}setDevice(e){return C(this,null,function*(){return typeof e=="string"?this._setDeviceById(e):e.deviceId?this._setDeviceById(e.deviceId):e.facingMode?this._setDeviceByFacingModel(e.facingMode):void 0})}_setDeviceById(e){return C(this,null,function*(){if(_.info("[".concat(this.getTrackId(),"] set device to ").concat(e)),this._enabled)try{const i=yield en.getDeviceById(e),n={};n.video=Qt({},this._constraints),n.video.deviceId={exact:e},n.video.facingMode=void 0,this._originMediaStreamTrack.stop();let r=null;try{r=yield tn(n,this.getTrackId())}catch(o){throw _.error("[".concat(this.getTrackId(),"] setDevice failed"),o.toString()),r=yield tn({video:this._constraints},this.getTrackId()),yield this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),o}yield this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution(),this._deviceName=i.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(i){throw _.error("[".concat(this.getTrackId(),"] setDevice error"),i.toString()),i}else try{const i=yield en.getDeviceById(e);this._deviceName=i.label,this._config.cameraId=e,this._constraints.deviceId={exact:e}}catch(i){throw _.error("[".concat(this.getTrackId(),"] setDevice error"),i.toString()),i}_.info("[".concat(this.getTrackId(),"] setDevice success"))})}_setDeviceByFacingModel(e){return C(this,null,function*(){_.info("[".concat(this.getTrackId(),"] set facingMode ").concat(e));const i={video:Qt(Qt({},this._constraints),{},{deviceId:void 0,facingMode:{exact:e}})};if(this._enabled){this._originMediaStreamTrack.stop();let n=null;try{n=yield tn(i,this.getTrackId())}catch(r){throw _.error("[".concat(this.getTrackId(),"] setDeviceByFacingModel failed"),r.toString()),n=yield tn({video:this._constraints},this.getTrackId()),yield this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),r}yield this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1),this.updateMediaStreamTrackResolution()}this._deviceName="",this._config.facingMode=e,this._config.cameraId=void 0,this._constraints=Qt({},i.video),_.info("[".concat(this.getTrackId(),"] setDeviceByFacingModel success"))})}setEnabled(e,i){return C(this,null,function*(){if(!i){if(e===this._enabled)return;this.stateCheck("enabled",e)}if(_.info("[".concat(this.getTrackId(),"] start setEnabled"),e),e){try{if(this.isExternalTrack)this._originMediaStreamTrack.enabled=!0;else{const n=yield tn({video:this._constraints},this.getTrackId());yield this._updateOriginMediaStreamTrack(n.getVideoTracks()[0],!1)}yield Bt(this,J.NEED_ENABLE_TRACK,this)}catch(n){throw _.error("[".concat(this.getTrackId(),"] setEnabled true error"),n.toString()),n}this.updateMediaStreamTrackResolution(),_.info("[".concat(this.getTrackId(),"] setEnabled to true success")),i||(this._enabled=!0)}else{this.isExternalTrack?this._originMediaStreamTrack.enabled=!1:(this._originMediaStreamTrack.onended=null,this._originMediaStreamTrack.stop()),i||(this._enabled=!1);try{yield Bt(this,J.NEED_DISABLE_TRACK,this)}catch(n){throw _.error("[".concat(this.getTrackId(),"] setEnabled to false error"),n.toString()),n}_.info("[".concat(this.getTrackId(),"] setEnabled to false success"))}})}setEncoderConfiguration(e,i){return C(this,null,function*(){if(!this._enabled)throw new k(v.TRACK_IS_DISABLED,"can not set encoder configuration when track is disabled");e=Nn(e),y("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=te(this._config);n.encoderConfig=e;const r=Ru(n);(je()||li()||bn())&&(r.deviceId=void 0),_.debug("[".concat(this.getTrackId(),"] setEncoderConfiguration applyConstraints"),JSON.stringify(e),JSON.stringify(r));try{yield this._originMediaStreamTrack.applyConstraints(r),this.updateMediaStreamTrackResolution()}catch(o){const s=new k(v.UNEXPECTED_ERROR,o.toString());throw _.error("[".concat(this.getTrackId(),"] applyConstraints error"),s.toString()),s}this._config=n,this._constraints=r,this._originalConstraints=r,this._encoderConfig=e,this._hints.indexOf(Vt.SCREEN_TRACK)===-1&&this.updateBitrateFromProfile();try{yield Bt(this,J.NEED_UPDATE_VIDEO_ENCODER,this)}catch(o){return o.throw(_)}})}_getDefaultPlayerConfig(){return{mirror:!0,fit:"cover"}}onTrackEnded(){if((li()||bn())&&this._enabled&&!this._isClosed&&Mt.duringInterruption){const e=()=>C(this,null,function*(){Mt.off(Ve.IOS_INTERRUPTION_END,e),this._enabled&&!this._isClosed&&(_.debug("[".concat(this.getTrackId(),"] try capture camera media device for interrupted iOS device.")),yield this.setEnabled(!1),yield this.setEnabled(!0))});Mt.on(Ve.IOS_INTERRUPTION_END,e)}else _.debug("[".concat(this.getTrackId(),"] track ended")),this.safeEmit(ha.TRACK_ENDED)}renewMediaStreamTrack(e){return C(this,null,function*(){const i=e||this._constraints,n=en.searchDeviceIdByName(this._deviceName);if(n&&!i.deviceId&&(i.deviceId={exact:n}),this._enabled){const r=yield tn({video:i},this.getTrackId());this._constraints=i,yield this._updateOriginMediaStreamTrack(r.getVideoTracks()[0],!0),this.updateMediaStreamTrackResolution()}})}close(){super.close(),Mt.off(Ve.IOS_15_16_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat),Mt.off(Ve.IOS_INTERRUPTION_END,this.tryResumeVideoForIOS15_16WeChat)}clone(e){let i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],n=this._encoderConfig;e&&(n=Qt(Qt({},n),Nn(e))),n=Jo(n);const r=Gt(8,"track-cam-cloned-"),o=new $N(i?this._mediaStreamTrack.clone():this._mediaStreamTrack,Jo(Qt(Qt({},this._config),{},{encoderConfig:n})),Jo(this._constraints),Jo(this._scalabilityMode),this._optimizationMode,r);return e&&n&&o.setEncoderConfiguration(n),_.debug("clone track from ".concat(this.getTrackId()," to ").concat(r,", clone ").concat(i)),o}bindProcessorContextEvents(){this.processorContext.on(Zi.REQUEST_UPDATE_CONSTRAINTS,(e,i,n)=>C(this,null,function*(){try{const r=Object.assign({},this._originalConstraints,...e);yield this.renewMediaStreamTrack(r),i()}catch(r){n(r)}})),this.processorContext.on(Zi.REQUEST_CONSTRAINTS,e=>C(this,null,function*(){e(this._originMediaStreamTrack.getSettings())}))}},gt(rn.prototype,"setDevice",[vb,Cb],Object.getOwnPropertyDescriptor(rn.prototype,"setDevice"),rn.prototype),gt(rn.prototype,"setEnabled",[yb,Ib,Ab],Object.getOwnPropertyDescriptor(rn.prototype,"setEnabled"),rn.prototype),gt(rn.prototype,"setEncoderConfiguration",[bb,wb],Object.getOwnPropertyDescriptor(rn.prototype,"setEncoderConfiguration"),rn.prototype),gt(rn.prototype,"close",[Ob],Object.getOwnPropertyDescriptor(rn.prototype,"close"),rn.prototype),rn);function hm(t,e,i,n){i.optimizationMode&&(n&&n.width&&n.height?(i.encoderConfig=Qt(Qt({},n),{},{bitrateMin:n.bitrateMin,bitrateMax:n.bitrateMax}),i.optimizationMode!=="motion"&&i.optimizationMode!=="detail"||(e.contentHint=i.optimizationMode,e.contentHint===i.optimizationMode?_.debug("[".concat(t,"] set content hint to"),i.optimizationMode):_.debug("[".concat(t,"] set content hint failed")))):_.warning("[".concat(t,"] can not apply optimization mode bitrate config, no encoderConfig")))}var Nb,Db,Pb,Lb,un,kb,Mb,Ub,xb,Vb,Fb,ri;class Bb extends HI{getUserId(){return this._userId}constructor(e,i,n,r){super(e,"track-".concat(e.kind,"-").concat(i,"-").concat(r.clientId,"_").concat(Gt(5,""))),D(this,"_userId",void 0),D(this,"_uintId",void 0),D(this,"_isDestroyed",!1),D(this,"store",void 0),D(this,"processor",void 0),D(this,"processorContext",void 0),this._userId=i,this._uintId=n,this.store=r}_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,_.info("[".concat(this.getTrackId(),"] is destroyed")),this.stop(),super.close()}getProcessorStats(){return this.processorContext.gatherStats()}getProcessorUsage(){return this.processorContext.gatherUsage()}}let ga=(Nb=it({argsMap:(t,e,i)=>[t.getTrackId(),typeof e=="string"?e:e instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement",i]}),Db=it({argsMap:t=>[t.getTrackId()]}),Pb=it({argsMap:(t,e)=>[t.getTrackId(),e.name]}),Lb=it({argsMap:t=>[t.getTrackId()]}),gt((un=class extends Bb{get isPlaying(){return!(!this._player||this._player.videoElementStatus!==ii.PLAYING)}get __className__(){return"RemoteVideoTrack"}constructor(t,e,i,n){super(t,e,i,n),D(this,"_videoVisibleTimer",null),D(this,"_previousVideoVisibleStatus",void 0),D(this,"_clearPreviousVideoVisibleStatus",()=>this._previousVideoVisibleStatus=void 0),D(this,"trackMediaType",_a.VIDEO),D(this,"_videoWidth",void 0),D(this,"_videoHeight",void 0),D(this,"_player",void 0),D(this,"processorDestination",void 0),D(this,"processorContext",void 0),this.updateMediaStreamTrackResolution(),this.processorContext=new iA(this.getTrackId(),"remote"),this.processorDestination=new eA(this.processorContext),this.bindProcessorDestinationEvents()}getStats(){return _o(()=>{_.warning("[deprecated] RemoteVideoTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteVideoStats instead")},"remoteVideoTrackGetStatsWarning"),zi(this,J.GET_STATS)||Qt({},GI)}play(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(typeof t=="string"){const n=document.getElementById(t);n?t=n:(_.warning("[".concat(this.getTrackId(),'] can not find "#').concat(t,'" element, use document.body')),t=document.body)}_.debug("[".concat(this.getTrackId(),"] start video playback in ").concat(t instanceof HTMLVideoElement?"HTMLVideoElement":"HTMLElement"),JSON.stringify(e));const i=Qt(Qt({fit:"cover"},e),{},{trackId:this.getTrackId(),element:t});this._player?this._player.updateConfig(i):(t instanceof HTMLVideoElement?this._player=new lm(i):this._player=new vu(i),this._player.updateVideoTrack(this._mediaStreamTrack),this._player.onFirstVideoFrameDecoded=()=>{this.store.subscribe(this.getUserId(),"video",void 0,void 0,Date.now()),this.safeEmit(pa.FIRST_FRAME_DECODED)},this._player.onVideoStateChanged=n=>{this.safeEmit(pa.VIDEO_STATE_CHANGED,n)}),this._player.play(this.store.sessionId||void 0),this._videoVisibleTimer&&window.clearInterval(this._videoVisibleTimer),this._clearPreviousVideoVisibleStatus(),this._videoVisibleTimer=window.setInterval(()=>{try{const n=this.getVideoElementVisibleStatus();this.safeEmit(pa.VIDEO_ELEMENT_VISIBLE_STATUS,n)}catch(n){}},y("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,_.debug("[".concat(this.getTrackId(),"] stop video playback")))}getCurrentFrameData(){return this._player?this._player.getCurrentFrame():new ImageData(2,2)}updateMediaStreamTrackResolution(){oA(this._originMediaStreamTrack).then(t=>{let[e,i]=t;this._videoHeight=i,this._videoWidth=e}).catch(lu)}_updatePlayerSource(){_.debug("[".concat(this.getTrackId(),"] update player source track")),this._player&&this._player.updateVideoTrack(this._mediaStreamTrack)}getVideoElementVisibleStatus(){try{var t,e;const i=this==null||(t=this._player)===null||t===void 0?void 0:t.getContainerElement(),n={track:this,element:this==null||(e=this._player)===null||e===void 0?void 0:e.getVideoElement(),slot:i==null?void 0:i.parentElement},{element:r,slot:o}=n;if(this.isPlaying&&r instanceof HTMLVideoElement&&o instanceof HTMLElement){const s=sI.checkOneElementVisible(r),a=Object.assign({},s);if(a.visible!==this._previousVideoVisibleStatus){this._previousVideoVisibleStatus=a.visible;const c=Z.reportApiInvoke(null,{tag:oe.TRACER,name:_e.REMOTE_VIDEO_TRACK_GET_VIDEO_VISIBLE,options:[this.getTrackId()]});a.visible?c.onSuccess("Video is visible"):c.onSuccess("Invisible because of ".concat(a.reason))}return a}return}catch(i){throw new k(v.GET_VIDEO_ELEMENT_VISIBLE_ERROR,i.message)}}pipe(t){if(this.processor===t)return t;if(t._source)throw new k(v.INVALID_OPERATION,"Processor ".concat(t.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=t,this.processor._source=this,t.updateInput({track:this._originMediaStreamTrack,context:this.processorContext}),t}unpipe(){if(!this.processor)return;const t=this.processor;this.processor._source=void 0,this.processor=void 0,t.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(ui.ON_TRACK,t=>C(this,null,function*(){t?t!==this._mediaStreamTrack&&(this._mediaStreamTrack=t,this._updatePlayerSource()):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())}))}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(ui.ON_TRACK)}_destroy(){super._destroy(),this.unbindProcessorDestinationEvents()}_onSei(t){this.emit(ts.SEI_RECEIVED,t)}}).prototype,"play",[Nb],Object.getOwnPropertyDescriptor(un.prototype,"play"),un.prototype),gt(un.prototype,"stop",[Db],Object.getOwnPropertyDescriptor(un.prototype,"stop"),un.prototype),gt(un.prototype,"pipe",[Pb],Object.getOwnPropertyDescriptor(un.prototype,"pipe"),un.prototype),gt(un.prototype,"unpipe",[Lb],Object.getOwnPropertyDescriptor(un.prototype,"unpipe"),un.prototype),un),Sa=(kb=it({argsMap:(t,e)=>[t.getTrackId(),e],throttleTime:300}),Mb=it({argsMap:(t,e)=>[t.getTrackId(),e]}),Ub=it({argsMap:t=>[t.getTrackId()]}),xb=it({argsMap:t=>[t.getTrackId()]}),Vb=it({argsMap:(t,e)=>[t.getTrackId(),e.name]}),Fb=it({argsMap:t=>[t.getTrackId()]}),gt((ri=class extends Bb{get isPlaying(){return this._useAudioElement?Ri.isPlaying(this.getTrackId()):this._source.isPlayed}get __className__(){return"RemoteAudioTrack"}constructor(t,e,i,n){super(t,e,i,n),D(this,"trackMediaType",_a.AUDIO),D(this,"_source",void 0),D(this,"_useAudioElement",!0),D(this,"_volume",100),D(this,"processorContext",void 0),D(this,"processorDestination",void 0),D(this,"_played",!1),D(this,"_bypassWebAudio",!1),y("DISABLE_WEBAUDIO")?(this._source=new cm,this._bypassWebAudio=!0,this._useAudioElement=!0):(this._source=new zI(t,!0),y("REMOTE_AUDIO_TRACK_USES_WEB_AUDIO")&&(this._useAudioElement=!1)),this._source.once(Qi.RECEIVE_TRACK_BUFFER,()=>{this.safeEmit(pa.FIRST_FRAME_DECODED)}),this.processorContext=new rA(this._source.context,this.getTrackId(),"remote"),this.processorDestination=new nA(this.processorContext),this.bindProcessorDestinationEvents(),this._source.on(Qi.UPDATE_SOURCE,()=>{this.processor&&this.processor.updateInput({node:this._source.processSourceNode,context:this.processorContext})})}setAudioFrameCallback(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:4096;if(!t)return this._source.removeAllListeners(Qi.ON_AUDIO_BUFFER),void this._source.stopGetAudioBuffer();this._source.startGetAudioBuffer(e),this._source.removeAllListeners(Qi.ON_AUDIO_BUFFER),this._source.on(Qi.ON_AUDIO_BUFFER,i=>t(i))}setVolume(t){this._volume=t,this._useAudioElement?Ri.setVolume(this.getTrackId(),t):this._source.setVolume(t/100)}setPlaybackDevice(t){return C(this,null,function*(){if(!this._useAudioElement||!VI())throw new k(v.NOT_SUPPORTED,"your browser does not support setting the audio output device");yield Ri.setSinkID(this.getTrackId(),t)})}getVolumeLevel(){return this._source.getAccurateVolumeLevel()}getStats(){return _o(()=>{_.warning("[deprecated] RemoteAudioTrack.getStats will be removed in the future, use AgoraRTCClient.getRemoteAudioStats instead")},"remoteAudioTrackGetStatsWarning"),zi(this,J.GET_STATS)||Qt({},jI)}play(){_.debug("[".concat(this.getTrackId(),"] start audio playback")),this._played=!0,this._useAudioElement?(_.debug("[".concat(this.getTrackId(),"] use audio element to play")),Ri.play(this._mediaStreamTrack,this.getTrackId(),this._volume,this.store.sessionId||void 0)):this._source.play()}stop(){_.debug("[".concat(this.getTrackId(),"] stop audio playback")),this._played=!1,this._useAudioElement?Ri.stop(this.getTrackId()):this._source.stop()}_destroy(){super._destroy(),this._played=!1,this.unbindProcessorDestinationEvents(),this._source.destroy()}_isFreeze(){return this._source.isFreeze}_updatePlayerSource(){let t=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];_.debug("[".concat(this.getTrackId(),"] update player source track")),t&&this._source.updateTrack(this._mediaStreamTrack),this._useAudioElement&&Ri.updateTrack(this.getTrackId(),this._mediaStreamTrack)}pipe(t){if(this._bypassWebAudio)throw new k(v.NOT_SUPPORTED,"can not pipe extension when WebAudio disabled");if(this.processor===t)return t;if(t._source)throw new k(v.INVALID_OPERATION,"Processor ".concat(t.name," already piped, please call unpipe beforehand."));return this.unpipe(),this.processor=t,this.processor._source=this,t.updateInput({track:this._originMediaStreamTrack,node:this._source.processSourceNode,context:this.processorContext}),t}unpipe(){var t;if(this._bypassWebAudio)throw new k(v.NOT_SUPPORTED,"can not unpipe extension when WebAudio disabled");if(!this.processor)return;const e=this.processor;(t=this._source.processSourceNode)===null||t===void 0||t.disconnect(),this.processor._source=!1,this.processor=void 0,e.reset()}bindProcessorDestinationEvents(){this.processorDestination.on(ui.ON_TRACK,t=>C(this,null,function*(){t?t!==this._mediaStreamTrack&&(this._mediaStreamTrack=t,this._updatePlayerSource(!1),this._source.processedNode=this._source.createMediaStreamSourceNode(t)):this._mediaStreamTrack!==this._originMediaStreamTrack&&(this._mediaStreamTrack=this._originMediaStreamTrack,this._updatePlayerSource())})),this.processorDestination.on(ui.ON_NODE,t=>{this._source.processedNode=t;const e=!t;this._useAudioElement!==e&&(this._played?(this.stop(),this._useAudioElement=e,this.play()):this._useAudioElement=e)})}unbindProcessorDestinationEvents(){this.processorDestination.removeAllListeners(ui.ON_TRACK),this.processorDestination.removeAllListeners(ui.ON_NODE)}}).prototype,"setVolume",[kb],Object.getOwnPropertyDescriptor(ri.prototype,"setVolume"),ri.prototype),gt(ri.prototype,"setPlaybackDevice",[Mb],Object.getOwnPropertyDescriptor(ri.prototype,"setPlaybackDevice"),ri.prototype),gt(ri.prototype,"play",[Ub],Object.getOwnPropertyDescriptor(ri.prototype,"play"),ri.prototype),gt(ri.prototype,"stop",[xb],Object.getOwnPropertyDescriptor(ri.prototype,"stop"),ri.prototype),gt(ri.prototype,"pipe",[Vb],Object.getOwnPropertyDescriptor(ri.prototype,"pipe"),ri.prototype),gt(ri.prototype,"unpipe",[Fb],Object.getOwnPropertyDescriptor(ri.prototype,"unpipe"),ri.prototype),ri);const Sr=new class extends $t{get visibility(){return document.visibilityState}get lastHiddenTime(){return this._lastHiddenTime}get lastVisibleTime(){return this._lastVisibleTime}constructor(){super(),D(this,"_lastHiddenTime",0),D(this,"_lastVisibleTime",0),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this._lastHiddenTime=performance.now():this._lastVisibleTime=performance.now(),_.debug("current web page is ".concat(document.visibilityState)),this.emit("VISIBILITY_CHANGE",document.visibilityState)})}};class jb extends $t{constructor(e,i){super(),D(this,"trackMediaType",_a.DATA),D(this,"_version",1),D(this,"_type",3),D(this,"_config",void 0),D(this,"_originDataChannel",void 0),D(this,"_dataStreamPacketHeader",new ArrayBuffer(4)),D(this,"_dataStreamPacketHandler",{serialize:n=>n,deserialize:n=>n}),D(this,"_datachannelEventMap",new Map),this._config=e,i&&(this._originDataChannel=i,this._bandDataChannelEvents(i)),this._initPacketHeader()}useDataStream(e){this._dataStreamPacketHandler=e}get id(){return this._config.id}get ordered(){return this._config.ordered}get maxRetransmits(){return y("DATASTREAM_MAX_RETRANSMITS")}get metadata(){return this._config.metadata}get readyState(){var e,i;return(e=(i=this._originDataChannel)===null||i===void 0?void 0:i.readyState)!==null&&e!==void 0?e:"connecting"}get _originDataChannelId(){var e,i;return(e=(i=this._originDataChannel)===null||i===void 0?void 0:i.id)!==null&&e!==void 0?e:null}getChannelId(){return this.id}getConfig(){return this._config}_close(){this._originDataChannel&&(this._unbindDataChannelEvents(this._originDataChannel),this._originDataChannel=void 0)}_waitTillOpen(){return C(this,null,function*(){return new K((e,i)=>{if(this._originDataChannel){this._originDataChannel.readyState==="open"&&e();const n=setTimeout(()=>{var r;i(new k(v.DATACHANNEL_CONNECTION_TIMEOUT,"Cannot create datachannel, id: ".concat((r=this._originDataChannel)===null||r===void 0?void 0:r.id)))},1e4);this._originDataChannel.onopen=()=>{clearTimeout(n),this._originDataChannel&&this._bandDataChannelEvents(this._originDataChannel),e()},this._originDataChannel.onerror=()=>{throw clearTimeout(n),new k(v.DATACHANNEL_CONNECTION_TIMEOUT)}}else i(new k(v.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),[Su.OPEN,Su.CLOSE,Su.ERROR].forEach(i=>{const n=()=>{this.emit(i)};this._datachannelEventMap.set(i,n),e.addEventListener(i,n)})}_unbindDataChannelEvents(e){Array.from(this._datachannelEventMap.entries()).forEach(i=>{let[n,r]=i;e.removeEventListener(n,r)}),this._datachannelEventMap.clear()}}class g3 extends jb{constructor(e){super(e),D(this,"_messageListener",void 0),this._messageListener=i=>{if(i.data.byteLength<this._dataStreamPacketHeader.byteLength)throw Error("invalid byteLength: the byte length must exceed "+this._dataStreamPacketHeader.byteLength);const n=i.data.slice(0,this._dataStreamPacketHeader.byteLength),r=new DataView(n).getUint8(3);if(r!==this.id)return void(y("SHOW_DATASTREAM2_LOG")&&_.debug("invalid datachannel id: ".concat(r," !== ").concat(this.id)));let o=i.data.slice(this._dataStreamPacketHeader.byteLength);o=this._dataStreamPacketHandler.deserialize(o),this.emit(Su.MESSAGE,o)}}_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)}}class S3 extends jb{send(e){if(this._originDataChannel){let i=e;i=this._dataStreamPacketHandler.serialize(e);const n=new Uint8Array(this._dataStreamPacketHeader.byteLength+i.byteLength);n.set(new Uint8Array(this._dataStreamPacketHeader),0),n.set(new Uint8Array(i),this._dataStreamPacketHeader.byteLength),this._originDataChannel.send(n.buffer)}}}function Cu(){const t=new Blob([atob("ZnVuY3Rpb24gdCh0LGUsbil7bGV0IGE9bmV3IFVpbnQ4QXJyYXkodCxlLG4pLG89W10scj0wO2Zvcig7by5sZW5ndGg8bjspciszPG4mJjA9PT1hW3JdJiYwPT09YVtyKzFdJiYzPT09YVtyKzJdJiYoMD09PWFbciszXXx8MT09PWFbciszXXx8Mj09PWFbciszXXx8Mz09PWFbciszXSk/KG8ucHVzaChhW3JdLGFbcisxXSxhW3IrM10pLHIrPTQpOihvLnB1c2goYVtyXSkscisrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobyl9ZnVuY3Rpb24gZSh0LGUpe2NvbnN0IG49ZnVuY3Rpb24odCl7Y29uc3QgZT10Lmxlbmd0aDtsZXQgbj1bXSxhPTA7Zm9yKDthPGU7KWErMjxlJiYwPT09dFthXSYmMD09PXRbYSsxXSYmKDA9PT10W2ErMl18fDE9PT10W2ErMl18fDI9PT10W2ErMl18fDM9PT10W2ErMl0pPyhuLnB1c2godFthXSx0W2ErMV0sMyx0W2ErMl0pLGErPTMpOihuLnB1c2godFthXSksYSsrKTtyZXR1cm4gbmV3IFVpbnQ4QXJyYXkobil9KGUpLGE9bi5sZW5ndGgsbz1NYXRoLmZsb29yKGEvMjU1KSxyPWElMjU1LHM9bmV3IFVpbnQ4QXJyYXkoNitvKzErYSt0LmJ5dGVMZW5ndGgpO3NbMF09MCxzWzFdPTAsc1syXT0wLHNbM109MSxzWzRdPTYsc1s1XT0xMDE7bGV0IGk9MDtmb3IoO2k8bzspc1s2K2ldPTI1NSxpKys7cmV0dXJuIHNbNitpXT1yLGkrKyxzLnNldChuLDYraSkscy5zZXQobmV3IFVpbnQ4QXJyYXkodCksNitpK2EpLHMuYnVmZmVyfWNvbnN0IG49NzEsYT0xLG89MixyPTEscz0yO3ZhciBpOyFmdW5jdGlvbih0KXt0W3QuQVVESU9fTEVWRUw9MV09IkFVRElPX0xFVkVMIix0W3QuTUVUQURBVEE9Ml09Ik1FVEFEQVRBIix0W3QuQVVESU9fNjRfQklUX1BUUz0zXT0iQVVESU9fNjRfQklUX1BUUyJ9KGl8fChpPXt9KSk7bmF2aWdhdG9yLnVzZXJBZ2VudC5pbmRleE9mKCJTYWZhcmkiKT4tMSYmLTE9PT1uYXZpZ2F0b3IudXNlckFnZW50LmluZGV4T2YoIkNocm9tZSIpJiYoc2VsZi5vbnJ0Y3RyYW5zZm9ybT1mPT57Y29uc3QgdT1mLnRyYW5zZm9ybWVyO2xldCBkPVtdLGw9W107dS5vcHRpb25zLnBvcnQub25tZXNzYWdlPXQ9Pnt0LmRhdGEuc2VpJiZkLnB1c2godC5kYXRhLnNlaSksdC5kYXRhLm1ldGFkYXRhJiZsLnB1c2godC5kYXRhLm1ldGFkYXRhKX0sc2VsZi5wb3N0TWVzc2FnZSgic3RhcnRlZCIpO2NvbnN0IGc9dS5yZWFkYWJsZS5nZXRSZWFkZXIoKSxjPXUud3JpdGFibGUuZ2V0V3JpdGVyKCk7InNlaS1yeCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiBlKG4pe2cucmVhZCgpLnRoZW4oKGE9PntpZighYS5kb25lKXtpZihhLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IGU9ZnVuY3Rpb24oZSl7Y29uc3Qgbj1uZXcgRGF0YVZpZXcoZS5kYXRhKTtsZXQgYT0wO2Zvcig7YSs0PGUuZGF0YS5ieXRlTGVuZ3RoOyl7aWYoMD09PW4uZ2V0VWludDgoYSswKSYmMD09PW4uZ2V0VWludDgoYSsxKSYmMD09PW4uZ2V0VWludDgoYSsyKSYmMT09PW4uZ2V0VWludDgoYSszKSYmNj09PW4uZ2V0VWludDgoYSs0KSl7bGV0IG89YSs2LHI9MCxzPTA7Zm9yKDsyNTU9PT0ocz1uLmdldFVpbnQ4KG8rKykpOylyKz0yNTU7cis9cztjb25zdCBpPXQoZS5kYXRhLG8scik7cmV0dXJuIG5ldyBVaW50OEFycmF5KGkpfWErK31yZXR1cm4gbnVsbH0oYS52YWx1ZSk7ZSYmbi5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3NlaTplfSl9Yy53cml0ZShhLnZhbHVlKSxuLm9wdGlvbnMucG9ydC5wb3N0TWVzc2FnZSh7dHJhbnNmb3JtZWQ6ITB9KSxlKG4pfX0pKX0odSk6InNlaS10eCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KG4pe2cucmVhZCgpLnRoZW4oKGE9PntpZighYS5kb25lKXtpZihhLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZFZpZGVvRnJhbWUpe2NvbnN0IHQ9ZC5zaGlmdCgpO3QmJihhLnZhbHVlLmRhdGE9ZShhLnZhbHVlLmRhdGEsdCkpfWMud3JpdGUoYS52YWx1ZSksbi5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChuKX19KSl9KHUpOiJhdWRpby1tZXRhZGF0YS1yeCI9PT11Lm9wdGlvbnMubmFtZT9mdW5jdGlvbiB0KGUpe2cucmVhZCgpLnRoZW4oKGY9PntpZighZi5kb25lKXtpZihmLnZhbHVlIGluc3RhbmNlb2YgUlRDRW5jb2RlZEF1ZGlvRnJhbWUpe2NvbnN0IHQ9ZnVuY3Rpb24odCxlPSExKXtjb25zdCBmPXQuZ2V0VWludDgoMCk7aWYoZiE9PW4pcmV0dXJuO2NvbnN0IHU9dC5nZXRVaW50MTYoMSksZD1hK28rdSxsPW5ldyBVaW50OEFycmF5KHQuYnl0ZUxlbmd0aC1kKTtsLnNldChuZXcgVWludDhBcnJheSh0LmJ1ZmZlcixkLHQuYnl0ZUxlbmd0aC1kKSk7Y29uc3QgZz17bTpmLHRsdkxlbjp1LHRsdjpbXSxmcmFtZTpsfTtsZXQgYz1hK287Zm9yKDtjPGQ7KXtjb25zdCBuPXQuZ2V0VWludDgoYyksYT10LmdldFVpbnQxNihjK3IpLG89citzO2lmKG49PT1pLkFVRElPX0xFVkVMKXtsZXQgcj10LmdldFVpbnQ4KGMrbyk7Zm9yKGxldCBlPTE7ZTxhO2UrKylyPXI8PDh8dC5nZXRVaW50OChjK28rZSk7Zy50bHYucHVzaCh7dGFnOm4sbGVuZ3RoOmEsdmFsdWU6ZT8xMjdecj4+MToxMjcmcn0pfWVsc2UgaWYobj09PWkuTUVUQURBVEF8fG49PT1pLkFVRElPXzY0X0JJVF9QVFMpe2NvbnN0IGU9bmV3IFVpbnQ4QXJyYXkoYSk7Zm9yKGxldCBuPTA7bjxhO24rKyllW25dPXQuZ2V0VWludDgoYytvK24pO2cudGx2LnB1c2goe3RhZzpuLGxlbmd0aDphLHZhbHVlOmV9KX1jKz1vK2F9cmV0dXJuIGd9KG5ldyBEYXRhVmlldyhmLnZhbHVlLmRhdGEpKTtpZih0KXtjb25zdCBuPXQudGx2LmZpbmQoKHQ9PnQudGFnPT09aS5NRVRBREFUQXx8dC50YWc9PT1pLkFVRElPXzY0X0JJVF9QVFMpKTtuJiZuLnZhbHVlIGluc3RhbmNlb2YgVWludDhBcnJheSYmZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe21ldGFkYXRhOm4udmFsdWV9KSxmLnZhbHVlLmRhdGE9dC5mcmFtZS5idWZmZXJ9fWMud3JpdGUoZi52YWx1ZSksZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe3RyYW5zZm9ybWVkOiEwfSksdChlKX19KSl9KHUpOiJhdWRpby1tZXRhZGF0YS10eCI9PT11Lm9wdGlvbnMubmFtZSYmZnVuY3Rpb24gdChlKXtnLnJlYWQoKS50aGVuKChmPT57aWYoIWYuZG9uZSl7aWYoZS5vcHRpb25zLnBvcnQucG9zdE1lc3NhZ2Uoe2dldE1ldGFkYXRhOiEwfSksZi52YWx1ZSBpbnN0YW5jZW9mIFJUQ0VuY29kZWRBdWRpb0ZyYW1lKXtjb25zdCB0PWwuc2hpZnQoKTt0JiYoZi52YWx1ZS5kYXRhPWZ1bmN0aW9uKHQsZSxpKXtjb25zdCBmPWkuYnl0ZUxlbmd0aCx1PWYrcitzLGQ9YStvK3UsbD1uZXcgQXJyYXlCdWZmZXIodC5ieXRlTGVuZ3RoK2QpLGc9bmV3IERhdGFWaWV3KGwpO2cuc2V0VWludDgoMCxuKSxnLnNldFVpbnQxNigxLHUpLGcuc2V0VWludDgoMyxlKSxnLnNldFVpbnQxNig0LGYpO2ZvcihsZXQgdD0wO3Q8Zjt0KyspZy5zZXRVaW50OCg2K3QsaVt0XSk7Y29uc3QgYz1uZXcgVWludDhBcnJheShnLmJ1ZmZlcik7cmV0dXJuIGMuc2V0KG5ldyBVaW50OEFycmF5KHQpLGQpLGMuYnVmZmVyfShmLnZhbHVlLmRhdGEsaS5BVURJT182NF9CSVRfUFRTLHQpKX1jLndyaXRlKGYudmFsdWUpLGUub3B0aW9ucy5wb3J0LnBvc3RNZXNzYWdlKHt0cmFuc2Zvcm1lZDohMH0pLHQoZSl9fSkpfSh1KX0sc2VsZi5wb3N0TWVzc2FnZSgicmVnaXN0ZXJlZCIpKTsK")],{type:"text/javascript"});return setTimeout(()=>vl.revokeObjectURL(t),0),new Worker(vl.createObjectURL(t))}const Gb=71,pm=1,_m=2,Em=1,Wb=2;var jr=function(t){return t[t.AUDIO_LEVEL=1]="AUDIO_LEVEL",t[t.METADATA=2]="METADATA",t[t.AUDIO_64_BIT_PTS=3]="AUDIO_64_BIT_PTS",t}(jr||{});function Hb(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const i=t.getUint8(0);if(i!==Gb)return;const n=t.getUint16(1),r=pm+_m+n,o=new Uint8Array(t.byteLength-r);o.set(new Uint8Array(t.buffer,r,t.byteLength-r));const s={m:i,tlvLen:n,tlv:[],frame:o};let a=pm+_m;for(;a<r;){const c=t.getUint8(a),d=t.getUint16(a+Em),l=Em+Wb;if(c===jr.AUDIO_LEVEL){let u=t.getUint8(a+l);for(let h=1;h<d;h++)u=u<<8|t.getUint8(a+l+h);s.tlv.push({tag:c,length:d,value:e?127^u>>1:127&u})}else if(c===jr.METADATA||c===jr.AUDIO_64_BIT_PTS){const u=new Uint8Array(d);for(let h=0;h<d;h++)u[h]=t.getUint8(a+l+h);s.tlv.push({tag:c,length:d,value:u})}a+=l+d}return s}const yu=new Map,Iu=127,ns=1e-10,mm=139/13,Au=new Map;function fm(t,e,i){const n="".concat(t,"-").concat(e,"-").concat(i);let r=0;return Au.has(n)?r=Au.get(n):(r=Math.log(function(s,a){const c=s-a;a<c&&(a=c);let d=1;for(let l=s,u=1;l>a;l--,u++)d=d*l/u;return d}(e,t))+t*Math.log(.5)+(e-t)*Math.log(1-.5)-Math.log(i)+i*t,Au.set(n,r)),r<ns&&(r=ns),r}function Kb(t,e,i){const n=e.length,r=t.length/n;let o=!1;for(let s=0,a=0;s<n;s++){let c=0;for(let d=a+r;a<d;a++)t[a]>i&&c++;e[s]!==c&&(e[s]=c,o=!0)}return o}window.cache=Au;let T3=0;class Yb{constructor(e){D(this,"id",void 0),D(this,"immediates",[]),D(this,"lastNonSilence",-1),D(this,"immediateSpeechActivityScore",ns),D(this,"lastLevelChangedTime",Date.now()),D(this,"levels",[]),D(this,"longs",[]),D(this,"longSpeechActivityScore",ns),D(this,"mediums",[]),D(this,"mediumSpeechActivityScore",ns),D(this,"minLevel",0),D(this,"nextMinLevel",0),D(this,"nextMinLevelWindowLength",0),D(this,"energyScore",0),this.id=e||"".concat(T3++),this.immediates.length=50,this.mediums.length=10,this.longs.length=1,this.levels.length=this.immediates.length}computeImmediates(){const e=this.immediates,i=this.levels,n=this.minLevel+mm;let r=!1;for(let o=0;o<e.length;++o){let s=i[o];s<n&&(s=0);const a=Math.floor(s/mm);e[o]!==a&&(e[o]=a,r=!0)}return r}computeLongs(){return Kb(this.mediums,this.longs,4)}computeMediums(){return Kb(this.immediates,this.mediums,7)}evaluateImmediateSpeechActivityScore(){this.immediateSpeechActivityScore=fm(this.immediates[0],13,.78)}evaluateLongSpeechActivityScore(e){this.longSpeechActivityScore=fm(this.longs[0],10,47),this.longSpeechActivityScore>ns&&(this.lastNonSilence=e)}evaluateMediumSpeechActivityScore(){this.mediumSpeechActivityScore=fm(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(bg(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,i){if(this.lastLevelChangedTime<=i){this.lastLevelChangedTime=i;let n=e;return e<0&&(n=0),e>Iu&&(n=Iu),this.levels.unshift(n),this.levels.length>this.immediates.length&&this.levels.pop(),this.updateMinLevel(n),n>=this.minLevel+mm?n:n/2}return-1}levelTimedOut(){this.levelChanged(0,this.lastLevelChangedTime)}updateMinLevel(e){if(e!==0){if(this.minLevel===0||this.minLevel>e)return this.minLevel=e,this.nextMinLevel=0,void(this.nextMinLevelWindowLength=0);if(this.nextMinLevel===0)return this.nextMinLevel=e,void(this.nextMinLevelWindowLength=1);if(this.nextMinLevel>e&&(this.nextMinLevel=e),this.nextMinLevelWindowLength++,this.nextMinLevelWindowLength>=750){let i=Math.sqrt(this.minLevel*this.nextMinLevel);i<0?i=0:i>Iu&&(i=Iu),this.minLevel=i,this.nextMinLevel=0,this.nextMinLevelWindowLength=0}}}}class R3{constructor(e){D(this,"algorithm",void 0),this.algorithm=e}execute(){let e=!this.algorithm;if(!e)try{const i=this.algorithm.runInDecisionMaker(this);i<=0?e=!0:setTimeout(this.execute.bind(this),i)}catch(i){e=!0}e&&this.algorithm&&this.algorithm.decisionMakerExited(this)}}class gm{constructor(e,i,n){D(this,"isDominant",void 0),D(this,"energyRanking",void 0),D(this,"energyScore",void 0),this.isDominant=e,this.energyRanking=i,this.energyScore=n}}class v3 extends $t{constructor(e){super(),D(this,"dominantId",null),D(this,"lastDecisionTime",0),D(this,"lastLevelChangedTime",0),D(this,"lastLevelIdleTime",0),D(this,"relativeSpeechActivities",[]),D(this,"speakers",new Map),D(this,"enableSilence",!1),D(this,"timeoutToSilenceInterval",0),D(this,"decisionMaker",null),D(this,"loudest",[]),D(this,"numLoudestToTrack",3),D(this,"energyExpireTimeMs",250),D(this,"energyAlphaPct",50),this.timeoutToSilenceInterval=e,this.enableSilence=e>0,this.relativeSpeechActivities.length=3}setLoudestConfig(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3,i=arguments.length>1?arguments[1]:void 0,n=arguments.length>2?arguments[2]:void 0;this.numLoudestToTrack=e,i!=null&&(this.energyExpireTimeMs=i),n!=null&&(this.energyAlphaPct=n),this.loudest.length>e&&this.loudest.splice(e)}getDominantSpeaker(){return this.dominantId}isAmongLoudest(e){return this.loudest.some(i=>i.id===e)}levelChanged(e,i){const n=Date.now(),r=this.getOrCreateSpeaker(e);this.lastLevelChangedTime<n&&(this.lastLevelChangedTime=n,this.maybeStartDecisionMaker());const o=r.levelChanged(i,n);return this.updateLoudestList(r,o,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(i=>{this.speakers.has(i.id)||this.speakers.set(i.id,i)})}removeSpeakers(e){e.forEach(i=>{this.speakers.delete(i.id)})}getOrCreateSpeaker(e){let i=this.speakers.get(e);return i||(i=new Yb(e),this.speakers.set(e,i),this.maybeStartDecisionMaker()),i}updateLoudestList(e,i,n){const r=e.id===this.dominantId;if(i<0){let c=0;for(;c<this.loudest.length&&this.loudest[c]!==e;)++c;return new gm(r,c,e.energyScore)}if(e.energyScore=Math.floor((this.energyAlphaPct*i+(100-this.energyAlphaPct)*e.energyScore+50)/100),this.numLoudestToTrack===0)return new gm(r,0,e.energyScore);const o=n-this.energyExpireTimeMs;let s=0;for(;s<this.loudest.length;){const c=this.loudest[s];if(c.getLastLevelChangedTime()<o&&this.loudest.length>=this.numLoudestToTrack)this.loudest.splice(s,1);else if(c.id!==e.id)++s;else if(this.loudest.splice(s,1),this.loudest.length<this.numLoudestToTrack)break}let a=0;for(;a<this.loudest.length&&!(this.loudest[a].energyScore<e.energyScore);)++a;return a<this.numLoudestToTrack&&(this.loudest.splice(a,0,e),this.loudest.length>this.numLoudestToTrack&&this.loudest.splice(this.numLoudestToTrack,1)),new gm(r,a,e.energyScore)}maybeStartDecisionMaker(){!this.decisionMaker&&this.speakers.size>0&&(this.decisionMaker=new R3(this),this.decisionMaker.execute())}makeDecision(e){let i=null,n=null;const r=this.speakers.size;let o=null;if(r===0)o=null;else if(r===1){var s;const a=Ui(s=this.speakers).call(s).next().value;this.enableSilence&&a&&(o=a.id,a.evaluateSpeechActivityScores(e),e-a.lastNonSilence>this.timeoutToSilenceInterval&&(o=null))}else{let a=this.dominantId==null?null:this.speakers.get(this.dominantId);if(a==null){const l=this.speakers.entries().next();l.value&&(o=l.value[0],a=l.value[1])}else o=a.id;a!=null&&a.evaluateSpeechActivityScores(e);const c=this.relativeSpeechActivities;let d=2;for(const l of this.speakers.entries()){const[u,h]=l;if(h===a)continue;h.evaluateSpeechActivityScores(e);for(let f=0;f<c.length;++f){const T=a==null?ns:a.getSpeechActivityScore(f);c[f]=Math.log(h.getSpeechActivityScore(f)/T)}const p=c[0],g=c[1],m=c[2];p>3&&g>2&&m>0&&g>d&&(d=g,o=u)}this.enableSilence&&a!=null&&o===a.id&&e-a.lastNonSilence>this.timeoutToSilenceInterval&&(o=null)}o==null&&!this.enableSilence||o===this.dominantId||(i=this.dominantId,this.dominantId=o,n=this.dominantId),n==null&&!this.enableSilence||n===i||this.emit("ActiveSpeakerChanged",n)}_runInDecisionMaker(){const e=Date.now(),i=300-(e-this.lastLevelIdleTime);let n=0;i<=0?(this.lastLevelIdleTime!==0&&this.timeoutIdleLevels(e),this.lastLevelIdleTime=e):n=i;let r=300-(e-this.lastDecisionTime);return r<=0&&(this.lastDecisionTime=e,this.makeDecision(e),r=300-(Date.now()-e)),r>0&&n>r&&(n=r),n}timeoutIdleLevels(e){const i=[];for(const r of Ui(n=this.speakers).call(n)){var n;const o=e-r.getLastLevelChangedTime();36e5<o&&(this.dominantId==null||r.id!==this.dominantId)?i.push(r.id):300<o&&r.levelTimedOut()}i.forEach(r=>this.speakers.delete(r))}}const Ta=new Map;let Zn=null,bu=null;const qb=3;let rs=[];const $n=new Map,wu=new Map;class C3{get samples(){return this.actives+this.inactives}get activeRate(){return this.actives/this.samples}constructor(e,i){D(this,"id",void 0),D(this,"track",void 0),D(this,"score",0),D(this,"active",!0),D(this,"muted",!1),D(this,"timer",0),D(this,"actives",0),D(this,"inactives",0),this.id=e,this.track=i,this.setActive($n.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{actives:i,inactives:n}=function(){const r=[],o=[];return Array.from(Ui($n).call($n)).forEach(s=>{s.active?r.push(s):o.push(s)}),{actives:r,inactives:o}}();if(i.length>3){let r;i.forEach(o=>{(!r||r.score>o.score)&&(r=o)}),r&&r.setActive(!1)}if(i.length<3&&n.length>0){let r;n.forEach(o=>{(!r||r.score<o.score)&&o.id!==this.id&&(r=o)}),r&&e&&!this.active&&(r.samples>40&&r.activeRate-this.activeRate>.4?r.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(i){let n;return Array.from(Ui($n).call($n)).forEach(r=>{!r.active||r.id===i||r.samples<40||(!n||r.score<n.score)&&(n=r)}),n}(this.id);e&&this.activeRate-e.activeRate>.4&&(e.setActive(!1),this.setActive(!0))}autoSwitchToInactive(){const e=function(i){let n;return Array.from(Ui($n).call($n)).forEach(r=>{r.active||r.id===i||r.samples<40||(!n||r.score>n.score)&&(n=r)}),n}(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(this.samples!==0)return this.samples<50?this.resetTimer():void this.autoCheckActive()},1e3)}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=0)}}let Ou;function zb(t){const e=$n.get(t);e&&($n.delete(t),e.clearTimer())}const Nu=new Map,y3=new Map;function I3(t,e,i){let n=new Uint8Array(t,e,i),r=[],o=0;for(;r.length<i;)o+3<i&&n[o]===0&&n[o+1]===0&&n[o+2]===3&&(n[o+3]===0||n[o+3]===1||n[o+3]===2||n[o+3]===3)?(r.push(n[o],n[o+1],n[o+3]),o+=4):(r.push(n[o]),o++);return new Uint8Array(r)}const Du=new Map,Vc=new Map;(function(){const t=vt();xe.getDisplayMedia=!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia),xe.getStreamFromExtension=t.name===It.CHROME&&Number(t.version)>34,xe.supportUnifiedPlan=function(){if(!window.RTCRtpTransceiver||!("currentDirection"in RTCRtpTransceiver.prototype))return!1;const e=new RTCPeerConnection;let i=!1;try{e.addTransceiver("audio"),i=!0}catch(n){}return e.close(),i}(),xe.supportMinBitrate=t.name===It.CHROME||t.name===It.EDGE,xe.supportSetRtpSenderParameters=function(){const e=vt();return!!(window.RTCRtpSender&&window.RTCRtpSender.prototype.setParameters&&window.RTCRtpSender.prototype.getParameters)&&(!!Vr()||!(!je()&&!su())||e.name===It.FIREFOX&&Number(e.version)>=64)}(),t.name===It.SAFARI&&(Number(t.version)>=14?xe.supportDualStream=!0:xe.supportDualStream=!1),xe.webAudioMediaStreamDest=function(){const e=vt();return!(e.name===It.SAFARI&&Number(e.version)<12)}(),xe.supportReplaceTrack=!!window.RTCRtpSender&&typeof RTCRtpSender.prototype.replaceTrack=="function",xe.supportWebGL=typeof WebGLRenderingContext!="undefined",xe.supportRequestFrame=!!window.CanvasCaptureMediaStreamTrack,Vr()||(xe.webAudioWithAEC=!0),xe.supportShareAudio=function(){const e=vt();return(e.os===we.WIN_10||e.os===we.WIN_81||e.os===we.WIN_7||e.os===we.LINUX||e.os===we.MAC_OS||e.os===we.CHROMIUM_OS)&&e.name===It.CHROME&&Number(e.version)>=74}(),xe.supportDataChannel=!!(Ac(76)||function(e){const i=vt();return!(i.name!==It.FIREFOX||!i.osVersion)&&Number(i.version)>=e}(68)||Qy(14)),xe.supportPCSetConfiguration=function(){const e=window.RTCPeerConnection;return!ne()&&!!e&&e.prototype.setConfiguration instanceof Function}(),xe.supportWebRTCEncodedTransform=function(){const e=vt();return e.name==="Chrome"&&Number(e.version)>=87||e.name==="Safari"&&Number(e.version)>=15}(),xe.supportWebRTCInsertableStream=function(){const e=vt();return(e.name===It.CHROME||e.name===It.EDGE)&&Number(e.version)>=94&&"MediaStreamTrackGenerator"in window&&"MediaStreamTrackProcessor"in window}(),xe.supportRequestVideoFrameCallback="requestVideoFrameCallback"in HTMLVideoElement.prototype,xe.supportWebCrypto=typeof window!="undefined"&&window.crypto!==void 0&&window.crypto.subtle!==void 0,du(()=>{xe.supportDualStreamEncoding=function(){const e=vt();return!!y("DISABLE_WEBAUDIO")||e.name==="Safari"&&Number(e.version)>=14||!!(e.name==="Chrome"&&/Windows/i.test(e.os||"")&&Number(e.version)>=100&&y("CHROME_DUAL_STREAM_USE_ENCODING"))}(),_.debug("browser ua: ",navigator.userAgent),_.info("browser info: ",t),_.info("browser compatibility: ",xe)})})();const A3=["CHINA","GLOBAL"],Xb=[[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]],os=[],Ra=[];function ss(t,e){return!!e&&os.some(i=>i.uid===t&&i.channelName===e)}function Sm(){return Ra.length>0}var b3=_C.forEach,Jb=kd("forEach")?[].forEach:function(t){return b3(this,t,arguments.length>1?arguments[1]:void 0)};Nt({target:"Array",proto:!0,forced:[].forEach!==Jb},{forEach:Jb});var w3=Sn("Array","forEach"),O3=no,N3=ti,D3=$e,P3=w3,Tm=Array.prototype,L3={DOMTokenList:!0,NodeList:!0},k3=function(t){var e=t.forEach;return t===Tm||D3(Tm,t)&&e===Tm.forEach||N3(L3,O3(t))?P3:e},M3=Pt(k3),U3=dr,Qb=Bd;Nt({target:"Object",stat:!0,forced:Lt(function(){Qb(1)})},{keys:function(t){return Qb(U3(t))}});var x3=Pt(sn.Object.keys),V3=Pt(yg),F3=Pt(Ag),B3=Nt,Zb=Ja,j3=tl,G3=gi,$b=Wh,W3=io,H3=to,K3=c_,Y3=Re,q3=oo,z3=rC("slice"),X3=Y3("species"),Rm=Array,J3=Math.max;B3({target:"Array",proto:!0,forced:!z3},{slice:function(t,e){var i,n,r,o=H3(this),s=W3(o),a=$b(t,s),c=$b(e===void 0?s:e,s);if(Zb(o)&&(i=o.constructor,(j3(i)&&(i===Rm||Zb(i.prototype))||G3(i)&&(i=i[X3])===null)&&(i=void 0),i===Rm||i===void 0))return q3(o,a,c);for(n=new(i===void 0?Rm:i)(J3(c-a,0)),r=0;a<c;a++,r++)a in o&&K3(n,r,o[a]);return n.length=r,n}});var Q3=Sn("Array","slice"),Z3=$e,$3=Q3,vm=Array.prototype,tW=function(t){var e=t.slice;return t===vm||Z3(vm,t)&&e===vm.slice?$3:e},eW=Pt(tW);function Q(t,e,i,n,r){var o,s,a,c={};return M3(o=x3(n)).call(o,function(d){c[d]=n[d]}),c.enumerable=!!c.enumerable,c.configurable=!!c.configurable,("value"in c||c.initializer)&&(c.writable=!0),c=V3(s=F3(a=eW(i).call(i)).call(a)).call(s,function(d,l){return l(t,e,d)||d},c),r&&c.initializer!==void 0&&(c.value=c.initializer?c.initializer.call(r):void 0,c.initializer=void 0),c.initializer===void 0?(tC(t,e,c),null):c}let Pu=function(t){return t[t.ACCESS_POINT=101]="ACCESS_POINT",t[t.UNILBS=201]="UNILBS",t[t.STRING_UID_ALLOCATOR=901]="STRING_UID_ALLOCATOR",t}({}),Cm=function(t){return t[t.IIIEGAL_APPID=1]="IIIEGAL_APPID",t[t.IIIEGAL_UID=2]="IIIEGAL_UID",t[t.INTERNAL_ERROR=3]="INTERNAL_ERROR",t}({}),Dn=function(t){return t[t.INVALID_VENDOR_KEY=5]="INVALID_VENDOR_KEY",t[t.INVALID_CHANNEL_NAME=7]="INVALID_CHANNEL_NAME",t[t.INTERNAL_ERROR=8]="INTERNAL_ERROR",t[t.NO_AUTHORIZED=9]="NO_AUTHORIZED",t[t.DYNAMIC_KEY_TIMEOUT=10]="DYNAMIC_KEY_TIMEOUT",t[t.NO_ACTIVE_STATUS=11]="NO_ACTIVE_STATUS",t[t.DYNAMIC_KEY_EXPIRED=13]="DYNAMIC_KEY_EXPIRED",t[t.STATIC_USE_DYNAMIC_KEY=14]="STATIC_USE_DYNAMIC_KEY",t[t.DYNAMIC_USE_STATIC_KEY=15]="DYNAMIC_USE_STATIC_KEY",t[t.USER_OVERLOAD=16]="USER_OVERLOAD",t[t.FORBIDDEN_REGION=18]="FORBIDDEN_REGION",t[t.CANNOT_MEET_AREA_DEMAND=19]="CANNOT_MEET_AREA_DEMAND",t}({}),hi=function(t){return t[t.NO_FLAG_SET=100]="NO_FLAG_SET",t[t.FLAG_SET_BUT_EMPTY=101]="FLAG_SET_BUT_EMPTY",t[t.INVALID_FALG_SET=102]="INVALID_FALG_SET",t[t.FLAG_SET_BUT_NO_RE=103]="FLAG_SET_BUT_NO_RE",t[t.INVALID_SERVICE_ID=104]="INVALID_SERVICE_ID",t[t.NO_SERVICE_AVAILABLE=200]="NO_SERVICE_AVAILABLE",t[t.NO_SERVICE_AVAILABLE_P2P=201]="NO_SERVICE_AVAILABLE_P2P",t[t.NO_SERVICE_AVAILABLE_VOICE=202]="NO_SERVICE_AVAILABLE_VOICE",t[t.NO_SERVICE_AVAILABLE_WEBRTC=203]="NO_SERVICE_AVAILABLE_WEBRTC",t[t.NO_SERVICE_AVAILABLE_CDS=204]="NO_SERVICE_AVAILABLE_CDS",t[t.NO_SERVICE_AVAILABLE_CDN=205]="NO_SERVICE_AVAILABLE_CDN",t[t.NO_SERVICE_AVAILABLE_TDS=206]="NO_SERVICE_AVAILABLE_TDS",t[t.NO_SERVICE_AVAILABLE_REPORT=207]="NO_SERVICE_AVAILABLE_REPORT",t[t.NO_SERVICE_AVAILABLE_APP_CENTER=208]="NO_SERVICE_AVAILABLE_APP_CENTER",t[t.NO_SERVICE_AVAILABLE_ENV0=209]="NO_SERVICE_AVAILABLE_ENV0",t[t.NO_SERVICE_AVAILABLE_VOET=210]="NO_SERVICE_AVAILABLE_VOET",t[t.NO_SERVICE_AVAILABLE_STRING_UID=211]="NO_SERVICE_AVAILABLE_STRING_UID",t[t.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS=212]="NO_SERVICE_AVAILABLE_WEBRTC_UNILBS",t[t.NO_SERVICE_AVAILABLE_UNILBS_FLV=213]="NO_SERVICE_AVAILABLE_UNILBS_FLV",t}({}),tt=function(t){return t[t.K_TIMESTAMP_EXPIRED=2]="K_TIMESTAMP_EXPIRED",t[t.K_CHANNEL_PERMISSION_INVALID=3]="K_CHANNEL_PERMISSION_INVALID",t[t.K_CERTIFICATE_INVALID=4]="K_CERTIFICATE_INVALID",t[t.K_CHANNEL_NAME_EMPTY=5]="K_CHANNEL_NAME_EMPTY",t[t.K_CHANNEL_NOT_FOUND=6]="K_CHANNEL_NOT_FOUND",t[t.K_TICKET_INVALID=7]="K_TICKET_INVALID",t[t.K_CHANNEL_CONFLICTED=8]="K_CHANNEL_CONFLICTED",t[t.K_SERVICE_NOT_READY=9]="K_SERVICE_NOT_READY",t[t.K_SERVICE_TOO_HEAVY=10]="K_SERVICE_TOO_HEAVY",t[t.K_UID_BANNED=14]="K_UID_BANNED",t[t.K_IP_BANNED=15]="K_IP_BANNED",t[t.K_CHANNEL_BANNED=16]="K_CHANNEL_BANNED",t[t.DATASTREAM2_NOT_AVAILABLE=27]="DATASTREAM2_NOT_AVAILABLE",t[t.K_AUTO_REBALANCE=28]="K_AUTO_REBALANCE",t[t.WARN_NO_AVAILABLE_CHANNEL=103]="WARN_NO_AVAILABLE_CHANNEL",t[t.WARN_LOOKUP_CHANNEL_TIMEOUT=104]="WARN_LOOKUP_CHANNEL_TIMEOUT",t[t.WARN_LOOKUP_CHANNEL_REJECTED=105]="WARN_LOOKUP_CHANNEL_REJECTED",t[t.WARN_OPEN_CHANNEL_TIMEOUT=106]="WARN_OPEN_CHANNEL_TIMEOUT",t[t.WARN_OPEN_CHANNEL_REJECTED=107]="WARN_OPEN_CHANNEL_REJECTED",t[t.WARN_REQUEST_DEFERRED=108]="WARN_REQUEST_DEFERRED",t[t.ERR_DYNAMIC_KEY_TIMEOUT=109]="ERR_DYNAMIC_KEY_TIMEOUT",t[t.ERR_NO_AUTHORIZED=110]="ERR_NO_AUTHORIZED",t[t.ERR_VOM_SERVICE_UNAVAILABLE=111]="ERR_VOM_SERVICE_UNAVAILABLE",t[t.ERR_NO_CHANNEL_AVAILABLE_CODE=112]="ERR_NO_CHANNEL_AVAILABLE_CODE",t[t.ERR_MASTER_VOCS_UNAVAILABLE=114]="ERR_MASTER_VOCS_UNAVAILABLE",t[t.ERR_INTERNAL_ERROR=115]="ERR_INTERNAL_ERROR",t[t.ERR_NO_ACTIVE_STATUS=116]="ERR_NO_ACTIVE_STATUS",t[t.ERR_INVALID_UID=117]="ERR_INVALID_UID",t[t.ERR_DYNAMIC_KEY_EXPIRED=118]="ERR_DYNAMIC_KEY_EXPIRED",t[t.ERR_STATIC_USE_DYANMIC_KE=119]="ERR_STATIC_USE_DYANMIC_KE",t[t.ERR_DYNAMIC_USE_STATIC_KE=120]="ERR_DYNAMIC_USE_STATIC_KE",t[t.ERR_NO_VOCS_AVAILABLE=2e3]="ERR_NO_VOCS_AVAILABLE",t[t.ERR_NO_VOS_AVAILABLE=2001]="ERR_NO_VOS_AVAILABLE",t[t.ERR_JOIN_CHANNEL_TIMEOUT=2002]="ERR_JOIN_CHANNEL_TIMEOUT",t[t.ERR_REPEAT_JOIN_CHANNEL=2003]="ERR_REPEAT_JOIN_CHANNEL",t[t.ERR_JOIN_BY_MULTI_IP=2004]="ERR_JOIN_BY_MULTI_IP",t[t.ERR_NOT_JOINED=2011]="ERR_NOT_JOINED",t[t.ERR_REPEAT_JOIN_REQUEST=2012]="ERR_REPEAT_JOIN_REQUEST",t[t.ERR_INVALID_VENDOR_KEY=2013]="ERR_INVALID_VENDOR_KEY",t[t.ERR_INVALID_CHANNEL_NAME=2014]="ERR_INVALID_CHANNEL_NAME",t[t.ERR_INVALID_STRINGUID=2015]="ERR_INVALID_STRINGUID",t[t.ERR_TOO_MANY_USERS=2016]="ERR_TOO_MANY_USERS",t[t.ERR_SET_CLIENT_ROLE_TIMEOUT=2017]="ERR_SET_CLIENT_ROLE_TIMEOUT",t[t.ERR_SET_CLIENT_ROLE_NO_PERMISSION=2018]="ERR_SET_CLIENT_ROLE_NO_PERMISSION",t[t.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE=2019]="ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",t[t.ERR_PUBLISH_REQUEST_INVALID=2020]="ERR_PUBLISH_REQUEST_INVALID",t[t.ERR_SUBSCRIBE_REQUEST_INVALID=2021]="ERR_SUBSCRIBE_REQUEST_INVALID",t[t.ERR_NOT_SUPPORTED_MESSAGE=2022]="ERR_NOT_SUPPORTED_MESSAGE",t[t.ERR_ILLEAGAL_PLUGIN=2023]="ERR_ILLEAGAL_PLUGIN",t[t.ERR_REJOIN_TOKEN_INVALID=2024]="ERR_REJOIN_TOKEN_INVALID",t[t.ERR_REJOIN_USER_NOT_JOINED=2025]="ERR_REJOIN_USER_NOT_JOINED",t[t.ERR_INVALID_OPTIONAL_INFO=2027]="ERR_INVALID_OPTIONAL_INFO",t[t.ILLEGAL_AES_PASSWORD=2028]="ILLEGAL_AES_PASSWORD",t[t.ILLEGAL_CLIENT_ROLE_LEVEL=2029]="ILLEGAL_CLIENT_ROLE_LEVEL",t[t.ERR_TOO_MANY_BROADCASTERS=2031]="ERR_TOO_MANY_BROADCASTERS",t[t.ERR_TOO_MANY_SUBSCRIBERS=2032]="ERR_TOO_MANY_SUBSCRIBERS",t[t.ERR_LICENSE_MISSING=32769]="ERR_LICENSE_MISSING",t[t.ERR_LICENSE_EXPIRED=32771]="ERR_LICENSE_EXPIRED",t[t.ERR_LICENSE_MINUTES_EXCEEDED=32773]="ERR_LICENSE_MINUTES_EXCEEDED",t[t.ERR_LICENSE_PERIOD_INVALID=32774]="ERR_LICENSE_PERIOD_INVALID",t[t.ERR_LICENSE_MULTIPLE_SDK_SERVICE=32778]="ERR_LICENSE_MULTIPLE_SDK_SERVICE",t[t.ERR_LICENSE_ILLEGAL=32783]="ERR_LICENSE_ILLEGAL",t[t.ERR_TEST_RECOVER=9e3]="ERR_TEST_RECOVER",t[t.ERR_TEST_TRYNEXT=9001]="ERR_TEST_TRYNEXT",t[t.ERR_TEST_RETRY=9002]="ERR_TEST_RETRY",t}({}),Ht=function(t){return t.CONNECTING="connecting",t.CONNECTED="connected",t.RECONNECTING="reconnecting",t.CLOSED="closed",t}({}),ot=function(t){return t.WS_CONNECTED="ws_connected",t.WS_RECONNECTING="ws_reconnecting",t.WS_CLOSED="ws_closed",t.WS_RECONNECT_CREATE_CONNECTION="ws_reconnect_create_connection",t.ON_BINARY_DATA="on_binary_data",t.REQUEST_RECOVER="request_recover",t.REQUEST_JOIN_INFO="request_join_info",t.REQUEST_REJOIN_INFO="req_rejoin_info",t.IS_P2P_DISCONNECTED="is_p2p_dis",t.DISCONNECT_P2P="dis_p2p",t.ABORT_P2P_EXECUTION="abort_p2p_execution",t.NEED_RENEW_SESSION="need-sid",t.REPORT_JOIN_GATEWAY="report_join_gateway",t.REQUEST_TIMEOUT="request_timeout",t.REQUEST_SUCCESS="request_success",t.JOIN_RESPONSE="join_response",t.PRE_CONNECT_PC="pre_connect_pc",t.P2P_CONNECTION="p2p_connection",t.P2P_REMOTE_CANDIDATE_UPDATE="p2p_remote_candidate_update",t.P2P_SUBSCRIBE="p2p_subscribe",t.P2P_UNSUBSCRIBE="p2p_unsubscribe",t.P2P_EXCHANGE_SDP="p2p_exchange_sdp",t.P2P_ON_ADD_VIDEO_STREAM="p2p_on_add_video_stream",t.P2P_ON_ADD_AUDIO_STREAM="p2p_on_add_audio_stream",t.RECOVER_NOTIFICATION="recover_notification",t}({}),nt=function(t){return t.PING="ping",t.PING_BACK="ping_back",t.JOIN="join_v3",t.REJOIN="rejoin_v3",t.LEAVE="leave",t.SET_CLIENT_ROLE="set_client_role",t.PUBLISH="publish",t.PUBLISH_DATASTREAM="publish_datastream",t.UNPUBLISH="unpublish",t.UNPUBLISH_DATASTREAM="unpublish_datastream",t.SUBSCRIBE="subscribe",t.PRE_SUBSCRIBE="pre_subscribe",t.SUBSCRIBE_DATASTREAM="subscribe_datastream",t.SUBSCRIBE_STREAMS="subscribe_streams",t.UNSUBSCRIBE="unsubscribe",t.UNSUBSCRIBE_DATASTREAM="unsubscribe_datastream",t.UNSUBSCRIBE_STREAMS="unsubscribe_streams",t.SUBSCRIBE_CHANGE="subscribe_change",t.TRAFFIC_STATS="traffic_stats",t.RENEW_TOKEN="renew_token",t.SWITCH_VIDEO_STREAM="switch_video_stream",t.DEFAULT_VIDEO_STREAM="default_video_stream",t.SET_FALLBACK_OPTION="set_fallback_option",t.GATEWAY_INFO="gateway_info",t.CONTROL="control",t.SEND_METADATA="send_metadata",t.DATA_STREAM="data_stream",t.PICK_SVC_LAYER="pick_svc_layer",t.RESTART_ICE="restart_ice",t.CONNECT_PC="connect_pc",t.SET_VIDEO_PROFILE="set_video_profile",t.SET_PARAMETER="set_parameter",t.SET_RTM2_FLAG="set_rtm2_flag",t}({}),Fc=function(t){return t.WRTC_STATS="wrtc_stats",t.WS_INFLATE_DATA_LENGTH="ws_inflate_data_length",t.DENOISER_STATS="denoiser_stats",t.EXTENSION_USAGE_STATS="extension_usage_stats",t}({}),mt=function(t){return t.ON_USER_ONLINE="on_user_online",t.ON_USER_OFFLINE="on_user_offline",t.ON_STREAM_FALLBACK_UPDATE="on_stream_fallback_update",t.ON_PUBLISH_STREAM="on_publish_stream",t.ON_UPLINK_STATS="on_uplink_stats",t.ON_P2P_LOST="on_p2p_lost",t.ON_REMOVE_STREAM="on_remove_stream",t.ON_ADD_AUDIO_STREAM="on_add_audio_stream",t.ON_ADD_VIDEO_STREAM="on_add_video_stream",t.ON_TOKEN_PRIVILEGE_WILL_EXPIRE="on_token_privilege_will_expire",t.ON_TOKEN_PRIVILEGE_DID_EXPIRE="on_token_privilege_did_expire",t.ON_USER_BANNED="on_user_banned",t.ON_USER_LICENSE_BANNED="on_user_license_banned",t.ON_NOTIFICATION="on_notification",t.ON_CRYPT_ERROR="on_crypt_error",t.MUTE_AUDIO="mute_audio",t.MUTE_VIDEO="mute_video",t.UNMUTE_AUDIO="unmute_audio",t.UNMUTE_VIDEO="unmute_video",t.ON_P2P_OK="on_p2p_ok",t.RECEIVE_METADATA="receive_metadata",t.ON_DATA_STREAM="on_data_stream",t.ON_RTP_CAPABILITY_CHANGE="on_rtp_capability_change",t.ON_REMOTE_DATASTREAM_UPDATE="on_remote_datastream_update",t.ON_REMOTE_FULL_DATASTREAM_INFO="on_remote_full_datastream_info",t.ENABLE_LOCAL_VIDEO="enable_local_video",t.DISABLE_LOCAL_VIDEO="disable_local_video",t.ENABLE_LOCAL_AUDIO="enable_local_audio",t.DISABLE_LOCAL_AUDIO="disable_local_audio",t.ON_PUBLISHED_USER_LIST="on_published_user_list",t}({}),pi=function(t){return t.SEND_ONLY="SEND_ONLY",t.RECEIVE_ONLY="RECEIVE_ONLY",t}({}),dt=function(t){return t.CONNECTED="websocket:connected",t.RECONNECTING="websocket:reconnecting",t.WILL_RECONNECT="websocket:will_reconnect",t.CLOSED="websocket:closed",t.FAILED="websocket:failed",t.ON_MESSAGE="websocket:on_message",t.REQUEST_NEW_URLS="websocket:request_new_urls",t.RECONNECT_CREATE_CONNECTION="websocket:reconnect_create_connection",t.ON_TOKEN_PRIVILEGE_DID_EXPIRE="websocket:on_token_privilege_did_expire",t}({});function Lu(t){if(typeof t!="string"||!/^[a-zA-Z0-9 \!\#\$\%\&\(\)\+\-\:\;\<\=\.\>\?\@\[\]\^\_\{\}\|\~\,]{1,64}$/.test(t))throw _.error("Invalid Channel Name ".concat(t)),new P(v.INVALID_PARAMS,"The length must be within 64 bytes. The supported characters: a-z,A-Z,0-9,space,!, #, $, %, &, (, ), +, -, :, ;, <, =, ., >, ?, @, [, ], ^, _, {, }, |, ~, ,")}function ku(t){if(e=t,!(typeof e=="number"&&Math.floor(e)===e&&0<=e&&e<=4294967295||oI(t,1,255)))throw new P(v.INVALID_PARAMS,"[String uid] Length of the string: [1,255]. ASCII characters only. [Number uid] The value range is [0,10000]");var e;typeof t=="string"&&_.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 Gr=function(t){return t.TRANSCODE="mix_streaming",t.RAW="raw_streaming",t}({});const iW={alpha:1,height:640,width:360,x:0,y:0,zOrder:0,audioChannel:0},ym={x:0,y:0,width:160,height:160,zOrder:255,alpha:1};function Im(t,e){Me(t.url,"".concat(e,".url"),1,1e3,!1),re(t.x)||xt(t.x,"".concat(e,".x"),0,1e4),re(t.y)||xt(t.y,"".concat(e,".y"),0,1e4),re(t.width)||xt(t.width,"".concat(e,".width"),0,1e4),re(t.height)||xt(t.height,"".concat(e,".height"),0,1e4),re(t.zOrder)||xt(t.zOrder,"".concat(e,".zOrder"),0,255),re(t.alpha)||xt(t.alpha,"".concat(e,".alpha"),0,1,!1)}const nW={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 fo=function(t){return t.WARNING="@live_uap-warning",t.ERROR="@line_uap-error",t.PUBLISH_STREAM_STATUS="@live_uap-publish-status",t.WORKER_STATUS="@live_uap-worker-status",t.REQUEST_NEW_ADDRESS="@live_uap-request-address",t}({}),Am=function(t){return t.REQUEST_WORKER_MANAGER_LIST="@live_req_worker_manager",t}({}),Ce=function(t){return t[t.LIVE_STREAM_RESPONSE_SUCCEED=200]="LIVE_STREAM_RESPONSE_SUCCEED",t[t.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM=454]="LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM",t[t.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR=450]="LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR",t[t.LIVE_STREAM_RESPONSE_BAD_STREAM=451]="LIVE_STREAM_RESPONSE_BAD_STREAM",t[t.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR=400]="LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR",t[t.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST=404]="LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST",t[t.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED=456]="LIVE_STREAM_RESPONSE_NOT_AUTHORIZED",t[t.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE=457]="LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE",t[t.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN=429]="LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN",t[t.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH=452]="LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH",t[t.LIVE_STREAM_RESPONSE_NOT_SUPPORTED=453]="LIVE_STREAM_RESPONSE_NOT_SUPPORTED",t[t.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM=455]="LIVE_STREAM_RESPONSE_MAX_STREAM_NUM",t[t.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR=500]="LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR",t[t.LIVE_STREAM_RESPONSE_WORKER_LOST=501]="LIVE_STREAM_RESPONSE_WORKER_LOST",t[t.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT=502]="LIVE_STREAM_RESPONSE_RESOURCE_LIMIT",t[t.LIVE_STREAM_RESPONSE_WORKER_QUIT=503]="LIVE_STREAM_RESPONSE_WORKER_QUIT",t[t.ERROR_FAIL_SEND_MESSAGE=504]="ERROR_FAIL_SEND_MESSAGE",t[t.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE=30]="PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE",t[t.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT=31]="PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT",t[t.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH=32]="PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH",t[t.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN=33]="PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN",t}({});function tw(t){if(!t.channelName)throw new P(v.INVALID_PARAMS,"invalid channelName in info");if(typeof t.uid!="number")throw new P(v.INVALID_PARAMS,"invalid uid in info, uid must be a number");return t.token&&Me(t.token,"info.token",1,2047),ku(t.uid),Lu(t.channelName),!0}let _i=function(t){return t[t.SetSdkProfile=0]="SetSdkProfile",t[t.SetSourceChannel=1]="SetSourceChannel",t[t.SetSourceUserId=2]="SetSourceUserId",t[t.SetDestChannel=3]="SetDestChannel",t[t.StartPacketTransfer=4]="StartPacketTransfer",t[t.StopPacketTransfer=5]="StopPacketTransfer",t[t.UpdateDestChannel=6]="UpdateDestChannel",t[t.Reconnect=7]="Reconnect",t[t.SetVideoProfile=8]="SetVideoProfile",t}({}),Wr=function(t){return t.NETWORK_DISCONNECTED="NETWORK_DISCONNECTED",t.NETWORK_CONNECTED="NETWORK_CONNECTED",t.PACKET_JOINED_SRC_CHANNEL="PACKET_JOINED_SRC_CHANNEL",t.PACKET_JOINED_DEST_CHANNEL="PACKET_JOINED_DEST_CHANNEL",t.PACKET_SENT_TO_DEST_CHANNEL="PACKET_SENT_TO_DEST_CHANNEL",t.PACKET_RECEIVED_VIDEO_FROM_SRC="PACKET_RECEIVED_VIDEO_FROM_SRC",t.PACKET_RECEIVED_AUDIO_FROM_SRC="PACKET_RECEIVED_AUDIO_FROM_SRC",t.PACKET_UPDATE_DEST_CHANNEL="PACKET_UPDATE_DEST_CHANNEL",t.PACKET_UPDATE_DEST_CHANNEL_REFUSED="PACKET_UPDATE_DEST_CHANNEL_REFUSED",t.PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE="PACKET_UPDATE_DEST_CHANNEL_NOT_CHANGE",t}({}),Di=function(t){return t.RELAY_STATE_IDLE="RELAY_STATE_IDLE",t.RELAY_STATE_CONNECTING="RELAY_STATE_CONNECTING",t.RELAY_STATE_RUNNING="RELAY_STATE_RUNNING",t.RELAY_STATE_FAILURE="RELAY_STATE_FAILURE",t}({}),va=function(t){return t.RELAY_OK="RELAY_OK",t.SERVER_CONNECTION_LOST="SERVER_CONNECTION_LOST",t.SRC_TOKEN_EXPIRED="SRC_TOKEN_EXPIRED",t.DEST_TOKEN_EXPIRED="DEST_TOKEN_EXPIRED",t}({}),Ot=function(t){return t.High="high",t.Low="low",t.Audio="audio",t.Screen="screen",t.ScreenLow="screen_low",t}({}),De=function(t){return t.DISCONNECT="disconnect",t.CONNECTION_STATE_CHANGE="connection-state-change",t.NETWORK_QUALITY="network-quality",t.STREAM_TYPE_CHANGE="stream-type-change",t.IS_P2P_DISCONNECTED="is-p2p-dis",t.DISCONNECT_P2P="dis-p2p",t.REQUEST_NEW_GATEWAY_LIST="req-gate-url",t.NEED_RENEW_SESSION="need-sid",t.REQUEST_P2P_CONNECTION_PARAMS="request-p2p-connection-params",t.JOIN_RESPONSE="join-response",t.RESET_CONNECTION_EVENTS="reset-connection-events",t.PRE_CONNECT_PC="pre-connect_pc",t.UPDATE_GATEWAY_CONFIG="update-gateway-config",t}({}),Mu=function(t){return t.P2P_DISCONNECTED="P2P_DISCONNECTED",t.A_ROUND_WS_FAILED="A_ROUND_WS_FAILED",t.TIMEOUT="TIMEOUT",t.UNKNOWN_REASON="UNKNOWN_REASON",t}({}),Ne=function(t){return t[t.Nothing=0]="Nothing",t[t.Audio=1]="Audio",t[t.LwoVideo=2]="LwoVideo",t[t.Video=4]="Video",t[t.Data=8]="Data",t[t.DataStream0=256]="DataStream0",t[t.DataStream1=512]="DataStream1",t[t.DataStream2=1024]="DataStream2",t[t.DataStream3=2048]="DataStream3",t[t.DataStream4=4096]="DataStream4",t[t.DataStream5=8192]="DataStream5",t[t.DataStream6=16384]="DataStream6",t[t.DataStream7=32768]="DataStream7",t}({}),At=function(t){return t.CHINA="CHINA",t.ASIA="ASIA",t.NORTH_AMERICA="NORTH_AMERICA",t.EUROPE="EUROPE",t.JAPAN="JAPAN",t.INDIA="INDIA",t.KOREA="KOREA",t.HKMC="HKMC",t.US="US",t.OCEANIA="OCEANIA",t.SOUTH_AMERICA="SOUTH_AMERICA",t.AFRICA="AFRICA",t.OVERSEA="OVERSEA",t.GLOBAL="GLOBAL",t.EXTENSIONS="EXTENSIONS",t}({});const ew=[At.AFRICA,At.ASIA,At.CHINA,At.EUROPE,At.GLOBAL,At.INDIA,At.JAPAN,At.NORTH_AMERICA,At.OCEANIA,At.OVERSEA,At.SOUTH_AMERICA];let ze=function(t){return t.CHINA="CN",t.ASIA="AS",t.NORTH_AMERICA="NA",t.EUROPE="EU",t.JAPAN="JP",t.INDIA="IN",t.KOREA="KR",t.HKMC="HK",t.US="US",t.OCEANIA="OC",t.SOUTH_AMERICA="SA",t.AFRICA="AF",t.OVERSEA="OVERSEA",t.GLOBAL="GLOBAL",t.EXTENSIONS="GLOBAL",t}({});const Uu={CHINA:{},ASIA:{CODE:ze.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:ze.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:ze.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:ze.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:ze.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:ze.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:ze.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:ze.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:ze.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:ze.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:ze.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:ze.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:ze.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:{}};qE&&(Uu.CHINA={CODE:ze.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 Bc=function(t){return t.UPDATE_BITRATE_LIMIT="update_bitrate_limit",t.UPDATE_CLIENT_ROLE_OPTIONS="update_client_role_options",t}({});function iw(t){return!!t&&!(!t.uplink||!t.id)&&t.uplink.max_bitrate!==void 0&&t.uplink.min_bitrate!==void 0}class nw extends $t{constructor(e,i){super(),S(this,"onICEConnectionStateChange",void 0),S(this,"onConnectionStateChange",void 0),S(this,"onDTLSTransportStateChange",void 0),S(this,"onDTLSTransportError",void 0),S(this,"onICETransportStateChange",void 0),S(this,"onFirstAudioReceived",void 0),S(this,"onFirstVideoReceived",void 0),S(this,"onFirstAudioDecoded",void 0),S(this,"onFirstVideoDecoded",void 0),S(this,"onFirstVideoDecodedTimeout",void 0),S(this,"onSelectedLocalCandidateChanged",void 0),S(this,"onSelectedRemoteCandidateChanged",void 0),S(this,"onICECandidateError",void 0),S(this,"getLocalVideoStats",void 0)}}class rw extends nw{constructor(e,i){super(e,i),S(this,"establishPromise",void 0)}}let q=function(t){return t.VIDEO="video",t.AUDIO="audio",t}({}),Xe=function(t){return t.UDP_RELAY="udp_relay",t.UDP_TCP_RELAY="udp_tcp_relay",t.TCP_RELAY="tcp_relay",t.RELAY="relay",t}({}),Hr=function(t){return t[t.FIRST_CONNECTION=0]="FIRST_CONNECTION",t[t.UDP_TCP_RESTART=1]="UDP_TCP_RESTART",t[t.RELAY_RESTART=2]="RELAY_RESTART",t[t.TCP_RESTART=3]="TCP_RESTART",t[t.OLD_FIRST_CONNECTION=10]="OLD_FIRST_CONNECTION",t[t.OLD_RESTART=11]="OLD_RESTART",t[t.DISCONNECTED_OR_FAILED=20]="DISCONNECTED_OR_FAILED",t}({});const ow=["disconnected","failed"];let V=function(t){return t.LocalVideoTrack="videoTrack",t.LocalAudioTrack="audioTrack",t.LocalVideoLowTrack="videoLowTrack",t}({}),wt=function(t){return t.New="new",t.Connected="connected",t.Reconnecting="reconnecting",t.Disconnected="disconnected",t}({}),$=function(t){return t.AudioMetadata="audioMetadata",t.StateChange="stateChange",t.IceConnectionStateChange="iceConnectionStateChange",t.RequestMuteLocal="requestMuteLocal",t.RequestUnmuteLocal="requestUnmuteLocal",t.RequestRePublish="requestRePublish",t.RequestRePublishDataChannel="requestRePublishDataChannel",t.RequestReSubscribe="requestReSubscribe",t.RequestUploadStats="requestUploadStats",t.RequestUpload="requestUpload",t.MediaReconnectStart="MediaReconnectStart",t.MediaReconnectEnd="MediaReconnectEnd",t.NeedSignalRTT="NeedSignalRTT",t.RequestRestartICE="RequestRestartIce",t.PeerConnectionStateChange="PeerConnectionStateChange",t.RequestReconnect="RequestReconnect",t.RequestReconnectPC="RequestReconnectPC",t.RequestUnpublishForReconnectPC="RequestUnpublishForReconnectPC",t.P2PLost="P2PLost",t.UpdateVideoEncoder="UpdateVideoEncoder",t.ConnectionTypeChange="ConnectionTypeChange",t.RequestLowStreamParameter="RequestLowStreamParameter",t.QueryClientConnectionState="QueryClientConnectionState",t.LocalCandidate="LocalCandidate",t.RequestP2PMuteLocal="requestP2PMuteLocal",t.RequestP2PUnPublish="RequestP2PUnPublish",t.RequestP2PUnmuteRemote="RequestP2PUnmuteRemote",t.RequestP2PMuteRemote="RequestP2PMuteRemote",t.RequestP2PRestartICE="RequestP2PRestartICE",t}({}),Pn=function(t){return t.CONNECTING="CONNECTING",t.RECONNECTING="RECONNECTING",t.CONNECTED="CONNECTED",t.CLOSED="CLOSED",t}({}),Ln=function(t){return t[t.CONNECT_AP=0]="CONNECT_AP",t[t.AP_CONNECTED=1]="AP_CONNECTED",t[t.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",t[t.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",t[t.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",t[t.CONNECT_WORKER=5]="CONNECT_WORKER",t[t.WORKER_CONNECTED=6]="WORKER_CONNECTED",t[t.CLOSED=7]="CLOSED",t}({}),Pe=function(t){return t.CONNECTION_STATE_CHANGE="connection-state-change",t.STATE_CHANGE="state-change",t.INSPECT_RESULT="inspect-result",t.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",t.REQUEST_NEW_WORKER_URL="request-new-worker-url",t}({}),sw=function(t){return t.CONNECTED="transmitter:connected",t.RECONNECTING="transmitter:reconnecting",t.WILL_RECONNECT="transmitter:will_reconnect",t.CLOSED="transmitter:closed",t.FAILED="transmitter:failed",t.ON_MESSAGE="transmitter:on_message",t.REQUEST_NEW_URLS="transmitter:request_new_urls",t.RECONNECT_CREATE_CONNECTION="transmitter:reconnect_create_connection",t.ON_TOKEN_PRIVILEGE_DID_EXPIRE="transmitter:on_token_privilege_did_expire",t.TO_CONNECT_DATACHANNEL="transmitter:to_connect_datachannel",t.FAILBACK="transmitter:failback",t.PRE_CONNECT_PC="transmitter:pre_connect_pc",t}({}),Tr=function(t){return t.CAMERA_CHANGED="camera-changed",t.MICROPHONE_CHANGED="microphone-changed",t.PLAYBACK_DEVICE_CHANGED="playback-device-changed",t.AUDIO_AUTOPLAY_FAILED="audio-autoplay-failed",t.AUTOPLAY_FAILED="autoplay-failed",t.AUDIO_CONTEXT_STATE_CHANGED="audio-context-state-changed",t.SECURITY_POLICY_VIOLATION="security-policy-violation",t}({}),hn=function(t){return t.CONNECTING="CONNECTING",t.RECONNECTING="RECONNECTING",t.CONNECTED="CONNECTED",t.CLOSED="CLOSED",t}({}),tr=function(t){return t.CONNECTION_STATE_CHANGE="connection-state-change",t.STATE_CHANGE="state-change",t.INSPECT_RESULT="inspect-result",t.CLIENT_LOCAL_VIDEO_TRACK="client-local-video-track",t.REQUEST_NEW_WORKER_URL="request-new-worker-url",t}({}),Ca=function(t){return t[t.CONNECT_AP=0]="CONNECT_AP",t[t.AP_CONNECTED=1]="AP_CONNECTED",t[t.CONNECT_WORKER_MANAGER=2]="CONNECT_WORKER_MANAGER",t[t.WORKER_MANAGER_CONNECTED=3]="WORKER_MANAGER_CONNECTED",t[t.GET_WORKER_MANAGER_RESPONSE=4]="GET_WORKER_MANAGER_RESPONSE",t[t.CONNECT_WORKER=5]="CONNECT_WORKER",t[t.WORKER_CONNECTED=6]="WORKER_CONNECTED",t[t.CLOSED=7]="CLOSED",t}({}),he=function(t){return t.CALL="call",t.CANDIDATE="candidate",t.PUBLISH="publish",t.UNPUBLISH="unpublish",t.CONTROL="control",t.RESTART_ICE="restart_ice",t.ACK="ack",t.RESPONSE="response",t.JOIN="join",t.CHECK="check",t}({}),ya=function(t){return t.ABORT="abort",t}({}),go=function(t){return t.MUTE_LOCAL_AUDIO="mute_local_audio",t.MUTE_LOCAL_VIDEO="mute_local_video",t.UNMUTE_LOCAL_AUDIO="unmute_local_audio",t.UNMUTE_LOCAL_VIDEO="unmute_local_video",t}({}),rW=function(t){return t.P2P_TOKEN_TIMEOUT="p2p_token_timeout",t.P2P_TOKEN_CHANGED="p2p_token_changed",t}({});const oW={[Pu.ACCESS_POINT]:{[hi.NO_FLAG_SET]:{desc:"flag is zero",retry:!1},[hi.FLAG_SET_BUT_EMPTY]:{desc:"flag is empty",retry:!1},[hi.INVALID_FALG_SET]:{desc:"invalid flag",retry:!1},[hi.FLAG_SET_BUT_NO_RE]:{desc:"flag set unilbs but no request",retry:!1},[hi.INVALID_SERVICE_ID]:{desc:"invalid service id",retry:!1},[hi.NO_SERVICE_AVAILABLE]:{desc:"no service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_P2P]:{desc:"no unilbs p2p service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_VOICE]:{desc:"no unilbs voice service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_WEBRTC]:{desc:"no unilbs webrtc service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_CDS]:{desc:"no cds service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_CDN]:{desc:"no cdn dispatcher service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_TDS]:{desc:"no tds service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_REPORT]:{desc:"no unilbs report service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_APP_CENTER]:{desc:"no app center service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_ENV0]:{desc:"no unilbs sig env0 service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_VOET]:{desc:"no unilbs voet service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_STRING_UID]:{desc:"no string uid service available",retry:!0},[hi.NO_SERVICE_AVAILABLE_WEBRTC_UNILBS]:{desc:"no webrtc unilbs service available",retry:!0}},[Pu.UNILBS]:{[Dn.INVALID_VENDOR_KEY]:{desc:"invalid vendor key, can not find appid",retry:!1},[Dn.INVALID_CHANNEL_NAME]:{desc:"invalid channel name",retry:!1},[Dn.INTERNAL_ERROR]:{desc:"unilbs internal error",retry:!1},[Dn.NO_AUTHORIZED]:{desc:"invalid token, authorized failed",retry:!1},[Dn.DYNAMIC_KEY_TIMEOUT]:{desc:"dynamic key or token timeout",retry:!1},[Dn.NO_ACTIVE_STATUS]:{desc:"no active status",retry:!1},[Dn.DYNAMIC_KEY_EXPIRED]:{desc:"dynamic key expired",retry:!1},[Dn.STATIC_USE_DYNAMIC_KEY]:{desc:"static use dynamic key",retry:!1},[Dn.DYNAMIC_USE_STATIC_KEY]:{desc:"dynamic use static key",retry:!1},[Dn.USER_OVERLOAD]:{desc:"amount of users over load",retry:!1},[Dn.FORBIDDEN_REGION]:{desc:"the request is forbidden in this area",retry:!1},[Dn.CANNOT_MEET_AREA_DEMAND]:{desc:"unable to allocate services in this area",retry:!1}},[Pu.STRING_UID_ALLOCATOR]:{[Cm.IIIEGAL_APPID]:{desc:"invalid appid",retry:!1},[Cm.IIIEGAL_UID]:{desc:"invalid string uid",retry:!1},[Cm.INTERNAL_ERROR]:{desc:"string uid allocator internal error",retry:!0}}};function Ia(t){const e=oW[Math.floor(t/1e4)];if(!e)return{desc:"unknown error",retry:!1};const i=e[t%1e4];if(!i){if(Math.floor(t/1e4)===Pu.ACCESS_POINT){const n=t%1e4;if(n.toString()[0]==="1")return{desc:t.toString(),retry:!1};if(n.toString()[0]==="2")return{desc:t.toString(),retry:!0}}return{desc:"unknown error",retry:!1}}return i}const sW={[tt.K_TIMESTAMP_EXPIRED]:{desc:"K_TIMESTAMP_EXPIRED",action:"failed"},[tt.K_CHANNEL_PERMISSION_INVALID]:{desc:"K_CHANNEL_PERMISSION_INVALID",action:"failed"},[tt.K_CERTIFICATE_INVALID]:{desc:"K_CERTIFICATE_INVALID",action:"failed"},[tt.K_CHANNEL_NAME_EMPTY]:{desc:"K_CHANNEL_NAME_EMPTY",action:"failed"},[tt.K_CHANNEL_NOT_FOUND]:{desc:"K_CHANNEL_NOT_FOUND",action:"failed"},[tt.K_TICKET_INVALID]:{desc:"K_TICKET_INVALID",action:"failed"},[tt.K_CHANNEL_CONFLICTED]:{desc:"K_CHANNEL_CONFLICTED",action:"failed"},[tt.K_SERVICE_NOT_READY]:{desc:"K_SERVICE_NOT_READY",action:"tryNext"},[tt.K_SERVICE_TOO_HEAVY]:{desc:"K_SERVICE_TOO_HEAVY",action:"tryNext"},[tt.K_UID_BANNED]:{desc:"K_UID_BANNED",action:"failed"},[tt.K_IP_BANNED]:{desc:"K_IP_BANNED",action:"failed"},[tt.DATASTREAM2_NOT_AVAILABLE]:{desc:"DATASTREAM2_NOT_AVAILABLE",action:"quit"},[tt.K_AUTO_REBALANCE]:{desc:"k_AUTO_REBALANCE",action:"recover"},[tt.ERR_INVALID_VENDOR_KEY]:{desc:"ERR_INVALID_VENDOR_KEY",action:"failed"},[tt.ERR_INVALID_CHANNEL_NAME]:{desc:"ERR_INVALID_CHANNEL_NAME",action:"failed"},[tt.WARN_NO_AVAILABLE_CHANNEL]:{desc:"WARN_NO_AVAILABLE_CHANNEL",action:"failed"},[tt.WARN_LOOKUP_CHANNEL_TIMEOUT]:{desc:"WARN_LOOKUP_CHANNEL_TIMEOUT",action:"tryNext"},[tt.WARN_LOOKUP_CHANNEL_REJECTED]:{desc:"WARN_LOOKUP_CHANNEL_REJECTED",action:"failed"},[tt.WARN_OPEN_CHANNEL_TIMEOUT]:{desc:"WARN_OPEN_CHANNEL_TIMEOUT",action:"tryNext"},[tt.WARN_OPEN_CHANNEL_REJECTED]:{desc:"WARN_OPEN_CHANNEL_REJECTED",action:"failed"},[tt.WARN_REQUEST_DEFERRED]:{desc:"WARN_REQUEST_DEFERRED",action:"failed"},[tt.ERR_DYNAMIC_KEY_TIMEOUT]:{desc:"ERR_DYNAMIC_KEY_TIMEOUT",action:"failed"},[tt.ERR_NO_AUTHORIZED]:{desc:"ERR_NO_AUTHORIZED",action:"failed"},[tt.ERR_VOM_SERVICE_UNAVAILABLE]:{desc:"ERR_VOM_SERVICE_UNAVAILABLE",action:"tryNext"},[tt.ERR_NO_CHANNEL_AVAILABLE_CODE]:{desc:"ERR_NO_CHANNEL_AVAILABLE_CODE",action:"failed"},[tt.ERR_MASTER_VOCS_UNAVAILABLE]:{desc:"ERR_MASTER_VOCS_UNAVAILABLE",action:"tryNext"},[tt.ERR_INTERNAL_ERROR]:{desc:"ERR_INTERNAL_ERROR",action:"tryNext"},[tt.ERR_NO_ACTIVE_STATUS]:{desc:"ERR_NO_ACTIVE_STATUS",action:"failed"},[tt.ERR_INVALID_UID]:{desc:"ERR_INVALID_UID",action:"failed"},[tt.ERR_DYNAMIC_KEY_EXPIRED]:{desc:"ERR_DYNAMIC_KEY_EXPIRED",action:"failed"},[tt.ERR_STATIC_USE_DYANMIC_KE]:{desc:"ERR_STATIC_USE_DYANMIC_KE",action:"failed"},[tt.ERR_DYNAMIC_USE_STATIC_KE]:{desc:"ERR_DYNAMIC_USE_STATIC_KE",action:"failed"},[tt.ERR_NO_VOCS_AVAILABLE]:{desc:"ERR_NO_VOCS_AVAILABLE",action:"tryNext"},[tt.ERR_NO_VOS_AVAILABLE]:{desc:"ERR_NO_VOS_AVAILABLE",action:"tryNext"},[tt.ERR_JOIN_CHANNEL_TIMEOUT]:{desc:"ERR_JOIN_CHANNEL_TIMEOUT",action:"tryNext"},[tt.ERR_JOIN_BY_MULTI_IP]:{desc:"ERR_JOIN_BY_MULTI_IP",action:"recover"},[tt.ERR_NOT_JOINED]:{desc:"ERR_NOT_JOINED",action:"failed"},[tt.ERR_REPEAT_JOIN_REQUEST]:{desc:"ERR_REPEAT_JOIN_REQUEST",action:"quit"},[tt.ERR_REPEAT_JOIN_CHANNEL]:{desc:"ERR_REPEAT_JOIN_CHANNEL",action:"quit"},[tt.ERR_INVALID_STRINGUID]:{desc:"ERR_INVALID_STRINGUID",action:"failed"},[tt.ERR_TOO_MANY_USERS]:{desc:"ERR_TOO_MANY_USERS",action:"tryNext"},[tt.ERR_SET_CLIENT_ROLE_TIMEOUT]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[tt.ERR_SET_CLIENT_ROLE_NO_PERMISSION]:{desc:"ERR_SET_CLIENT_ROLE_TIMEOUT",action:"failed"},[tt.ERR_SET_CLIENT_ROLE_ALREADY_IN_USE]:{desc:"ERR_SET_CLIENT_ROLE_ALREADY_IN_USE",action:"success"},[tt.ERR_PUBLISH_REQUEST_INVALID]:{desc:"ERR_PUBLISH_REQUEST_INVALID",action:"failed"},[tt.ERR_SUBSCRIBE_REQUEST_INVALID]:{desc:"ERR_SUBSCRIBE_REQUEST_INVALID",action:"failed"},[tt.ERR_NOT_SUPPORTED_MESSAGE]:{desc:"ERR_NOT_SUPPORTED_MESSAGE",action:"failed"},[tt.ERR_ILLEAGAL_PLUGIN]:{desc:"ERR_ILLEAGAL_PLUGIN",action:"failed"},[tt.ILLEGAL_CLIENT_ROLE_LEVEL]:{desc:"ILLEGAL_CLIENT_ROLE_LEVEL",action:"failed"},[tt.ERR_REJOIN_TOKEN_INVALID]:{desc:"ERR_REJOIN_TOKEN_INVALID",action:"failed"},[tt.ERR_REJOIN_USER_NOT_JOINED]:{desc:"ERR_REJOIN_NOT_JOINED",action:"failed"},[tt.ERR_INVALID_OPTIONAL_INFO]:{desc:"ERR_INVALID_OPTIONAL_INFO",action:"quit"},[tt.ERR_TEST_RECOVER]:{desc:"ERR_TEST_RECOVER",action:"recover"},[tt.ERR_TEST_TRYNEXT]:{desc:"ERR_TEST_TRYNEXT",action:"recover"},[tt.ERR_TEST_RETRY]:{desc:"ERR_TEST_RETRY",action:"recover"},[tt.ILLEGAL_AES_PASSWORD]:{desc:"ERR_TEST_RETRY",action:"failed"},[tt.ERR_TOO_MANY_BROADCASTERS]:{desc:"ERR_TOO_MANY_BROADCASTERS",action:"failed"},[tt.ERR_TOO_MANY_SUBSCRIBERS]:{desc:"ERR_TOO_MANY_SUBSCRIBERS",action:"failed"},[tt.ERR_LICENSE_ILLEGAL]:{desc:"ERR_LICENSE_ILLEGAL",action:"quit"},[tt.ERR_LICENSE_MISSING]:{desc:"ERR_LICENSE_MISSING",action:"quit"},[tt.ERR_LICENSE_EXPIRED]:{desc:"ERR_LICENSE_EXPIRED",action:"quit"},[tt.ERR_LICENSE_MINUTES_EXCEEDED]:{desc:"ERR_LICENSE_MINUTES_EXCEEDED",action:"quit"},[tt.ERR_LICENSE_PERIOD_INVALID]:{desc:"ERR_LICENSE_PERIOD_INVALID",action:"quit"},[tt.ERR_LICENSE_MULTIPLE_SDK_SERVICE]:{desc:"ERR_LICENSE_MULTIPLE_SDK_SERVICE",action:"quit"}};function jc(t){return sW[t]||{desc:"UNKNOWN_ERROR_".concat(t),action:"failed"}}function aw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function bm(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?aw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):aw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}function wm(t,e){if(typeof t=="string")return t;const{proxy:i,host:n,port:r}=t;if(e){const o=y("JOIN_GATEWAY_FALLBACK_PORT")||443;return o===443?"wss://".concat(n,"/ws/?p=").concat(Number(r)+150):"wss://".concat(n,":").concat(o,"/ws/?p=").concat(Number(r)+150)}return i?"wss://".concat(i,"/ws/?h=").concat(n,"&p=").concat(r):"wss://".concat(n,":").concat(r)}const aW=/wss:\/\/(.+)\/ws\/\?h=(.+)&p=([0-9]+)\/?/,cW=/wss:\/\/(.+)\/ws\/\?p=([0-9]+)\/?/,dW=/wss:\/\/(.+):([0-9]+)\/?/,lW=/wss:\/\/(.[^\/]+)\/?/;let uW=0;class hW{constructor(e,i){S(this,"id",0),S(this,"store",void 0),S(this,"recordIndex",void 0),S(this,"websockets",[]),S(this,"try443PortDuration",2e3),S(this,"forceCloseWSDuration",5e3),S(this,"try443PortTimeout",null),S(this,"forceCloseTimeout",null),S(this,"isTry443PortFailed",!1),S(this,"isNormalPortFailed",!1),S(this,"useDoubleDomain",!1),S(this,"useProxy",!1),S(this,"startTime",Date.now()),this.id=++uW,this.try443PortDuration=y("JOIN_GATEWAY_TRY_443PORT_DURATION")||2e3,this.forceCloseWSDuration=e||5e3,this.store=i}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 i=Date.now()-this.startTime;for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];_.debug("[choose-best-ws ".concat((e=this.store)===null||e===void 0?void 0:e.clientId," ").concat(this.id,"] ").concat(i,"ms:"),...r)}createWebSocket(e,i,n){this.logger("createWebSocket:",e,{isTry443Port:i,hasTimeoutDetection:n});const r=y("GATEWAY_DOMAINS"),o=Date.now(),s=[],a=r.find(h=>{var p;return G(p=e.host).call(p,h)});a||(this.useDoubleDomain=!1);const c=[];if(this.useDoubleDomain)r.forEach(h=>{c.push(wm(bm(bm({},e),{},{host:e.host.replace(a,h)}),i))});else{const h=bm({},e);if(i&&a){const p=r.find(g=>g!==a);p&&(h.host=h.host.replace(a,p))}c.push(wm(h,i))}try{c.forEach(h=>{const p=new WebSocket(h);p.binaryType="arraybuffer",s.push(p),this.logger("ws is connecting:",p.url)})}catch(h){if(this.logger("ws create failed"),s.forEach(p=>p.close()),s.length=0,this.useDoubleDomain)return this.useDoubleDomain=!1,this.createWebSocket(e,i,n);if(!i&&Number(e.port)!==443)return this.createWebSocket(e,!0,n);throw new P(v.WS_ERR,"init websocket failed! Error: ".concat(h.toString()))}const d=Ic();this.store&&this.store.recordJoinChannelService({urls:s.map(h=>h.url),service:"gateway"},this.recordIndex),s.forEach(h=>{h.onopen=()=>{this.logger("onopen: ws ".concat(h.url," open cost ").concat(Date.now()-o,"ms")),this.websockets.forEach(p=>{p!==h&&(p.onopen=null,p.onclose=null,p.onmessage=null,p.close(),this.logger("close backup websocket: ".concat(p.url)))}),this.websockets.length=0,d.resolve(h)},h.onclose=p=>{this.logger("onclose: ws ".concat(h.url," closed cost ").concat(Date.now()-o,"ms state: ").concat(h.readyState));const g=s.every(m=>m.readyState===WebSocket.CLOSED||m.readyState===WebSocket.CLOSING);this.logger("".concat(i?"443":"47xx"," websocket closed, all failed: ").concat(g)),g&&(i||this.isTry443PortFailed||this.useProxy)?(this.logger("onclose: all websocket is closed, ".concat(p.reason)),d.reject({code:p.code,reason:Mu.A_ROUND_WS_FAILED})):!i&&g&&!this.isNormalPortFailed&&this.try443PortTimeout&&(this.logger("all 47xx websocket is closed, try 443 port"),this.clearTimeout(),u()),i?this.isTry443PortFailed=g:this.isNormalPortFailed=g},h.onmessage=p=>this.logger("".concat(h.url," onmessage: ").concat(p.data))}),this.websockets.push(...s);const l=()=>{this.websockets.forEach(h=>h.readyState!==WebSocket.OPEN&&h.close())},u=()=>{if(d.isResolved)return l();vt().os===we.MAC_OS&&ne()&&l(),this.createWebSocket(e,!0,!0).then(h=>{d.resolve(h)}).catch(h=>{this.isNormalPortFailed&&d.reject(h),this.logger("try 443 port to create ws failed")}),this.forceCloseTimeout=window.setTimeout(()=>{this.logger("5s timeout close un-opens, isWebsocket created: ",d.isResolved),this.forceCloseTimeout=null,l()},this.forceCloseWSDuration)};return n||(()=>{if(i||this.useProxy)return this.logger("add 5s timeout at ".concat(i?"try-443":"proxy"," condition")),this.forceCloseTimeout=window.setTimeout(()=>{this.forceCloseTimeout=null,l()},this.forceCloseWSDuration);this.try443PortTimeout=window.setTimeout(()=>{this.logger("2s timeout, isWebsocket created: ",d.isResolved),this.try443PortTimeout=null,u()},this.try443PortDuration)})(),d.promise}chooseBestWebsocket(e,i,n,r){return this.useDoubleDomain=!!i,typeof e=="string"&&(e=function(o){let s,a,c;return[,s,a,c]=o.match(aW)||[],s||([,a,c]=o.match(cW)||[]),a&&c||([,a,c]=o.match(dW)||[]),a&&c||([,a]=o.match(lW)||[]),a||_.warning("un-destructible url: ",o),{proxy:s,host:a,port:c||"443"}}(e)),this.recordIndex=r,this.useProxy=!!e.proxy,n&&this.useProxy&&(_.warn("cannot use 443 only when use proxy"),n=!1),this.createWebSocket(e,!!n,!1).finally(()=>this.clearTimeout())}}function cw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}class dw extends $t{get url(){return this.websocket&&this.websocket.url||this._websocketUrl}get reconnectMode(){return this._reconnectMode}set reconnectMode(e){var i;G(i=["tryNext","recover"]).call(i,e)&&this.resetReconnectCount(e),this._reconnectMode=e}get state(){return this._state}set state(e){e!==this._state&&(this._state=e,this._state==="reconnecting"?this.emit(dt.RECONNECTING,this.reconnectReason):this._state==="connected"?this.emit(dt.CONNECTED):this._state==="closed"?this.emit(dt.CLOSED):this._state==="failed"&&this.emit(dt.FAILED))}resetReconnectCount(e){_.debug("websocket reset reconnect count, reason: "+e),this.reconnectCount=0}constructor(e,i){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],o=arguments.length>4&&arguments[4]!==void 0&&arguments[4],s=arguments.length>5?arguments[5]:void 0;super(),S(this,"_websocketUrl",null),S(this,"connectionID",0),S(this,"currentURLIndex",0),S(this,"urls",[]),S(this,"_reconnectMode","tryNext"),S(this,"reconnectReason",void 0),S(this,"_initMutex",void 0),S(this,"name",void 0),S(this,"_state","closed"),S(this,"reconnectInterrupter",void 0),S(this,"websocket",void 0),S(this,"retryConfig",void 0),S(this,"reconnectCount",0),S(this,"forceCloseTimeout",5e3),S(this,"onlineReconnectListener",void 0),S(this,"useCompress",void 0),S(this,"tryDoubleDomain",!1),S(this,"use443PortOnly",!1),S(this,"wsInflateLength",0),S(this,"wsDeflateLength",0),S(this,"closeEstablishingWs",()=>{}),S(this,"store",void 0),S(this,"joinGatewayRecordIndex",void 0),this.store=s,this.name=e,this.retryConfig=function(u){for(var h=1;h<arguments.length;h++){var p=arguments[h]!=null?arguments[h]:{};h%2?cw(Object(p),!0).forEach(function(g){S(u,g,p[g])}):Object.getOwnPropertyDescriptors?Object.defineProperties(u,Object.getOwnPropertyDescriptors(p)):cw(Object(p)).forEach(function(g){Object.defineProperty(u,g,Object.getOwnPropertyDescriptor(p,g))})}return u}({},i),this.useCompress=n,this.tryDoubleDomain=r,this.use443PortOnly=o,this._initMutex=new qe("websocket",s?s.clientId:void 0);const{timeout:a,timeoutFactor:c}=i,d=Math.max(300,Math.floor(3*a/5)),l=Math.max(1.2,Math.floor(8*c)/10);Fi.ONLINE&&(this.retryConfig.timeout=d,this.retryConfig.timeoutFactor=l),Ee.on(ra.NETWORK_STATE_CHANGE,(u,h)=>{u!==h&&(this.resetReconnectCount("network state change: ".concat(h," -> ").concat(u)),u===Fi.ONLINE?(this.retryConfig.timeout=d,this.retryConfig.timeoutFactor=l):(this.retryConfig.timeout=a,this.retryConfig.timeoutFactor=c))})}getConnection(){return this.websocket||void 0}init(i){return C(this,arguments,function*(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const r=yield this._initMutex.lock();this._reconnectMode="tryNext",this.forceCloseTimeout=n,this.urls=e,this.state="connecting";try{const o=Ic(),s=this.urls[this.currentURLIndex];y("ENABLE_PREALLOC_PC")&&this.emit(sw.PRE_CONNECT_PC),this.createWebSocketConnection(s).then(o.resolve).catch(o.reject),this.once(dt.CLOSED,()=>{o.reject(new k(v.WS_DISCONNECT))}),this.once(dt.CONNECTED,o.resolve),yield o.promise}catch(o){}finally{r()}})}close(e,i){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 n=this.websocket;i?setTimeout(()=>n.close(),500):n.close(),this.websocket=void 0,this._websocketUrl=null}this.state=e?"failed":"closed",this.closeEstablishingWs&&this.closeEstablishingWs()}reconnect(e,i){if(!this.websocket)return void _.warning("[".concat(this.name,"] can not reconnect, no websocket"));e!==void 0&&(this.reconnectMode=e),_.debug("[".concat(this.name,"] reconnect is triggered initiative")),typeof this.joinGatewayRecordIndex=="number"&&this.store&&this.store.recordJoinChannelService({status:"error",errors:[new Error(i)]},this.joinGatewayRecordIndex);const n=this.websocket.onclose;this.websocket.onclose=null,this.websocket.close(),n&&n.bind(this.websocket)({code:9999,reason:i})}sendMessage(e){let i=arguments.length>2&&arguments[2]!==void 0&&arguments[2];if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new k(v.WS_ABORT,"websocket is not ready");try{i||(e=JSON.stringify(e)),this.websocket.send(e)}catch(n){throw new k(v.WS_ERR,"send websocket message error"+n.toString())}}setWsInflateData(e){this.wsDeflateLength=this.wsDeflateLength+e.originLength,this.wsInflateLength=this.wsInflateLength+e.compressedLength}getWsInflateData(){const e=this.wsInflateLength,i=this.wsDeflateLength;return this.clearWsInflateData(),{wsInflateLength:e,wsDeflateLength:i}}clearWsInflateData(){this.wsInflateLength=0,this.wsDeflateLength=0}createWebSocketConnection(e){return C(this,null,function*(){var i;const n=Ic();this.connectionID+=1,this.joinGatewayRecordIndex=void 0;const r=l=>{var u;(u=this.store)===null||u===void 0||u.signalChannelOpen(),_.debug("[".concat(this.name,"] websocket opened:"),l),this.reconnectMode="retry",this.state="connected",this.resetReconnectCount("opened"),n.resolve()},o=l=>C(this,null,function*(){var u;if(_.debug("[".concat(this.name,"] websocket close ").concat((u=this.websocket)===null||u===void 0?void 0:u.url,", code: ").concat(l.code,", reason: ").concat(l.reason,", current mode: ").concat(this.reconnectMode)),this.reconnectCount>=this.retryConfig.maxRetryCount)n.reject(new k(v.WS_DISCONNECT,"websocket close: ".concat(l.code))),this.close();else{this.state==="connected"&&(this.reconnectReason=l.reason,this.state="reconnecting");const h=zi(this,dt.WILL_RECONNECT,this.reconnectMode,l.reason)||this.reconnectMode,p=yield this.reconnectWithAction(h);if(this.state==="closed")return void _.debug("[".concat(this.connectionID,"] ws is closed, no need to reconnect"));if(!p)return n.reject(new k(v.WS_DISCONNECT,"websocket reconnect failed: ".concat(l.code))),this.close(!0);n.resolve()}}),s=l=>{this.emit(dt.ON_MESSAGE,l)},a=l=>{_.warn("[".concat(this.connectionID,"] ws open error ").concat(l))};this.websocket&&(this.websocket.onclose=null,this.websocket.close()),y("GATEWAY_WSS_ADDRESS")&&this.name.startsWith("gateway")&&(e=y("GATEWAY_WSS_ADDRESS")),_.debug("[".concat(this.name,"] start connect, url:"),e);const c=(i=this.store)===null||i===void 0?void 0:i.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"gateway"});try{var d;this._websocketUrl=wm(e);const l=yield this.chooseBestWebsocketConnection(e);this.websocket=l,r&&r(this.websocket.url),this.websocket.onclose=o,this.websocket.onmessage=s,this.websocket.onerror=a,(d=this.store)===null||d===void 0||d.recordJoinChannelService({endTs:Date.now(),status:"success"},c),this.joinGatewayRecordIndex=c}catch(l){const u=this.state==="closed",h=l instanceof k,p=h&&l.code===v.WS_ABORT,g=h&&l.code===v.WS_ERR,m=h?l.message:l&&(l.reason||l.toString());_.warning("[choose-best-ws] chooseBestWebsocket error: ".concat(m)),this.store&&this.store.recordJoinChannelService({endTs:Date.now(),status:p?"aborted":"error",errors:[l]},c),u||g?(n.reject(u?new k(v.WS_DISCONNECT,"websocket is closed: ".concat(m)):new k(v.WS_ERR,"init websocket failed: ".concat(m))),g&&_.error("[".concat(this.name,"] init websocket failed: ").concat(m))):o&&o(l)}return n.promise})}reconnectWithAction(i){return C(this,arguments,function*(e){let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(this.reconnectCount>=this.retryConfig.maxRetryCount||this.urls.length===0||this.state==="closed")return!1;_.warning("[choose-best-ws] action: =>",e),this.onlineReconnectListener||Ee.isOnline||!Ee.onlineWaiter||(this.onlineReconnectListener=Ee.onlineWaiter.then(()=>{this.onlineReconnectListener=void 0}));let r=!0;if(this.reconnectInterrupter=()=>r=!1,n){const a=FE(this.reconnectCount,this.retryConfig);_.debug("[".concat(this.name,"] wait ").concat(a,"ms to reconnect websocket, mode: ").concat(e)),yield K.race([Ue(a),this.onlineReconnectListener||new K(()=>{})])}if(this._state==="closed"||!r)return!1;this.reconnectCount+=1;const o=(a,c)=>C(this,null,function*(){this.emit(dt.RECONNECT_CREATE_CONNECTION,c),yield this.createWebSocketConnection(a)});try{if(e==="retry")yield o(this.urls[this.currentURLIndex],e);else if(e==="tryNext"){if(this.currentURLIndex+=1,this.currentURLIndex>=this.urls.length)return this.reconnectWithAction("recover",!1);_.debug("[".concat(this.name,"] websocket url length: ").concat(this.urls.length," current index: ").concat(this.currentURLIndex)),yield o(this.urls[this.currentURLIndex],e)}else e==="recover"&&(_.debug("[".concat(this.name,"] request new urls")),this.resetReconnectCount("recover mode"),this.urls=yield We(this,dt.REQUEST_NEW_URLS),this.currentURLIndex=0,yield o(this.urls[this.currentURLIndex],e))}catch(a){var s;_.error("[".concat(this.name,"] reconnect failed ").concat(a&&a.toString()));const c=a==null||(s=a.data)===null||s===void 0?void 0:s.desc;return Array.isArray(c)&&G(c).call(c,"dynamic key expired")?(this.emit(dt.ON_TOKEN_PRIVILEGE_DID_EXPIRE),!1):this.reconnectWithAction(e,n)}return!0})}}class Om extends dw{constructor(e,i){super(e,i,arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3&&arguments[3]!==void 0&&arguments[3],arguments.length>4&&arguments[4]!==void 0&&arguments[4],arguments.length>5?arguments[5]:void 0)}chooseBestWebsocketConnection(e,i){return C(this,null,function*(){const n=Ic(),r=function(s,a){return new hW(s,a)}(this.forceCloseTimeout,this.store);this.closeEstablishingWs=()=>{_.debug("[choose-best-ws] close establishing websockets"),r.closeAllWebsockets(),n.reject(new k(v.WS_ABORT,"choose best websocket aborted"))};const o=y("GATEWAY_DOMAINS");return _.debug("[choose-best-ws] currentDomain: ",e,", domains: ",o,"total: ".concat(this.urls.length),"current: ".concat(this.currentURLIndex+1)),r.chooseBestWebsocket(e,this.tryDoubleDomain,this.use443PortOnly,i).then(n.resolve).catch(n.reject),n.promise.finally(()=>{this.closeEstablishingWs=void 0})})}}class Gc extends dw{constructor(e,i){super(e,i,arguments.length>2&&arguments[2]!==void 0&&arguments[2],arguments.length>3&&arguments[3]!==void 0&&arguments[3],arguments.length>4&&arguments[4]!==void 0&&arguments[4],arguments.length>5?arguments[5]:void 0)}chooseBestWebsocketConnection(e,i){return C(this,null,function*(){return new K((n,r)=>{let o=!1;const s=[];this.closeEstablishingWs=()=>{_.debug("[choose-best-ws] close establishing websockets"),s.forEach(g=>{g.onclose=null,g.onopen=null,g.onmessage=null,g.close()}),r(new k(v.WS_ABORT,"choose best websocket aborted"))};const a=y("GATEWAY_DOMAINS");let c;const d=e.indexOf("?h="),l=a.find(g=>d!==-1?G(e).call(e,g,d):G(e).call(e,g));_.debug("[choose-best-ws] currentDomain: ",l,", domains: ",a);let u=!this.tryDoubleDomain||!l;if(!u&&l){var h;const g=Date.now();try{a.forEach(m=>{const f=d===-1?e.replace(l,m):e.substr(0,d)+e.substr(d).replace(l,m),T=new WebSocket(f);T.binaryType="arraybuffer",s.push(T),_.debug("[choose-best-ws] ws is connecting:",T.url)})}catch(m){for(_.debug("[choose-best-ws] ws create failed, fallback to single url"),s.forEach(f=>f.close());s.length;)s.pop();u=!0}(h=this.store)===null||h===void 0||h.recordJoinChannelService({urls:s.map(m=>m.url),service:"gateway"},i),s.forEach(m=>{m.onopen=()=>{if(o)return;const f=Date.now()-g;_.debug("[choose-best-ws] ws open cost ".concat(f,"ms")),s.filter(T=>T!==m).forEach(T=>{_.debug("[choose-best-ws]close backup websocket: ".concat(T.url)),T.close()}),o=!0,n(m)},m.onclose=f=>{c=f,!o&&(s.find(T=>!(T.readyState===WebSocket.CLOSED||T.readyState===WebSocket.CLOSING))||(_.debug("[choose-best-ws] all websocket is closed"),o=!0,r(c)))},m.onmessage=f=>{_.debug("[choose-best-ws]".concat(m.url," onmessage: ").concat(f.data))}}),Ue(this.forceCloseTimeout).then(()=>{s.forEach(m=>{m.readyState!==WebSocket.OPEN&&m.close()})})}if(u){var p;let g;_.debug("[choose-best-ws] use single url: ",e),(p=this.store)===null||p===void 0||p.recordJoinChannelService({urls:[e],service:"gateway"},i);try{g=new WebSocket(e),s.push(g),g.binaryType="arraybuffer"}catch(m){const f=new k(v.WS_ERR,"init websocket failed! Error: ".concat(m.toString()));return _.error("[".concat(this.name,"]").concat(f)),void r(f)}g.onopen=()=>{n(g)},g.onclose=m=>{r(m)},g.onmessage=m=>{_.debug("[choose-best-ws]".concat(g.url," onmessage: ").concat(m.data))},Ue(this.forceCloseTimeout).then(()=>{g&&g.readyState!==WebSocket.OPEN&&g.close()})}}).then(n=>(this.closeEstablishingWs=void 0,n)).catch(n=>{throw this.closeEstablishingWs=void 0,n})})}}class pW extends $t{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Ht.CONNECTED?this.emit(ot.WS_CONNECTED):e===Ht.RECONNECTING?this.emit(ot.WS_RECONNECTING,this._websocketReconnectReason):e===Ht.CLOSED&&this.emit(ot.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,i){super(),S(this,"_disconnectedReason",void 0),S(this,"_websocketReconnectReason",void 0),S(this,"_connectionState",Ht.CLOSED),S(this,"reconnectToken",void 0),S(this,"websocket",void 0),S(this,"openConnectionTime",void 0),S(this,"clientId",void 0),S(this,"lastMsgTime",Date.now()),S(this,"uploadCache",[]),S(this,"uploadCacheInterval",void 0),S(this,"rttRolling",new RI(5)),S(this,"pingpongTimer",void 0),S(this,"wsInflateDataTimer",void 0),S(this,"pingpongTimeoutCount",0),S(this,"joinResponse",void 0),S(this,"multiIpOption",void 0),S(this,"initError",void 0),S(this,"spec",void 0),S(this,"store",void 0),S(this,"onWebsocketMessage",n=>{if(n.data instanceof ArrayBuffer)return void this.emit(ot.ON_BINARY_DATA,n.data);const r=JSON.parse(n.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(r,"_id")){const o="res-@".concat(r._id);this.emit(o,r._result,r._message)}else if(Object.prototype.hasOwnProperty.call(r,"_type")){if(this.emit(r._type,r._message),r._type===mt.ON_NOTIFICATION&&this.handleNotification(r._message),r._type===mt.ON_USER_BANNED)switch(r._message.error_code){case 14:this.close(bt.UID_BANNED);break;case 15:this.close(bt.IP_BANNED);break;case 16:this.close(bt.CHANNEL_BANNED)}if(r._type===mt.ON_USER_LICENSE_BANNED)switch(r._message.error_code){case tt.ERR_LICENSE_MISSING:this.close(bt.LICENSE_MISSING);break;case tt.ERR_LICENSE_EXPIRED:this.close(bt.LICENSE_EXPIRED);break;case tt.ERR_LICENSE_MINUTES_EXCEEDED:this.close(bt.LICENSE_MINUTES_EXCEEDED);break;case tt.ERR_LICENSE_PERIOD_INVALID:this.close(bt.LICENSE_PERIOD_INVALID);break;case tt.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(bt.LICENSE_MULTIPLE_SDK_SERVICE);break;case tt.ERR_LICENSE_ILLEGAL:this.close(bt.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=e.clientId,this.spec=e,this.store=i,this.websocket=new Om("gateway-".concat(this.clientId),this.spec.retryConfig,!0,y("JOIN_GATEWAY_USE_DUAL_DOMAIN"),y("JOIN_GATEWAY_USE_443PORT_ONLY"),i),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===Ht.CONNECTED&&this.reconnect("retry",Ge.OFFLINE)})}request(e,i,n,r){return C(this,null,function*(){const o=Gt(6,""),s={_id:o,_type:e,_message:i},a=this.websocket.connectionID,c=()=>new K((g,m)=>{if(this.connectionState===Ht.CONNECTED)return g();const f=()=>{this.off(ot.WS_CLOSED,T),g()},T=()=>{this.off(ot.WS_CONNECTED,f),m(new P(v.WS_ABORT))};this.once(ot.WS_CONNECTED,f),this.once(ot.WS_CLOSED,T),e!==nt.PUBLISH&&e!==nt.PUBLISH_DATASTREAM&&e!==nt.SUBSCRIBE&&e!==nt.SUBSCRIBE_DATASTREAM&&e!==nt.UNSUBSCRIBE&&e!==nt.UNSUBSCRIBE_DATASTREAM&&e!==nt.UNPUBLISH&&e!==nt.UNPUBLISH_DATASTREAM&&e!==nt.CONTROL&&e!==nt.RESTART_ICE||this.once(ot.DISCONNECT_P2P,()=>{m(new P(v.DISCONNECT_P2P))}),e!==nt.PUBLISH&&e!==nt.RESTART_ICE||this.once(ot.ABORT_P2P_EXECUTION,()=>{m(new P(v.DISCONNECT_P2P))})});if(this.connectionState!==Ht.CONNECTING&&this.connectionState!==Ht.RECONNECTING||e===nt.JOIN||e===nt.REJOIN||(yield c()),this.websocket.sendMessage(s,!0),r)return;const d=new K((g,m)=>{let f=!1;const T=(A,N)=>{f=!0,g({isSuccess:A==="success",message:N||{}}),this.off(ot.WS_CLOSED,R),this.off(ot.WS_RECONNECTING,R),this.emit(ot.REQUEST_SUCCESS,e,i)};this.once("res-@".concat(o),T);const R=()=>{m(new P(v.WS_ABORT,"type: ".concat(e))),this.off(ot.WS_CLOSED,R),this.off(ot.WS_RECONNECTING,R),this.off("res-@".concat(o),T)};this.once(ot.WS_CLOSED,R),this.once(ot.WS_RECONNECTING,R),Ue(y("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==a||f||(_.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(ot.REQUEST_TIMEOUT,e,i))})});let l=null;try{l=yield d}catch(g){if(this.connectionState===Ht.CLOSED||e===nt.LEAVE)throw new P(v.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?g.throw():e===nt.JOIN||e===nt.REJOIN?null:(yield c(),yield this.request(e,i))}if(l.isSuccess)return l.message;const u=Number(l.message.error_code||l.message.code),h=jc(u),p=new P(v.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(l.message.error_str),{code:u,data:l.message,desc:h.desc});return h.action==="success"?l.message:(_.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(u,", message: ").concat(h.desc,", action: ").concat(h.action)),u===tt.ERR_TOO_MANY_BROADCASTERS?((e===nt.JOIN||e===nt.REJOIN)&&(this.initError=p,this.close()),p.throw()):h.action==="failed"?p.throw():h.action==="quit"?(this.initError=p,this.close(),p.throw()):(u===tt.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=l.message.option,_.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Ge.MULTI_IP)):this.reconnect(h.action,Ge.SERVER_ERROR),e===nt.JOIN||e===nt.REJOIN?null:yield this.request(e,i)))})}waitMessage(e,i){return new K(n=>{const r=o=>{(!i||i(o))&&(this.off(e,r),n(o))};this.on(e,r)})}uploadWRTCStats(e){if(!this.store.sessionId)return void _.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const i={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(Fc.WRTC_STATS,i)}upload(e,i){const n={_type:e,_message:i};try{this.websocket.sendMessage(n)}catch(r){const o=y("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>o&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==Ht.CONNECTED)return;const s=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(s._type,s._message)},y("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,i){const n={_type:e,_message:i};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 K((i,n)=>{this.once(ot.WS_CONNECTED,()=>i(this.joinResponse)),this.once(ot.WS_CLOSED,r=>n(this.initError||new P(v.WS_ABORT,r))),this.connectionState=Ht.CONNECTING,this.websocket.init(e).catch(n),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||bt.LEAVE,this.connectionState=Ht.CLOSED,_.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close()}join(){return C(this,null,function*(){if(!this.joinResponse){this.emit(ot.ABORT_P2P_EXECUTION);const e=yield We(this,ot.REQUEST_JOIN_INFO),i=yield this.request(nt.JOIN,e);if(!i)return this.emit(ot.REPORT_JOIN_GATEWAY,Mu.TIMEOUT,this.url||""),!1;this.joinResponse=i,this.emit(ot.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Ht.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0})}rejoin(){return C(this,null,function*(){if(!this.reconnectToken)throw new P(v.UNEXPECTED_ERROR,"can not rejoin, no rejoin token");const e=Dc(this,ot.REQUEST_REJOIN_INFO);e.token=this.reconnectToken;const i=yield this.request(nt.REJOIN,e);return!!i&&(this.connectionState=Ht.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),i.peers&&i.peers.forEach(n=>{this.emit(mt.ON_USER_ONLINE,{uid:n.uid}),n.audio&&this.emit(mt.ON_ADD_AUDIO_STREAM,{uid:n.uid,uint_id:n.uint_id,audio:!0,ssrcId:n.audio_ssrc}),n.video&&this.emit(mt.ON_ADD_VIDEO_STREAM,{uid:n.uid,uint_id:n.uint_id,video:!0,ssrcId:n.video_ssrc}),n.audio_mute?this.emit(mt.MUTE_AUDIO,{uid:n.uid}):this.emit(mt.UNMUTE_AUDIO,{uid:n.uid}),n.video_mute?this.emit(mt.MUTE_VIDEO,{uid:n.uid}):this.emit(mt.UNMUTE_VIDEO,{uid:n.uid}),n.audio_enable_local?this.emit(mt.ENABLE_LOCAL_AUDIO,{uid:n.uid}):this.emit(mt.DISABLE_LOCAL_AUDIO,{uid:n.uid}),n.video_enable_local?this.emit(mt.ENABLE_LOCAL_VIDEO,{uid:n.uid}):this.emit(mt.DISABLE_LOCAL_VIDEO,{uid:n.uid}),n.audio||n.video||this.emit(mt.ON_REMOVE_STREAM,{uid:n.uid,uint_id:n.uint_id})}),!0)})}reconnect(e,i){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,i)}handleNotification(e){_.debug("[".concat(this.clientId,"] receive notification: "),e);const i=jc(e.code);if(e.code===28&&"detail"in e&&(_.info("[".concat(this.clientId,"] receive recover notification: "),e.detail),this.emit(ot.RECOVER_NOTIFICATION,e.detail)),i.action!=="success"){if(i.action!=="failed")return i.action==="quit"?(i.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(bt.UID_BANNED),void this.close()):void this.reconnect(i.action,Ge.SERVER_ERROR);_.error("[".concat(this.clientId,"] ignore error: "),i.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=y("PING_PONG_TIME_OUT"),i=Date.now();this.pingpongTimeoutCount>=e&&(_.warning("[".concat(this.clientId,"] PING-PONG Timeout. Last Socket Message: ").concat(i-this.lastMsgTime,"ms")),i-this.lastMsgTime>y("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Ge.TIMEOUT):this.request(nt.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const n=Date.now()-i;this.rttRolling.add(n),y("REPORT_STATS")&&this.send(nt.PING_BACK,{pingpongElapse:n})}).catch(n=>{})}handleWsInflateData(){const{wsInflateLength:e,wsDeflateLength:i}=this.websocket.getWsInflateData();e!==0&&i!==0&&this.upload(Fc.WS_INFLATE_DATA_LENGTH,{ws_deflate_length:i,ws_inflate_length:e})}handleWebsocketEvents(){this.websocket.on(dt.RECONNECT_CREATE_CONNECTION,e=>{this.emit(ot.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(dt.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(dt.CLOSED,()=>{this.connectionState=Ht.CLOSED}),this.websocket.on(dt.FAILED,()=>{this._disconnectedReason=bt.NETWORK_ERROR,this.connectionState=Ht.CLOSED}),this.websocket.on(dt.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Ht.CONNECTED?this.connectionState=Ht.RECONNECTING:this.connectionState=Ht.CONNECTING}),this.websocket.on(dt.WILL_RECONNECT,(e,i,n)=>{const r=Dc(this,ot.IS_P2P_DISCONNECTED),o=r||e!=="retry";r&&e==="retry"&&(_.debug("".concat(this.clientId," reconnect mode is retry, but p2p lost, change to tryNext")),e="tryNext",i=Mu.P2P_DISCONNECTED),o&&(_.debug("".concat(this.clientId," will renewSession, reconnect mode: ").concat(e)),this.emit(ot.REPORT_JOIN_GATEWAY,i||Mu.UNKNOWN_REASON,this.url||""),this.reconnectToken=void 0,this.emit(ot.DISCONNECT_P2P)),n(e)}),this.websocket.on(dt.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.reconnectToken?this.rejoin().catch(e=>{_.warning("[".concat(this.clientId,"] rejoin failed ").concat(e)),this.reconnect("tryNext",Ge.SERVER_ERROR)}):this.join().catch(e=>{if(this.emit(ot.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof P){if(e.code===v.UNEXPECTED_RESPONSE&&e.data.code===tt.ERR_NO_AUTHORIZED)return this.initError=new P(v.TOKEN_EXPIRE,"dynamic key expired"),void this.close(bt.TOKEN_EXPIRE);_.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Ge.SERVER_ERROR):(this.initError=e,this.close())}})}),this.websocket.on(dt.REQUEST_NEW_URLS,(e,i)=>{We(this,ot.REQUEST_RECOVER,this.multiIpOption).then(e).catch(i)}),this.websocket.on(dt.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(mt.ON_TOKEN_PRIVILEGE_DID_EXPIRE)}),this.websocket.on(sw.PRE_CONNECT_PC,()=>{this.emit(ot.PRE_CONNECT_PC)})}}let _W=function(t){return t.NATIVE_RTC="native_rtc",t.NATIVE_RTM="native_rtm",t.WEB_RTC="web_rtc",t.WEB_RTM="web_rtm",t}({}),me=function(t){return t[t.CHOOSE_SERVER=11]="CHOOSE_SERVER",t[t.CLOUD_PROXY=18]="CLOUD_PROXY",t[t.CLOUD_PROXY_5=20]="CLOUD_PROXY_5",t[t.CLOUD_PROXY_FALLBACK=26]="CLOUD_PROXY_FALLBACK",t}({});function lw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function xu(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?lw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):lw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}function So(t){return t.match(/^[\.\:\d]+$/)?"".concat(t.replace(/[^\d]/g,"-"),".").concat(y("TURN_DOMAIN")):(_.debug("Cannot recognized as ip address: ".concat(t,", use as host")),t)}function Nm(t,e){t.addresses||(t.addresses=[]);const i=function(a,c){if(y("CONNECT_GATEWAY_WITHOUT_DOMAIN"))return a.map(u=>{let{ip:h,port:p}=u;return{address:"".concat(h,":").concat(p)}});const d=y("GATEWAY_DOMAINS");let l=d[1]&&G(c).call(c,d[1])?1:0;return a.map(u=>{let{domain_prefix:h,port:p,ip:g}=u;if(h)return{address:"".concat(h,".").concat(d[l++%d.length],":").concat(p)};const m=/^[\.\:\d]+$/.test(g),f=m?"".concat(g.replace(/[^\d]/g,"-"),".").concat(d[l++%d.length],":").concat(p):"".concat(g,":").concat(p);return m||_.debug("Cannot recognized as ip address: ".concat(g,", use as host")),{ip:g,port:p,address:f}})}(t.addresses,e),n=Array.isArray(t.detail)&&t.detail[18];if(n&&typeof n=="string"){const a=n.split(";");for(let c=0;c<a.length;c++){var r;const d=ni(r=a[c]).call(r);i[c]&&d&&(i[c].ip6=d)}}const o=t.detail&&t.detail.candidate;let s;if(o){const[a,c]=o.split(":");a&&c&&(s={port:Number(c),ip:a,address:"".concat(a,":").concat(c)})}return{gatewayAddrs:i,apGatewayAddress:s,uid:t.uid,cid:t.cid,cert:t.cert,vid:t.detail&&t.detail[8],uni_lbs_ip:t.detail&&t.detail[1],res:t,csIp:t.detail&&t.detail[502]}}function Bi(t){return typeof t=="number"?t:t.exact||t.ideal||t.max||t.min||0}function uw(t){const e=t._encoderConfig;if(!e)return{};const i={resolution:e.width&&e.height?"".concat(Bi(e.width),"x").concat(Bi(e.height)):void 0,maxVideoBW:e.bitrateMax,minVideoBW:e.bitrateMin};return typeof e.frameRate=="number"?(i.maxFrameRate=e.frameRate,i.minFrameRate=e.frameRate):e.frameRate&&(i.maxFrameRate=e.frameRate.max||e.frameRate.ideal||e.frameRate.exact||e.frameRate.min,i.minFrameRate=e.frameRate.min||e.frameRate.ideal||e.frameRate.exact||e.frameRate.max),i}function hw(t){return t>=0&&t<.17?1:t>=.17&&t<.36?2:t>=.36&&t<.59?3:t>=.59&&t<=1?4:t>1?5:0}function Wc(t,e){let i,n,r;switch(e){case me.CHOOSE_SERVER:n=4096,r="choose server";break;case me.CLOUD_PROXY:n=1048576,r="proxy";break;case me.CLOUD_PROXY_5:n=4194304,r="proxy5";break;case me.CLOUD_PROXY_FALLBACK:n=4194310,r="proxy fallback";break;default:throw new P(v.UNEXPECTED_ERROR,"multi unlibs response transformer get unknown service id",{csIp:t.detail&&t.detail[502],retry:!1})}if(t.response_body.forEach(o=>{o.buffer&&o.buffer.flag===n&&(i={code:o.buffer.code,addresses:(o.buffer.edges_services||[]).map(s=>xu(xu({},s),{},{ticket:o.buffer.cert})),server_ts:t.enter_ts,uid:o.buffer.uid,cid:o.buffer.cid,cname:o.buffer.cname,detail:xu(xu({},o.buffer.detail),t.detail),flag:o.buffer.flag,opid:t.opid,cert:o.buffer.cert})}),!i)throw new P(v.MULTI_UNILBS_RESPONSE_ERROR,"cannot parse response ".concat(r," from multi unilbs response"),{csIp:t.detail&&t.detail[502]});return i}function pw(t,e){return C(this,null,function*(){return yield K.all(t.addresses.map(i=>C(this,null,function*(){return{address:y("USE_TURN_IP")?i.ip:So(i.ip),tcpport:i.port,udpport:i.port,username:e&&y("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?e.toString():He.username,password:e&&y("ENCRYPT_PROXY_USERNAME_AND_PSW")&&window.isSecureContext?yield kE(e.toString()):He.password}})))})}function Dm(t,e){const i=e.getMediaStreamTrack(!0).getSettings(),n=e.videoHeight||i.height,r=e.videoWidth||i.width;return n&&r?Math.max(Math.min(n,r)/Math.min(Bi(t.height),Bi(t.width)),1):(_.warning("can't get ori-track's height, default scale down 4 times for low stream"),4)}function To(t){let{candidateType:e,relayProtocol:i,type:n,address:r,port:o,protocol:s}=t;const a={candidateType:e,relayProtocol:i,protocol:s};if(n!=="local-candidate"){const c=r.split(".");c.length>=4&&(c[1]="*",c[2]="*"),a.address=c.join("."),a.port=o}return a}function Vu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:y("SVC_MODE");if(y("ENABLE_SVC"))return function(e){return e in pu}(t)?t:pu.L1T3}const _w={[q.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"}],[q.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 Fu(t,e,i){e.forEach(n=>{var r;const o=_w[t].find(a=>{var c;let{key:d}=a;return G(c=n.extensionName).call(c,d)});if(!o)return;const s=i.find(a=>{let{extensionName:c}=a;return G(c).call(c,o.key)});s&&G(r=s.extensionName).call(r,"gdpr_forbidden")&&(n.extensionName=s.extensionName)})}function Aa(t,e){e.forEach(i=>{var n;const r=_w[t].find(o=>{var s;let{key:a}=o;return G(s=i.extensionName).call(s,a)});G(n=i.extensionName).call(n,"gdpr_forbidden")&&r&&(i.extensionName=r.extensionName)})}function Ew(t){return t==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"||G(t).call(t,"abs-send-time")}function Bu(t){return t==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"||G(t).call(t,"draft-holmer-rmcat-transport-wide-cc-extensions-01")}function mw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function fw(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?mw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):mw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}function Hc(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},n=arguments.length>3?arguments[3]:void 0;const{filterRTX:r,filterVideoFec:o,filterAudioFec:s,filterAudioCodec:a,filterVideoCodec:c}=e,{useXR:d}=i;let l=[],u=[],h=[],p=[],g=!1,m=!1;if(Ni(t).mediaDescriptions.forEach(T=>{n&&n!==T.attributes.direction||(T.media.mediaType!=="video"||g||(u=T.attributes.payloads,p=T.attributes.extmaps,g=!0),T.media.mediaType!=="audio"||m||(l=T.attributes.payloads,h=T.attributes.extmaps,m=!0))}),!p||u.length===0)throw new Error("Cannot get video capabilities from SDP.");if(!h||l.length===0)throw new Error("Cannot get audio capabilities from SDP.");if(u.forEach(T=>{var R;(R=T.rtpMap)!==null&&R!==void 0&&R.clockRate&&(T.rtpMap.clockRate=parseInt(T.rtpMap.clockRate)),d&&T.rtcpFeedbacks.push({type:"rrtr"})}),l.forEach(T=>{var R;(R=T.rtpMap)!==null&&R!==void 0&&R.clockRate&&(T.rtpMap.clockRate=parseInt(T.rtpMap.clockRate)),d&&T.rtcpFeedbacks.push({type:"rrtr"})}),r&&(l=l.filter(T=>{var R;return((R=T.rtpMap)===null||R===void 0?void 0:R.encodingName.toLowerCase())!=="rtx"}),u=u.filter(T=>{var R;return((R=T.rtpMap)===null||R===void 0?void 0:R.encodingName.toLowerCase())!=="rtx"})),o&&(u=u.filter(T=>{var R;return!/(red)|(ulpfec)|(flexfec)/i.test(((R=T.rtpMap)===null||R===void 0?void 0:R.encodingName)||"")})),s&&(l=l.filter(T=>{var R;return!/(red)|(ulpfec)|(flexfec)/i.test(((R=T.rtpMap)===null||R===void 0?void 0:R.encodingName)||"")})),a&&(a==null?void 0:a.length)>0&&(l=l.filter(T=>{var R;return G(a).call(a,((R=T.rtpMap)===null||R===void 0?void 0:R.encodingName.toLowerCase())||"")})),c&&(c==null?void 0:c.length)>0){const T=u.filter(R=>{var A;return G(c).call(c,((A=R.rtpMap)===null||A===void 0?void 0:A.encodingName.toLowerCase())||"")});u=T.concat(r?[]:km(T,u))}const f=y("UNSUPPORTED_VIDEO_CODEC");return f&&f.length>0&&(u=u.filter(T=>!(T.rtpMap&&G(f).call(f,T.rtpMap.encodingName.toLowerCase())))),{audioCodecs:l,videoCodecs:u,audioExtensions:h,videoExtensions:p}}function Ro(t){const e=Ni(t);let i,n;for(const r of e.mediaDescriptions){if(!i){const o=r.attributes.iceUfrag,s=r.attributes.icePwd;if(!o||!s)throw new Error("Cannot get iceUfrag or icePwd from SDP.");i={iceUfrag:o,icePwd:s}}if(!n){const o=r.attributes.fingerprints;o.length>0&&(n={fingerprints:o})}}if(!n&&e.attributes.fingerprints.length>0&&(n={fingerprints:e.attributes.fingerprints}),!n||!i)throw new Error("Cannot get iceParameters or dtlsParameters from SDP.");return{iceParameters:i,dtlsParameters:n}}function gw(t,e){const i=[],n=t.attributes.ssrcGroups.filter(s=>s.semantic==="FID"),r=t.attributes.ssrcGroups.find(s=>s.semantic==="SIM"),o=t.attributes.ssrcs;if(r)r.ssrcIds.forEach(s=>{var a;const c=(a=n.find(d=>d.ssrcIds[0]===s))===null||a===void 0?void 0:a.ssrcIds[1];i.push({ssrcId:s,rtx:e?c:void 0})});else if(n.length>0){const s=n[0].ssrcIds[0],a=n[0].ssrcIds[1];i.push({ssrcId:s,rtx:e?a:void 0})}else{if(o.length===0)throw new Error("No ssrcs found on local media description.");i.push({ssrcId:o[0].ssrcId})}return i}function Sw(t,e,i){const{cname:n}=t;let r=[];e&&(r=Tw(e)),r.length===0&&(r=t.iceParameters.candidates.map(l=>({foundation:l.foundation,componentId:"1",transport:l.protocol,priority:l.priority.toString(),connectionAddress:l.ip,port:l.port.toString(),type:l.type,extension:{}})),_.debug("Using candidates from gateway."));const o={fingerprints:t.dtlsParameters.fingerprints.map(l=>({hashFunction:l.algorithm,fingerprint:l.fingerprint}))},s={iceUfrag:t.iceParameters.iceUfrag,icePwd:t.iceParameters.icePwd};let a;switch(t.dtlsParameters.role){case"server":a="passive";break;case"client":a="active";break;case"auto":a="actpass"}const c=Gu(t.rtpCapabilities),d=[];return Array.isArray(i)&&i.length>0&&i.forEach(l=>{d.push({kind:q.VIDEO,ssrcId:l.v,rtx:l.v_rtx,mslabel:"".concat(l.v,"_").concat(l.a)},{kind:q.AUDIO,ssrcId:l.a,mslabel:"".concat(l.v,"_").concat(l.a)})}),{dtlsParameters:o,iceParameters:s,candidates:r,rtpCapabilities:c,setup:a,cname:n,preSSRCs:d}}function Tw(t){let e=[];return t.ip&&typeof t.port=="number"&&(e=[{foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip,port:t.port.toString(),type:"host",extension:{}}],_.debug("Using remote candidate from AP ".concat(t.ip,":").concat(t.port)),t.ip6&&(e.push({foundation:"udpcandidate",componentId:"1",transport:"udp",priority:"2103266323",connectionAddress:t.ip6,port:t.port.toString(),type:"host",extension:{}}),_.debug("Using IPV6 remote candidate from AP ".concat(t.ip6,":").concat(t.port)))),e}function as(t,e,i){const n=[],r=[];return t.forEach(o=>{let{ssrcId:s,rtx:a}=o;const c=Gt(8,"track-"),d={ssrcId:s,attributes:fw({label:c,mslabel:i=i||Gt(10,""),msid:"".concat(i," ").concat(c)},e&&{cname:e})};if(n.push(d),a!==void 0){const l={ssrcId:a,attributes:fw({label:c,mslabel:i,msid:"".concat(i," ").concat(c)},e&&{cname:e})};n.push(l),r.push({semantic:"FID",ssrcIds:[s,a]})}}),t.length>1&&r.push({semantic:"SIM",ssrcIds:t.map(o=>{let{ssrcId:s}=o;return s})}),{ssrcs:n,ssrcGroups:r}}function ba(t,e){e instanceof ae&&t.attributes.payloads.forEach(i=>{var n;const r=(n=i.rtpMap)===null||n===void 0?void 0:n.encodingName.toLowerCase();if(!r||["opus","pcmu","pcma","g722"].indexOf(r)===-1)return;i.fmtp||(i.fmtp={parameters:{}}),r==="opus"&&typeof y("OPUS_PTIME")=="number"?i.fmtp.parameters.ptime=y("OPUS_PTIME"):i.fmtp.parameters.minptime="10",i.fmtp.parameters.useinbandfec="1";const o=e._encoderConfig;o&&(r!=="pcmu"&&r!=="pcma"&&r!=="g722"&&(o.bitrate&&!ne()&&(i.fmtp.parameters.maxaveragebitrate="".concat(Math.floor(1e3*o.bitrate))),o.sampleRate&&(i.fmtp.parameters.maxplaybackrate="".concat(o.sampleRate),i.fmtp.parameters["sprop-maxcapturerate"]="".concat(o.sampleRate)),o.stereo&&(i.fmtp.parameters.stereo="1",i.fmtp.parameters["sprop-stereo"]="1")),e instanceof xc&&r==="opus"&&e._config.DTX&&(i.fmtp.parameters.usedtx="1"))})}function Pm(t){const e=t.attributes.unrecognized.findIndex(i=>i.attField==="x-google-flag"&&i.attValue==="conference");e!==-1&&t.attributes.unrecognized.splice(e,1)}function Lm(t,e){var i;if(!(e instanceof Yt&&e._encoderConfig&&e._hints.indexOf(Vt.SCREEN_TRACK)===-1))return;const n=e._encoderConfig;Ct().supportMinBitrate&&n.bitrateMin&&t.attributes.payloads.forEach(r=>{var o,s;G(o=["h264","h265","vp8","vp9","av1"]).call(o,((s=r.rtpMap)===null||s===void 0?void 0:s.encodingName.toLowerCase())||"")&&(r.fmtp||(r.fmtp={parameters:{}}),r.fmtp.parameters["x-google-min-bitrate"]="".concat(n.bitrateMin))}),Ct().supportMinBitrate&&!G(i=e._hints).call(i,Vt.LOW_STREAM)&&n.bitrateMax&&t.attributes.payloads.forEach(r=>{var o,s;G(o=["h264","h265","vp8","vp9","av1"]).call(o,((s=r.rtpMap)===null||s===void 0?void 0:s.encodingName.toLowerCase())||"")&&(r.fmtp||(r.fmtp={parameters:{}}),r.fmtp.parameters["x-google-start-bitrate"]="".concat(y("X_GOOGLE_START_BITRATE")||Math.floor(n.bitrateMax)))})}function Rw(t){if(t.media.mediaType!=="video")return;const e=vt();if(e.name!==It.SAFARI&&e.os!==we.IOS)return;const i=t.attributes.extmaps.findIndex(n=>/video-orientation/g.test(n.extensionName));i!==-1&&t.attributes.extmaps.splice(i,1)}function ju(t,e,i){if(!e)return;let n,r;if(t.media.mediaType==="video"?(n=i.videoExtensions,r=i.videoCodecs):(n=i.audioExtensions,r=i.audioCodecs),e.twcc===!0){const o=n.find(s=>Bu(s.extensionName));if(o){const s=o.extensionName;t.attributes.extmaps.find(c=>Bu(c.extensionName))||t.attributes.extmaps.push({entry:o.entry,extensionName:s}),function(c,d){return d.filter(l=>!!c.find(u=>u.payloadType===l.payloadType&&!!u.rtcpFeedbacks.find(h=>h.type==="transport-cc")))}(r,t.attributes.payloads).forEach(c=>{c.rtcpFeedbacks.find(d=>d.type==="transport-cc")||c.rtcpFeedbacks.push({type:"transport-cc"})})}}else if(e.twcc===!1){const o=t.attributes.extmaps.findIndex(s=>Bu(s.extensionName));o!==-1&&t.attributes.extmaps.splice(o,1),t.attributes.payloads.forEach(s=>{const a=s.rtcpFeedbacks.findIndex(c=>c.type==="transport-cc");a!==-1&&s.rtcpFeedbacks.splice(a,1)})}if(e.remb===!0){const o=n.find(s=>Ew(s.extensionName));if(o){const s=o.extensionName;t.attributes.extmaps.find(c=>c.extensionName===s)||t.attributes.extmaps.push({entry:o.entry,extensionName:s}),function(c,d){return d.filter(l=>!!c.find(u=>u.payloadType===l.payloadType&&!!u.rtcpFeedbacks.find(h=>h.type==="goog-remb")))}(r,t.attributes.payloads).forEach(c=>{c.rtcpFeedbacks.find(d=>d.type==="goog-remb")||c.rtcpFeedbacks.push({type:"goog-remb"})})}}else if(e.remb===!1){const o=t.attributes.extmaps.findIndex(s=>Ew(s.extensionName));o!==-1&&t.attributes.extmaps.splice(o,1),t.attributes.payloads.forEach(s=>{const a=s.rtcpFeedbacks.findIndex(c=>c.type==="goog-remb");a!==-1&&s.rtcpFeedbacks.splice(a,1)})}}function vw(t,e,i){if(ne()||t.media.mediaType!=="video"||!(e instanceof Yt)||i!=="vp9"&&i!=="vp8"||i==="vp8"&&!y("SIMULCAST")||i==="vp9"&&y("ENABLE_SVC")||e._scalabilityMode===void 0||e._scalabilityMode.numSpatialLayers<=1)return;const n=i==="vp8"?2:e._scalabilityMode.numSpatialLayers,r=t.attributes.ssrcs[0],o=t.attributes.ssrcGroups.find(a=>a.semantic==="FID"&&a.ssrcIds[0]===r.ssrcId),s={semantic:"SIM",ssrcIds:[r.ssrcId]};for(let a=1;a<n;a++)t.attributes.ssrcs.push({ssrcId:r.ssrcId+a,attributes:te(r.attributes)}),s.ssrcIds.push(r.ssrcId+a),o&&(t.attributes.ssrcs.push({ssrcId:o.ssrcIds[1]+a,attributes:te(r.attributes)}),t.attributes.ssrcGroups.push({semantic:"FID",ssrcIds:[r.ssrcId+a,o.ssrcIds[1]+a]}));t.attributes.ssrcGroups.unshift(s)}function Cw(){return C(this,arguments,function*(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=new RTCPeerConnection;i.addTransceiver("video",{direction:"sendonly"}),i.addTransceiver("audio",{direction:"sendonly"}),i.addTransceiver("video",{direction:"recvonly"}),i.addTransceiver("audio",{direction:"recvonly"});const n=(yield i.createOffer()).sdp,{send:r,recv:o,sendrecv:s}=function(){let a=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},d=arguments.length>2?arguments[2]:void 0;const l=Hc(d,a,c,"sendonly"),u=Hc(d,a,c,"recvonly"),h={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},p={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},g={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(kn(l,u,"videoExtensions",h,p,g),kn(l,u,"videoCodecs",h,p,g),kn(l,u,"audioExtensions",h,p,g),kn(l,u,"audioCodecs",h,p,g),y("RAISE_H264_BASELINE_PRIORITY")){const m=[],f=[];g.videoCodecs.forEach((T,R)=>{var A;if(((A=T.rtpMap)===null||A===void 0?void 0:A.encodingName.toLocaleLowerCase())==="h264"){var N,O;const w=g.videoCodecs[R+1],L=w&&ww(T,w),M=(N=T.fmtp)===null||N===void 0?void 0:N.parameters["profile-level-id"],j=(O=T.fmtp)===null||O===void 0?void 0:O.parameters["packetization-mode"];!M||M!==y("FIRST_H264_PROFILE_LEVEL_ID")||y("FIRST_PACKETIZATION_MODE")&&j!==y("FIRST_PACKETIZATION_MODE")?L?f.push([T,w]):f.push([T]):L?m.push([T,w]):m.push([T])}}),m.length>0&&f.length>0&&(_.debug("raising H264 baseline profile priority"),g.videoCodecs.forEach((T,R)=>{var A;if(((A=T.rtpMap)===null||A===void 0?void 0:A.encodingName.toLocaleLowerCase())==="h264"){const N=ww(T,g.videoCodecs[R+1]),O=m.shift()||f.shift()||[];O.length>0&&(N?g.videoCodecs.splice(R,2,...O):g.videoCodecs.splice(R,1,...O))}}),p.videoCodecs=p.videoCodecs.filter(T=>{var R,A;return!(((R=T.rtpMap)===null||R===void 0?void 0:R.encodingName.toLocaleLowerCase())==="h264"&&((A=T.fmtp)===null||A===void 0?void 0:A.parameters["profile-level-id"])!==y("FIRST_H264_PROFILE_LEVEL_ID"))}),y("FILTER_SEND_H264_BASELINE")&&(h.videoCodecs=h.videoCodecs.filter(T=>{var R,A;return!(((R=T.rtpMap)===null||R===void 0?void 0:R.encodingName.toLocaleLowerCase())==="h264"&&((A=T.fmtp)===null||A===void 0?void 0:A.parameters["profile-level-id"])!==y("FIRST_H264_PROFILE_LEVEL_ID"))})))}return{send:h,recv:p,sendrecv:g}}(t,e,n);try{i.close()}catch(a){}return{send:r,recv:o,sendrecv:s}})}function yw(){const t={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},e=Hc(arguments.length>2?arguments[2]:void 0,arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},"recvonly"),i={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},n={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(kn(t,e,"videoExtensions",i,n,r),kn(t,e,"videoCodecs",i,n,r),kn(t,e,"audioExtensions",i,n,r),kn(t,e,"audioCodecs",i,n,r),y("RAISE_H264_BASELINE_PRIORITY")){const o=r.videoCodecs.findIndex(s=>s.rtpMap&&s.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&s.fmtp&&s.fmtp.parameters["profile-level-id"]==="42001f");if(o!==-1){const s=r.videoCodecs.findIndex(a=>a.rtpMap&&a.rtpMap.encodingName.toLocaleLowerCase()==="h264");if(s<o){_.debug("raising H264 baseline profile priority");const a=r.videoCodecs[o];r.videoCodecs.splice(o,1),r.videoCodecs.splice(s,0,a)}s!==-1&&(n.videoCodecs=n.videoCodecs.filter(a=>!(a.rtpMap&&a.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&a.fmtp&&a.fmtp.parameters["profile-level-id"]!=="42001f")))}}return{send:i,recv:n,sendrecv:r}}function kn(t,e,i,n,r,o){if(i==="videoExtensions"||i==="audioExtensions"){const s=[];return t[i].forEach(a=>{e[i].some((c,d)=>{if(a.entry===c.entry&&a.extensionName===c.extensionName)return s.push(d),!0})?o[i].push(a):n[i].push(a)}),void e[i].forEach((a,c)=>{s.indexOf(c)===-1&&r[i].push(a)})}if(i==="videoCodecs"||i==="audioCodecs"){const s=[];return t[i].forEach(a=>{e[i].some((c,d)=>{if(a.payloadType===c.payloadType&&JSON.stringify(a)===JSON.stringify(c))return s.push(d),!0})?o[i].push(a):n[i].push(a)}),void e[i].forEach((a,c)=>{s.indexOf(c)===-1&&r[i].push(a)})}}function Gu(t){const{send:e,recv:i,sendrecv:n}=t;if(!n){if(!e||!i)throw new Error("cannot merge rtp capabilities because one of send or recv is empty!");return{send:e,recv:i}}let r,o;return e?(r={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},r.audioCodecs=[...e.audioCodecs,...n.audioCodecs],r.videoCodecs=[...e.videoCodecs,...n.videoCodecs],r.audioExtensions=[...e.audioExtensions,...n.audioExtensions],r.videoExtensions=[...e.videoExtensions,...n.videoExtensions]):r=n,i?(o={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},o.audioCodecs=[...i.audioCodecs,...n.audioCodecs],o.videoCodecs=[...i.videoCodecs,...n.videoCodecs],o.audioExtensions=[...i.audioExtensions,...n.audioExtensions],o.videoExtensions=[...i.videoExtensions,...n.videoExtensions]):o=n,{send:r,recv:o}}function wa(t){t.media.mediaType==="audio"&&t.attributes.payloads.filter(e=>{var i;return((i=e.rtpMap)===null||i===void 0?void 0:i.encodingName.toLowerCase())==="opus"}).forEach(e=>{e.fmtp||(e.fmtp={parameters:{}}),e.fmtp.parameters.stereo="1",e.fmtp.parameters["sprop-stereo"]="1"})}function Kc(t,e,i,n){let r=[];if(t===q.VIDEO){if(y("H264_PROFILE_LEVEL_ID")&&n==="h264"&&(r=e.videoCodecs.filter(o=>{var s;return G(s=o.rtpMap&&o.rtpMap.encodingName.toLowerCase()||"").call(s,n)&&o&&o.fmtp&&o.fmtp.parameters["profile-level-id"]===y("H264_PROFILE_LEVEL_ID")})),!Array.isArray(r)||r.length===0){let o=[];const s=[],a=[],c=[];if(i.videoCodecs.forEach(d=>{const l=d.rtpMap&&d.rtpMap.encodingName.toLowerCase()||"";G(l).call(l,n)?o.push(d):G(l).call(l,"vp9")?s.push(d):G(l).call(l,"vp8")?a.push(d):G(l).call(l,"h264")&&c.push(d)}),o.length===0){let d="";s.length!==0?(o=s,d="vp9"):a.length!==0?(o=a,d="vp8"):c.length!==0&&(o=c,d="h264"),_.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(d))}o.length!==0&&(r=e.videoCodecs.filter(d=>o.some(l=>l.payloadType===d.payloadType)))}if(r.length===0&&(_.warning("codec ".concat(n," not included in rtpCapabilities, fallback to default payloads: ").concat(e.videoCodecs[0].rtpMap&&e.videoCodecs[0].rtpMap.encodingName)),r=e.videoCodecs),y("USE_PUB_RTX")||y("USE_SUB_RTX")){const o=km(r,e.videoCodecs);r=[...r,...o]}}else{r=e.audioCodecs.filter(s=>{var a;return G(a=s.rtpMap&&s.rtpMap.encodingName.toLowerCase()||"").call(a,n)});const o=e.audioCodecs.filter(s=>{var a;return G(a=s.rtpMap&&s.rtpMap.encodingName.toLowerCase()||"").call(a,"red")});r.length===0&&(_.warning("codec ".concat(n," not included in rtpCapabilities, fallback to opus")),r=e.audioCodecs.filter(s=>{var a;return G(a=s.rtpMap&&s.rtpMap.encodingName.toLowerCase()||"").call(a,"opus")})),y("ENABLE_AUDIO_RED")&&o.length!==0&&(r=[...o,...r])}return r}function km(t,e){const i=t.map(n=>n.payloadType.toString());return e.filter(n=>n.rtpMap&&n.rtpMap.encodingName==="rtx"&&n.fmtp&&n.fmtp.parameters.apt&&G(i).call(i,n.fmtp&&n.fmtp.parameters.apt))}function Yc(t,e,i){return C(this,null,function*(){const n=e.toString(),r=Aw(n,"offer","remote","exchangeSDP");yield t.setRemoteDescription({type:"offer",sdp:n});const o=yield t.createAnswer();if(!o.sdp)throw new Error("cannot get answer sdp");let s=o.sdp;s=Iw(s,i||{}),r==null||r(s||""),yield t.setLocalDescription({type:"answer",sdp:s})})}function Iw(t,e,i){const n=Ni(t),{useXR:r}=e;return n.mediaDescriptions.forEach(o=>{var s;o.attributes.mid&&(Array.isArray(i)&&!G(i).call(i,o.attributes.mid)||(o.media.mediaType==="audio"&&wa(o),r&&G(s=["audio","video"]).call(s,o.media.mediaType)&&o.attributes.payloads.forEach(a=>{a.rtcpFeedbacks.findIndex(c=>c.type==="rrtr")===-1&&a.rtcpFeedbacks.push({type:"rrtr"})})))}),mo(n)}function Aw(t,e,i,n){if(y("SDP_LOGGING"))return _.upload("exchanging ".concat(i," ").concat(e," SDP during P2PConnection.").concat(n,`
`),t),e==="offer"?r=>{Aw(r,"answer",i==="local"?"remote":"local",n)}:void 0}function bw(t){const e=y("COMPATIBLE_SDP_EXTENSION");return!!(Array.isArray(e)&&e.length>0)&&e.some(i=>G(t).call(t,i))}function ww(t,e){try{var i;return((i=t.fmtp)===null||i===void 0?void 0:i.parameters.apt)===e.payloadType.toString()}catch(n){return!1}}function Ow(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function ji(t,e){return typeof y(t)===e?y(t):void 0}function EW(){try{const t=y("EXPERIMENTS")||{};return typeof t=="string"||Array.isArray(t)?{}:function(e){for(var i=1;i<arguments.length;i++){var n=arguments[i]!=null?arguments[i]:{};i%2?Ow(Object(n),!0).forEach(function(r){S(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Ow(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}({},t)}catch(t){return _.debug("handle gateway attributes failed: ",t),{}}}const Nw={};function vo(t){(!(arguments.length>1&&arguments[1]!==void 0)||arguments[1])&&_.debug("install service ".concat(t.name)),Nw[t.name]=t}function Kr(t){const e=Nw[t];if(!e)throw new k(v.INVALID_OPERATION,"".concat(t," not found, please use AgoraRTC.use(").concat(t,"Service) to load it first"));return e}function Dw(t,e){return Kr("DataStream").create(t,e)}function Wu(){return Kr("InterceptFrame").create()}function Pw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Rr(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?Pw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):Pw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}const Mm=new Map;class mW extends $t{get state(){return this._state}set state(e){if(e===this._state)return;const i=this._state;this._state=e,e==="DISCONNECTED"&&this._disconnectedReason?this.emit(De.CONNECTION_STATE_CHANGE,e,i,this._disconnectedReason):this.emit(De.CONNECTION_STATE_CHANGE,e,i)}get joinGatewayStartTime(){return this._joinGatewayStartTime}set joinGatewayStartTime(e){_.debug("[".concat(this.store.clientId,"] set joinGatewayStartTime at ").concat(e)),this._joinGatewayStartTime=e}constructor(e,i){var n,r,o;super(),S(this,"store",void 0),S(this,"joinInfo",void 0),S(this,"key",void 0),S(this,"ntpOffset",0),S(this,"signal",void 0),S(this,"role",void 0),S(this,"inChannelInfo",{joinAt:null,duration:0}),S(this,"spec",void 0),S(this,"_state","DISCONNECTED"),S(this,"_statsCollector",void 0),S(this,"_disconnectedReason",void 0),S(this,"isSignalRecover",!1),S(this,"hasChangeBGPAddress",!1),S(this,"trafficStatsInterval",void 0),S(this,"networkQualityInterval",void 0),S(this,"_joinGatewayStartTime",0),S(this,"_signalTimeout",!1),S(this,"_clientRoleOptions",void 0),S(this,"_isProactiveJoin",!1),this.store=e,this.spec=i,this.signal=this.store.useP2P?(n={spec:Rr(Rr({},i),{},{retryConfig:i.websocketRetryConfig}),store:e},(r=(o=Kr("P2PChannel")).createSubmodule)===null||r===void 0?void 0:r.call(o,n)):new pW(Rr(Rr({},i),{},{retryConfig:i.websocketRetryConfig}),e),this._statsCollector=i.statsCollector,this.role=i.role||"audience",this._clientRoleOptions=i.clientRoleOptions,this.handleSignalEvents()}join(e,i,n){return C(this,null,function*(){this.store.joinGatewayStart(),e.cloudProxyServer!=="disabled"&&(this.hasChangeBGPAddress=!0);const r=Date.now();let o=Mm.get(e.cname);if(o||(o=new Map,Mm.set(e.cname,o)),this._isProactiveJoin=!0,o.has(e.uid)){const d=new P(v.UID_CONFLICT);throw Z.joinGateway(e.sid,{lts:r,succ:!1,ec:d.code,addr:null,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!e.proxyServer,signalChannel:"0",preload:e.preload}),d}o.set(e.uid,!0),this.joinInfo=e,this.key=i;let s=0;this.joinGatewayStartTime=r;const a=e.proxyServer;try{_.debug("[".concat(this.store.clientId,"] use websocket join uid ").concat(s));const d=e.gatewayAddrs.map(l=>{let{address:u}=l;const[h,p]=u.split(":"),g={host:h,port:p};return e.proxyServer&&(g.proxy=e.proxyServer),g});s=(yield this.signal.init(d)).uid,_.debug("[".concat(this.store.clientId,"] websocket join uid ").concat(s," cost ").concat(Date.now()-this.joinGatewayStartTime))}catch(d){var c;throw _.error("[".concat(this.store.clientId,"] User join failed"),d.toString()),Z.joinGateway(e.sid,{lts:r,succ:!1,ec:((c=d.data)===null||c===void 0?void 0:c.desc)||d.code,errorMsg:d.message,addr:this.signal.url,uid:e.uid,cid:e.cid,firstSuccess:this._isProactiveJoin,isProxy:!!a,signalChannel:"0",preload:e.preload}),o.delete(e.uid),this.signal.close(),d}return this.state="CONNECTED",this.inChannelInfo.joinAt=Date.now(),_.debug("[".concat(this.store.clientId,"] Connected to gateway server")),this.trafficStatsInterval=window.setInterval(()=>{this.updateTrafficStats().catch(d=>{_.warning("[".concat(this.store.clientId,"] get traffic stats error"),d.toString())})},3e3),this.networkQualityInterval=window.setInterval(()=>{navigator&&navigator.onLine!==void 0&&!navigator.onLine?this.emit(De.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6}):this._signalTimeout?this.emit(De.NETWORK_QUALITY,{downlinkNetworkQuality:5,uplinkNetworkQuality:5}):this.state==="CONNECTED"&&this._statsCollector.trafficStats?this.emit(De.NETWORK_QUALITY,{uplinkNetworkQuality:hw(this._statsCollector.trafficStats.B_unq),downlinkNetworkQuality:hw(this._statsCollector.trafficStats.B_dnq)}):this.emit(De.NETWORK_QUALITY,{uplinkNetworkQuality:0,downlinkNetworkQuality:0})},2e3),this.store.joinGatewayEnd(),s})}leave(){return C(this,arguments,function*(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0],i=arguments.length>1?arguments[1]:void 0;if(this.state!=="DISCONNECTED"){i!==bt.FALLBACK&&(this.state="DISCONNECTING");try{e||this.signal.connectionState!==Ht.CONNECTED||(yield function(n,r){return r===1/0?n:K.race([n,BG(r)])}(this.signal.request(nt.LEAVE,void 0,!0),3e3))}catch(n){_.warning("[".concat(this.store.clientId,"] leave request failed, ignore"),n)}this.signal.close(i),i!==bt.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}})}publish(e,i,n){return C(this,null,function*(){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const r={state:"offer",p2p_id:this.store.p2pId,ortc:i,mode:this.spec.mode,extend:y("PUB_EXTEND"),twcc:!!y("PUBLISH_TWCC"),rtx:!!y("USE_PUB_RTX")};try{return(yield this.signal.request(nt.PUBLISH,r,!0))._message}catch(o){if(n&&o.data&&o.data.code===tt.ERR_PUBLISH_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receive publish error code, retry"),o.toString()),yield this.tryUnpubBeforeRepub(e,i),this.publish(e,i,!1);throw o}})}publishDataChannel(e,i,n){return C(this,null,function*(){var r;if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));const o={stream_id:i.streamId,ordered:i.ordered?1:0,max_retrans_times:(r=i.maxRetransmits)!==null&&r!==void 0?r:10,channel_id:i.channelId,metadata:i.metadata};try{yield this.signal.request(nt.PUBLISH_DATASTREAM,o,!0)}catch(s){if(n&&s.data&&s.data.code===tt.ERR_PUBLISH_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receive publish datachannels error code, retry"),s.toString()),yield this.tryUnpubDataChannelBeforeRepub(e,i),this.publishDataChannel(e,i,!1);throw s}})}unpublish(e,i){return C(this,null,function*(){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));yield this.signal.request(nt.UNPUBLISH,{stream_id:i,ortc:e},!0)}catch(n){_.warning("[".concat(this.store.clientId,"] unpublish warning: "),n)}})}unpublishDataChannel(e){return C(this,null,function*(){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));yield K.all(e.map(i=>this.signal.request(nt.UNPUBLISH_DATASTREAM,{channel_id:i},!0)))}catch(i){_.warning("unpublish datachannels warning: ",i)}})}presubscribe(e,i,n){return C(this,null,function*(){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not presubscribe when connection state is ".concat(this.state));const r={stream_id:e,stream_type:i,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!y("SUBSCRIBE_TWCC"),rtx:!!y("USE_SUB_RTX")||void 0,extend:y("SUB_EXTEND"),svc:Array.isArray(y("SVC"))&&y("SVC").length!==0?y("SVC"):void 0};try{return yield this.signal.request(nt.PRE_SUBSCRIBE,r,!0)}catch(o){if(n&&o.data&&o.data.code===tt.ERR_SUBSCRIBE_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] pre-subscribe error, retry"),o.toString()),this.presubscribe(e,i,!1);throw o}})}subscribe(e,i,n){return C(this,null,function*(){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not subscribe when connection state is ".concat(this.state));const r={stream_id:e,stream_type:i.stream_type,mode:this.spec.mode,codec:this.spec.codec,p2p_id:this.store.p2pId,twcc:!!y("SUBSCRIBE_TWCC"),rtx:!!y("USE_SUB_RTX"),extend:y("SUB_EXTEND"),ssrcId:i.ssrcId,svc:Array.isArray(y("SVC"))&&y("SVC").length!==0?y("SVC"):void 0};try{return(yield this.signal.request(nt.SUBSCRIBE,r,!0))._message}catch(o){if(n&&o.data&&o.data.code===tt.ERR_SUBSCRIBE_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receiver subscribe error code, retry"),o.toString()),yield this.tryUnsubBeforeResub(e,i),yield this.subscribe(e,i,!1);throw o}})}subscribeDataChannel(e,i,n){return C(this,null,function*(){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not subscribe datachannel when connection state is ".concat(this.state));const r={uid:e,stream_id:i.id,channel_id:i.datachannelId};try{return void(yield this.signal.request(nt.SUBSCRIBE_DATASTREAM,r,!0))}catch(o){if(n&&o.data&&o.data.code===tt.ERR_SUBSCRIBE_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receiver subscribe datachannel error code, retry"),o.toString()),yield this.tryUnsubDataChannelBeforeResub(e,i),yield this.subscribeDataChannel(e,i,!1);throw o}})}subscribeAll(e,i){return C(this,null,function*(){if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not massSubscribe when connection state is ".concat(this.state));const n={p2p_id:this.store.p2pId,users:e,dtx:!1,rtx:!!y("USE_SUB_RTX"),twcc:!!y("SUBSCRIBE_TWCC"),svc:Array.isArray(y("SVC"))&&y("SVC").length!==0?y("SVC"):void 0};try{return yield this.signal.request(nt.SUBSCRIBE_STREAMS,n,!0)}catch(r){if(i&&r.data&&r.data.code===tt.ERR_SUBSCRIBE_REQUEST_INVALID)return _.warning("[".concat(this.store.clientId,"] receiver massSubscribe error code, retry"),r.toString()),yield this.tryMassUnsubBeforeResub(e),yield this.subscribeAll(e,!1);throw r}})}setVideoProfile(e){return C(this,null,function*(){const i=function(n){if(!(n.bitrateMax&&n.bitrateMin&&n.frameRate&&n.height&&n.width))return;let r=n.frameRate,o=n.width,s=n.height,a=!0;return typeof r!="number"&&(r=r.exact||r.ideal||r.max||r.min||0,r||(a=!1)),typeof o!="number"&&(o=o.exact||o.ideal||o.max||o.min||0,o||(a=!1)),typeof s!="number"&&(s=s.exact||s.ideal||s.max||s.min||0,r||(a=!1)),a?{stream_type:0,width:o,height:s,fps:r,start_bps:1e3*n.bitrateMax,min_bps:1e3*n.bitrateMin,target_bps:1e3*n.bitrateMax}:void 0}(e);if(i)return this.signal.request(nt.SET_VIDEO_PROFILE,i);_.debug("[".concat(this.store.clientId,"] encoder config is not complete, do not report to gateway"))})}unsubscribe(e,i){return C(this,null,function*(){try{yield this.signal.request(nt.UNSUBSCRIBE,{p2p_id:this.store.p2pId,ortc:e,stream_id:i},!0)}catch(n){_.warning("[".concat(this.store.clientId,"] unsubscribe warning: "),n)}})}unsubscribeDataChannel(e,i){return C(this,null,function*(){try{if(this.state!=="CONNECTED"&&this.state!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not publish when connection state is ".concat(this.state));yield K.all(e.map(n=>this.signal.request(nt.UNSUBSCRIBE_DATASTREAM,{stream_id:n,uid:i},!0)))}catch(n){_.warning("unsubscribeDataChannel warning: ",n)}})}massUnsubscribe(e){return C(this,null,function*(){try{yield this.signal.request(nt.UNSUBSCRIBE_STREAMS,e,!0)}catch(i){_.warning("[".concat(this.store.clientId,"] massUnsubscribeAll warning: "),i)}})}reconnectPC(e){return C(this,null,function*(){const{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}=e;return{gatewayEstablishParams:yield this.signal.request(nt.CONNECT_PC,{p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:{iceParameters:i,dtlsParameters:n,rtpCapabilities:r}},!0),gatewayAddress:this.getCurrentGatewayAddress()}})}getGatewayInfo(){return this.signal.request(nt.GATEWAY_INFO)}renewToken(e){return C(this,null,function*(){yield this.signal.request(nt.RENEW_TOKEN,e),this.key=e.token})}updateClientRole(e,i){i&&(this._clientRoleOptions=Object.assign({},i)),y("CLIENT_ROLE_OPTIONS")&&(_.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(y("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," ")),this._clientRoleOptions=Object.assign({},y("CLIENT_ROLE_OPTIONS"))),this.role=e}setClientRole(e,i){return C(this,null,function*(){if(i&&(this._clientRoleOptions=Object.assign({},i)),y("CLIENT_ROLE_OPTIONS")&&(this._clientRoleOptions=Object.assign({},y("CLIENT_ROLE_OPTIONS")),_.debug("[".concat(this.store.clientId,"] Set roleOptions for ").concat(JSON.stringify(y("CLIENT_ROLE_OPTIONS"))," instead of ").concat(JSON.stringify(this._clientRoleOptions)," "))),this.state!=="CONNECTED")return void(this.role=e);let n,r=0;e==="audience"?this._clientRoleOptions&&this._clientRoleOptions.delay?(n=this._clientRoleOptions.delay,r=1):r=this._clientRoleOptions&&this._clientRoleOptions.level?this._clientRoleOptions.level:2:r=0,yield this.signal.request(nt.SET_CLIENT_ROLE,{role:e,level:r,delay:n,client_ts:Date.now()}),this.role=e})}setRemoteVideoStreamType(e,i){return C(this,null,function*(){yield this.signal.request(nt.SWITCH_VIDEO_STREAM,{stream_id:e,stream_type:i})})}setDefaultRemoteVideoStreamType(e){return C(this,null,function*(){yield this.signal.request(nt.DEFAULT_VIDEO_STREAM,{stream_type:e})})}setStreamFallbackOption(e,i){return C(this,null,function*(){yield this.signal.request(nt.SET_FALLBACK_OPTION,{stream_id:e,fallback_type:i})})}pickSVCLayer(e,i){return C(this,null,function*(){yield this.signal.request(nt.PICK_SVC_LAYER,{stream_id:e,spatial_layer:i.spatialLayer,temporal_layer:i.temporalLayer})})}setRTM2Flag(e){return C(this,null,function*(){yield this.signal.request(nt.SET_RTM2_FLAG,{rtm2_flag:e})})}sendExtensionMessage(e,i,n){return C(this,null,function*(){if(this.store.useP2P)return this.signal.sendExtensionMessage(e,i,n)})}getInChannelInfo(){return this.inChannelInfo.joinAt&&(this.inChannelInfo.duration=Date.now()-this.inChannelInfo.joinAt),Rr({},this.inChannelInfo)}getGatewayVersion(){return C(this,null,function*(){return(yield this.signal.request(nt.GATEWAY_INFO)).version})}reset(){if(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=Mm.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)}updateTurnConfigFromSignal(){if(!this.joinInfo)return;const e=function(i){let n;return n=i.startsWith("dc")?i.match(/(dc\:\/\/)?([^:]+):(\d+)/):i.match(/(wss\:\/\/)?([^:]+):(\d+)/),n?{username:He.username,password:He.password,turnServerURL:n[2],tcpport:parseInt(n[3])+30,udpport:parseInt(n[3])+30,forceturn:!1}:null}((this.joinInfo.cloudProxyServer==="disabled"?this.signal.url:this.joinInfo.gatewayAddrs[this.signal.currentURLIndex].address)||"");this.joinInfo.turnServer.serversFromGateway=[],e&&this.joinInfo.turnServer.mode!=="off"&&this.joinInfo.cloudProxyServer==="disabled"&&this.joinInfo.turnServer.serversFromGateway.push(Rr(Rr({},He),{},{turnServerURL:e.turnServerURL,tcpport:e.tcpport,udpport:e.udpport,username:this.joinInfo.uid.toString(),password:this.joinInfo.token}))}updateTrafficStats(){return C(this,null,function*(){if(this.state!=="CONNECTED")return;const e=yield this.signal.request(nt.TRAFFIC_STATS,void 0,!0);e.timestamp=Date.now(),e.ntp_offset!=null&&(this.ntpOffset=e.ntp_offset),e.peer_delay.forEach(i=>{const n=this._statsCollector.trafficStats&&this._statsCollector.trafficStats.peer_delay.find(r=>r.peer_uid===i.peer_uid);n&&n.B_st!==i.B_st&&du(()=>{this.emit(De.STREAM_TYPE_CHANGE,i.peer_uid,i.B_st)})}),this._statsCollector.updateTrafficStats(e)})}getJoinMessage(e){var i;if(!this.joinInfo||!this.key)throw new P(v.UNEXPECTED_ERROR,"can not generate join message, no join info");const n=Object.assign({},this.joinInfo.apResponse);let r=y("REPORT_APP_SCENARIO");if(typeof r!="string")try{r=JSON.stringify(r)}catch(u){r=void 0}var o;r&&r.length>128&&(r=void 0),this.store.hasStartJoinChannel=!0,this.store.isABTestSuccess||this.emit(De.UPDATE_GATEWAY_CONFIG),o=this.store.clientId,G(Ra).call(Ra,o)||Ra.push(o);const s=!(ne()||Jy(87)||FI())&&typeof y("ENABLE_PRE_SUB")=="boolean"&&y("ENABLE_PRE_SUB"),a=!FI()&&ji("ENABLE_PREALLOC_PC","boolean"),c=EW(),d=Ac(87)||function(){const u=vt();if(u.name!==It.SAFARI||!u.browserVersion)return!1;const h=u.browserVersion.split(".");return Number(h[0])>15||Number(h[0])===15&&Number(h[1])>=4}(),l=Rr({license:this.joinInfo.license,p2p_id:this.store.p2pId,session_id:this.joinInfo.sid,app_id:this.joinInfo.appId,channel_key:this.key,channel_name:this.joinInfo.cname,sdk_version:dn,browser:navigator.userAgent,process_id:y("PROCESS_ID"),mode:this.store.useP2P?"p2p":this.spec.mode,codec:this.spec.codec,role:this.role,has_changed_gateway:this.hasChangeBGPAddress,ap_response:n,extend:y("JOIN_EXTEND"),details:{6:this.joinInfo.stringUid,cservice_map:this.joinInfo.cloudProxyServer==="proxy3"?"1":this.joinInfo.cloudProxyServer==="proxy5"?"2":void 0},features:{rejoin:!0},optionalInfo:this.joinInfo.optionalInfo,appScenario:r,attributes:{userAttributes:Rr(Rr({enableEncodedTransform:!!y("ENABLE_AUDIO_METADATA")&&d||!!y("ENABLE_AUDIO_TOPN")&&AE(It.CHROME,87,116)||void 0,enableAudioMetadata:!!y("ENABLE_AUDIO_METADATA")&&d,enableAudioPts:!!y("ENABLE_AUDIO_PTS_METADATA")&&d,topnSmoothLevel:y("TOPN_SMOOTH_LEVEL"),topnNewSpeakerDelay:y("TOPN_NEW_SPEAKER_DELAY"),topnSwitchHoldMs:y("TOPN_SWITCH_HOLD_MS"),topnAudioGain:y("TOPN_AUDIO_GAIN"),enablePublishedUserList:y("ENABLE_PUBLISHED_USER_LIST"),maxSubscription:y("MAX_SUBSCRIPTION"),subscribeAudioFilterTopN:ji("SUBSCRIBE_AUDIO_FILTER_TOPN","number"),enablePublishAudioFilter:ji("ENABLE_PUBLISH_AUDIO_FILTER","boolean"),enableUserLicenseCheck:ji("ENABLE_USER_LICENSE_CHECK","boolean"),enableRTX:y("USE_PUB_RTX")===!0||y("USE_SUB_RTX")===!0||void 0,disableFEC:y("DISABLE_FEC"),enableNTPReport:!!y("ENABLE_NTP_REPORT")||void 0,enableInstantVideo:!!y("ENABLE_INSTANT_VIDEO")||void 0,enableFulllinkAvSync:!!y("ENABLE_FULL_LINK_AV_SYNC")||void 0,enableDataStream2:ji("ENABLE_DATASTREAM_2","boolean"),enableAutFeedback:!!y("ENABLE_AUT_FEEDBACK")||void 0,rtm2Flag:typeof this.joinInfo.rtmFlag=="number"?this.joinInfo.rtmFlag:void 0,enableUserAutoRebalanceCheck:!!y("ENABLE_USER_AUTO_REBALANCE_CHECK"),enableXR:ji("USE_XR","boolean"),enableLossbasedBwe:ji("ENABLE_LOSSBASED_BWE","boolean"),enableAutCC:!!y("ENABLE_AUT_CC")||void 0,enableCCFallback:ji("ENABLE_CC_FALLBACK","boolean"),enablePreallocPC:a,preSubNum:s?ji("PRE_SUB_NUM","number"):void 0,enablePubTWCC:ji("PUBLISH_TWCC","boolean"),enableSubTWCC:ji("SUBSCRIBE_TWCC","boolean"),enablePubRTX:ji("USE_PUB_RTX","boolean"),enableSubRTX:ji("USE_SUB_RTX","boolean"),enableSubSVC:y("ENABLE_SVC")?y("ENABLE_SVC_DEFAULT_CODECS"):Array.isArray(y("SVC"))&&y("SVC").length!==0?y("SVC"):void 0,enableSvcExtended:y("ENABLE_SVC")&&Array.isArray(y("SVC_EXTENDED"))&&y("SVC_EXTENDED").length!==0?y("SVC_EXTENDED"):void 0},c),{},{audioDuplicate:ji("ENABLE_AUDIO_RED","boolean")?(i=ji("AUDIO_DUPLICATE_NUM","number"))!==null&&i!==void 0?i:2:void 0})},join_ts:this.joinGatewayStartTime},e);return this.joinInfo.stringUid&&(l.string_uid=this.joinInfo.stringUid),this.joinInfo.aesmode&&this.joinInfo.aespassword&&(l.aes_mode=this.joinInfo.aesmode,y("ENCRYPT_AES")?(l.aes_secret=this.joinInfo.aespassword,l.aes_encrypt=!0):l.aes_secret=this.joinInfo.aespassword,this.joinInfo.aessalt&&(l.aes_salt=this.joinInfo.aessalt)),n.addresses[this.signal.websocket.currentURLIndex]&&(l.ap_response.ticket=n.addresses[this.signal.websocket.currentURLIndex].ticket,delete n.addresses),this.joinInfo.defaultVideoStream!==void 0&&(l.default_video_stream=this.joinInfo.defaultVideoStream),l}getRejoinMessage(){if(!this.joinInfo)throw new P(v.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)}}handleSignalEvents(){this.signal.on(ot.WS_RECONNECT_CREATE_CONNECTION,e=>{this.joinGatewayStartTime=Date.now()}),this.signal.on(ot.WS_RECONNECTING,e=>{this.joinInfo&&Z.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:e||Ge.NETWORK_ERROR}),this.joinInfo&&(this.state="RECONNECTING",Z.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:this.spec.mode==="live"?1:0,channelMode:0,lsid:this.joinInfo.sid,clientRole:this.role==="audience"?2:1,buildFormat:1}),this.isSignalRecover=!1,this.joinGatewayStartTime=Date.now())}),this.signal.on(ot.WS_CLOSED,e=>{let i;switch(e){case bt.LEAVE:i=Ge.LEAVE;break;case bt.UID_BANNED:case bt.IP_BANNED:case bt.CHANNEL_BANNED:case bt.SERVER_ERROR:i=Ge.SERVER_ERROR;break;case bt.FALLBACK:i=Ge.FALLBACK;break;case bt.LICENSE_MISSING:case bt.LICENSE_EXPIRED:case bt.LICENSE_MINUTES_EXCEEDED:case bt.LICENSE_PERIOD_INVALID:case bt.LICENSE_MULTIPLE_SDK_SERVICE:case bt.LICENSE_ILLEGAL:case bt.TOKEN_EXPIRE:i=e;break;default:i=Ge.NETWORK_ERROR}_.debug("[".concat(this.store.clientId,"] [signal] websocket closed, reason: ").concat(i||"undefined -> "+Ge.NETWORK_ERROR)),this.joinInfo&&Z.WebSocketQuit(this.joinInfo.sid,{lts:Date.now(),succ:e===bt.LEAVE?1:-1,cname:this.joinInfo.cname,uid:this.joinInfo.uid,cid:this.joinInfo.cid,errorCode:i}),this._disconnectedReason=e,e!==bt.FALLBACK&&(this.state="DISCONNECTED"),this.reset()}),this.signal.on(ot.WS_CONNECTED,()=>{if(this.updateTurnConfigFromSignal(),this.state="CONNECTED",this.joinInfo){if(this.role==="audience"){const e=y("CLIENT_ROLE_OPTIONS")||this._clientRoleOptions;e&&(e.level||e.delay)&&(_.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(Z.joinGateway(this.joinInfo.sid,{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,signalChannel:"0",preload:this.joinInfo.preload,isABTestSuccess:this.store.isABTestSuccess}),this._isProactiveJoin=!1,this.joinInfo.useLocalAccessPoint&&this.joinInfo.setLocalAPVersion===1){const e=this.signal.url&&this.signal.url.match(/wss\:\/\/([^:]+):(\d+)/);if(!e)return void _.error("[".concat(this.store.clientId,"] set local access point after joined failed: ").concat(e));kt("EVENT_REPORT_DOMAIN",e[1]),kt("EVENT_REPORT_BACKUP_DOMAIN",e[1]),kt("LOG_UPLOAD_SERVER","".concat(e[1],":6444"))}}}),this.signal.on(mt.ON_UPLINK_STATS,e=>{this._statsCollector.updateUplinkStats(e)}),this.signal.on(ot.REQUEST_RECOVER,(e,i,n)=>{if(!this.joinInfo)return n(new P(v.UNEXPECTED_ERROR,"gateway: can not recover, no join info"));e&&(this.joinInfo.multiIP=e,this.hasChangeBGPAddress=!0),this.isSignalRecover=!0,We(this,De.REQUEST_NEW_GATEWAY_LIST).then(i).catch(n)}),this.signal.on(ot.REQUEST_JOIN_INFO,(e,i,n)=>C(this,null,function*(){var r;if(this.updateTurnConfigFromSignal(),this.store.useP2P)return void e(this.getJoinMessage({ortc:{}}));const o=te((r=this.joinInfo)===null||r===void 0?void 0:r.turnServer);if(y("NEW_TURN_MODE")&&o){let d=o.servers,l=o.serversFromGateway;const u=this.signal.currentURLIndex;d.length>0&&(d=[d[u%d.length]],o.servers=d),Array.isArray(l)&&l.length>0&&(l=[l[0]],o.serversFromGateway=l),_.debug("[".concat(this.store.clientId,"] use single turn, use turn server index: ").concat(u))}const{iceParameters:s,dtlsParameters:a,rtpCapabilities:c}=yield We(this,De.REQUEST_P2P_CONNECTION_PARAMS,{turnServer:o});try{e(this.getJoinMessage({ortc:{iceParameters:s,dtlsParameters:a,rtpCapabilities:c,version:"2"}}))}catch(d){i(d)}})),this.signal.on(ot.REQUEST_REJOIN_INFO,e=>{e(this.getRejoinMessage())}),this.signal.on(ot.REPORT_JOIN_GATEWAY,(e,i)=>{if(!this.joinInfo)return;let n,r="";var o;e instanceof P?(n=((o=e.data)===null||o===void 0?void 0:o.desc)||e.code,r=e.message):n=e,Z.joinGateway(this.joinInfo.sid,{lts:this.joinGatewayStartTime,succ:!1,ec:n,errorMsg:r,addr:i,uid:this.joinInfo.uid,cid:this.joinInfo.cid,firstSuccess:this._isProactiveJoin,isProxy:!!this.joinInfo.proxyServer,signalChannel:"0",preload:this.joinInfo.preload})}),this.signal.on(ot.IS_P2P_DISCONNECTED,e=>{e(Dc(this,De.IS_P2P_DISCONNECTED))}),this.signal.on(ot.DISCONNECT_P2P,()=>{this.emit(De.DISCONNECT_P2P)}),this.signal.on(ot.REQUEST_SUCCESS,()=>{this._signalTimeout=!1}),this.signal.on(ot.REQUEST_TIMEOUT,()=>{this._signalTimeout=!0}),this.signal.on(ot.JOIN_RESPONSE,e=>{const i=this.getCurrentGatewayAddress();this.emit(De.JOIN_RESPONSE,e,i)}),this.signal.on(ot.PRE_CONNECT_PC,()=>C(this,null,function*(){if(this.joinInfo){this.updateTurnConfigFromSignal();const e=this.getCurrentGatewayAddress(),i=y("FINGERPRINT")||this.joinInfo.apResponse.addresses[this.signal.currentURLIndex].fingerprint;if(e&&i){const n=Tw(e);this.emit(De.PRE_CONNECT_PC,{candidates:n,fingerprint:i})}}})),this.signal.on(ot.RECOVER_NOTIFICATION,e=>{this.joinInfo&&typeof y("AP_REQUEST_DETAIL")=="string"&&(this.joinInfo.apRequestDetail="".concat(y("AP_REQUEST_DETAIL"),";").concat(e))})}tryUnsubBeforeResub(e,i){return C(this,null,function*(){try{yield this.signal.request(nt.UNSUBSCRIBE,{p2p_id:this.store.p2pId,stream_id:e,ortc:[i]},!0)}catch(n){throw _.warning("[".concat(this.store.clientId,"] tryUnsubBeforeResub warning"),n),n}})}tryUnsubDataChannelBeforeResub(e,i){return C(this,null,function*(){try{yield this.signal.request(nt.UNSUBSCRIBE,{stream_id:i.id},!0)}catch(n){throw _.warning("unsubscribe datachannel warning",n),n}})}tryUnpubBeforeRepub(e,i){return C(this,null,function*(){try{yield this.signal.request(nt.UNPUBLISH,{stream_id:e,ortc:i},!0)}catch(n){throw _.warning("[".concat(this.store.clientId,"] tryUnpubBeforeRepub warning: "),n),n}})}tryUnpubDataChannelBeforeRepub(e,i){return C(this,null,function*(){try{yield this.signal.request(nt.UNPUBLISH_DATASTREAM,{channnel_id:i.channelId},!0)}catch(n){throw _.warning("unpublish datastream warning: ",n),n}})}tryMassUnsubBeforeResub(e){return C(this,null,function*(){const i={users:e.map(n=>({stream_id:n.stream_id,stream_type:n.stream_type}))};try{yield this.signal.request(nt.UNSUBSCRIBE_STREAMS,i,!0)}catch(n){throw _.warning("[".concat(this.store.clientId,"] tryMassUnsubBeforeResub warning"),n),n}})}muteLocal(e,i){return C(this,null,function*(){const n={action:e.find(r=>r.stream_type===Ot.Audio)?"mute_local_audio":"mute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:i};try{yield this.signal.request(nt.CONTROL,n,!0,!0)}catch(r){throw _.warning("[".concat(this.store.clientId,"] gateway muteLocal warning: "),r),r}})}unmuteLocal(e,i){return C(this,null,function*(){const n={action:e.find(r=>r.stream_type===Ot.Audio)?"unmute_local_audio":"unmute_local_video",p2p_id:this.store.p2pId,ortc:e,stream_id:i};try{yield this.signal.request(nt.CONTROL,n,!0,!0)}catch(r){throw _.warning("[".concat(this.store.clientId,"] gateway unmuteLocal warning: "),r),r}})}muteRemote(e,i){return C(this,null,function*(){const n={action:e===q.AUDIO?"mute_remote_audio":"mute_remote_video",p2p_id:this.store.p2pId,stream_id:i};try{yield this.signal.request(nt.CONTROL,n,!0,!0)}catch(r){throw _.warning("[".concat(this.store.clientId,"] gateway muteRemote warning: "),r),r}})}unmuteRemote(e,i){return C(this,null,function*(){const n={action:e===q.AUDIO?"unmute_remote_audio":"unmute_remote_video",p2p_id:this.store.p2pId,stream_id:i};try{yield this.signal.request(nt.CONTROL,n,!0,!0)}catch(r){throw _.warning("[".concat(this.store.clientId,"] gateway unmuteRemote warning: "),r),r}})}uploadWRTCStats(e){this.signal.uploadWRTCStats(e)}upload(e,i){this.signal.upload(e,i)}getSignalRTT(){return this.signal.rtt}restartICE(e){return C(this,null,function*(){const i={p2p_id:this.store.p2pId,stream_id:this.store.uid,ortc:e};try{return yield this.signal.request(nt.RESTART_ICE,i,!0)}catch(n){throw _.warning("[".concat(this.store.clientId,"] P2PChannel.restartICE warning: "),n),n}})}reconnect(e,i){this.state==="CONNECTED"&&this.signal.reconnect(e||void 0,i||Ge.P2P_FAILED)}getCurrentGatewayAddress(){var e,i;if(!y("GATEWAY_WSS_ADDRESS"))return y("USE_CANDIDATE_FROM_AP_DETAIL")&&(e=this.joinInfo)!==null&&e!==void 0&&e.apGatewayAddress?(_.debug("[".concat(this.store.clientId,"] use candidate from ap detail, ").concat(JSON.stringify(this.joinInfo.apGatewayAddress))),this.joinInfo.apGatewayAddress):(i=this.joinInfo)!==null&&i!==void 0&&i.gatewayAddrs?this.joinInfo.gatewayAddrs[this.signal.currentURLIndex]:void 0}setPublishAudioFilterEnabled(e){return C(this,null,function*(){yield this.signal.request(nt.SET_PARAMETER,{enablePublishAudioFilter:e})})}}let Hu=0,Um=0;function er(t,e,i,n){return new K((r,o)=>{e.timeout=e.timeout||y("HTTP_CONNECT_TIMEOUT"),e.responseType=e.responseType||"json",e.data&&!i?(e.data=JSON.stringify(e.data),Hu+=Er(e.data)):i&&(e.data.size?Hu+=e.data.size:e.data instanceof FormData?Hu+=_I(e.data):Hu+=Er(JSON.stringify(e.data))),e.headers=e.headers||{},e.headers["Content-Type"]=e.headers["Content-Type"]||"application/json",e.method="POST",e.url=t,Ti.request(e).then(s=>{typeof s.data=="string"?Um+=Er(s.data):s.data instanceof ArrayBuffer||s.data instanceof Uint8Array?Um+=s.data.byteLength:Um+=Er(JSON.stringify(s.data)),n&&r({data:s.data,headers:s.headers}),r(s.data)}).catch(s=>{Ti.isCancel(s)?o(new P(v.OPERATION_ABORTED,"cancel token canceled")):s.code==="ECONNABORTED"?o(new P(v.NETWORK_TIMEOUT,s.message)):s.response?o(new P(v.NETWORK_RESPONSE_ERROR,s.response.status)):o(new P(v.NETWORK_ERROR,s.message))})})}/*! formdata-polyfill. MIT License. Jimmy W?rting <https://jimmy.warting.se/opensource> */(function(){var t;function e(U){var B=0;return function(){return B<U.length?{done:!1,value:U[B++]}:{done:!0}}}var i=typeof Object.defineProperties=="function"?Object.defineProperty:function(U,B,X){return U==Array.prototype||U==Object.prototype||(U[B]=X.value),U},n,r=function(U){U=[typeof globalThis=="object"&&globalThis,U,typeof window=="object"&&window,typeof self=="object"&&self,typeof Qe=="object"&&Qe];for(var B=0;B<U.length;++B){var X=U[B];if(X&&X.Math==Math)return X}throw Error("Cannot find global object")}(this);function o(U,B){if(B)t:{var X=r;U=U.split(".");for(var x=0;x<U.length-1;x++){var E=U[x];if(!(E in X))break t;X=X[E]}(B=B(x=X[U=U[U.length-1]]))!=x&&B!=null&&i(X,U,{configurable:!0,writable:!0,value:B})}}function s(U){return(U={next:U})[Symbol.iterator]=function(){return this},U}function a(U){var B=typeof Symbol!="undefined"&&Symbol.iterator&&U[Symbol.iterator];return B?B.call(U):{next:e(U)}}if(o("Symbol",function(U){function B(E,I){this.A=E,i(this,"description",{configurable:!0,writable:!0,value:I})}if(U)return U;B.prototype.toString=function(){return this.A};var X="jscomp_symbol_"+(1e9*Math.random()>>>0)+"_",x=0;return function E(I){if(this instanceof E)throw new TypeError("Symbol is not a constructor");return new B(X+(I||"")+"_"+x++,I)}}),o("Symbol.iterator",function(U){if(U)return U;U=Symbol("Symbol.iterator");for(var B="Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" "),X=0;X<B.length;X++){var x=r[B[X]];typeof x=="function"&&typeof x.prototype[U]!="function"&&i(x.prototype,U,{configurable:!0,writable:!0,value:function(){return s(e(this))}})}return U}),typeof Object.setPrototypeOf=="function")n=Object.setPrototypeOf;else{var c;t:{var d={};try{d.__proto__={a:!0},c=d.a;break t}catch(U){}c=!1}n=c?function(U,B){if(U.__proto__=B,U.__proto__!==B)throw new TypeError(U+" is not extensible");return U}:null}var l=n;function u(){this.m=!1,this.j=null,this.v=void 0,this.h=1,this.u=this.C=0,this.l=null}function h(U){if(U.m)throw new TypeError("Generator is already running");U.m=!0}function p(U,B){return U.h=3,{value:B}}function g(U){this.g=new u,this.G=U}function m(U,B,X,x){try{var E=B.call(U.g.j,X);if(!(E instanceof Object))throw new TypeError("Iterator result "+E+" is not an object");if(!E.done)return U.g.m=!1,E;var I=E.value}catch(b){return U.g.j=null,U.g.s(b),f(U)}return U.g.j=null,x.call(U.g,I),f(U)}function f(U){for(;U.g.h;)try{var B=U.G(U.g);if(B)return U.g.m=!1,{value:B.value,done:!1}}catch(X){U.g.v=void 0,U.g.s(X)}if(U.g.m=!1,U.g.l){if(B=U.g.l,U.g.l=null,B.F)throw B.D;return{value:B.return,done:!0}}return{value:void 0,done:!0}}function T(U){this.next=function(B){return U.o(B)},this.throw=function(B){return U.s(B)},this.return=function(B){return function(X,x){h(X.g);var E=X.g.j;return E?m(X,"return"in E?E.return:function(I){return{value:I,done:!0}},x,X.g.return):(X.g.return(x),f(X))}(U,B)},this[Symbol.iterator]=function(){return this}}function R(U,B){return B=new T(new g(B)),l&&U.prototype&&l(B,U.prototype),B}if(u.prototype.o=function(U){this.v=U},u.prototype.s=function(U){this.l={D:U,F:!0},this.h=this.C||this.u},u.prototype.return=function(U){this.l={return:U},this.h=this.u},g.prototype.o=function(U){return h(this.g),this.g.j?m(this,this.g.j.next,U,this.g.o):(this.g.o(U),f(this))},g.prototype.s=function(U){return h(this.g),this.g.j?m(this,this.g.j.throw,U,this.g.o):(this.g.s(U),f(this))},o("Array.prototype.entries",function(U){return U||function(){return function(B,X){B instanceof String&&(B+="");var x=0,E=!1,I={next:function(){if(!E&&x<B.length){var b=x++;return{value:X(b,B[b]),done:!1}}return E=!0,{done:!0,value:void 0}}};return I[Symbol.iterator]=function(){return I},I}(this,function(B,X){return[B,X]})}}),typeof Blob!="undefined"&&(typeof FormData=="undefined"||!FormData.prototype.keys)){var A=function(U,B){for(var X=0;X<U.length;X++)B(U[X])},N=function(U){return U.replace(/\r?\n|\r/g,`\r
`)},O=function(U,B,X){return B instanceof Blob?(X=X!==void 0?X+"":typeof B.name=="string"?B.name:"blob",B.name===X&&Object.prototype.toString.call(B)!=="[object Blob]"||(B=new File([B],X)),[String(U),B]):[String(U),String(B)]},w=function(U,B){if(U.length<B)throw new TypeError(B+" argument required, but only "+U.length+" present.")},L=typeof globalThis=="object"?globalThis:typeof window=="object"?window:typeof self=="object"?self:this,M=L.FormData,j=L.XMLHttpRequest&&L.XMLHttpRequest.prototype.send,H=L.Request&&L.fetch,ht=L.navigator&&L.navigator.sendBeacon,lt=L.Element&&L.Element.prototype,rt=L.Symbol&&Symbol.toStringTag;rt&&(Blob.prototype[rt]||(Blob.prototype[rt]="Blob"),"File"in L&&!File.prototype[rt]&&(File.prototype[rt]="File"));try{new File([],"")}catch(U){L.File=function(B,X,x){return B=new Blob(B,x||{}),Object.defineProperties(B,{name:{value:X},lastModified:{value:+(x&&x.lastModified!==void 0?new Date(x.lastModified):new Date)},toString:{value:function(){return"[object File]"}}}),rt&&Object.defineProperty(B,rt,{value:"File"}),B}}var Kt=function(U){return U.replace(/\n/g,"%0A").replace(/\r/g,"%0D").replace(/"/g,"%22")},Ft=function(U){this.i=[];var B=this;U&&A(U.elements,function(X){if(X.name&&!X.disabled&&X.type!=="submit"&&X.type!=="button"&&!X.matches("form fieldset[disabled] *"))if(X.type==="file"){var x=X.files&&X.files.length?X.files:[new File([],"",{type:"application/octet-stream"})];A(x,function(E){B.append(X.name,E)})}else X.type==="select-multiple"||X.type==="select-one"?A(X.options,function(E){!E.disabled&&E.selected&&B.append(X.name,E.value)}):X.type==="checkbox"||X.type==="radio"?X.checked&&B.append(X.name,X.value):(x=X.type==="textarea"?N(X.value):X.value,B.append(X.name,x))})};if((t=Ft.prototype).append=function(U,B,X){w(arguments,2),this.i.push(O(U,B,X))},t.delete=function(U){w(arguments,1);var B=[];U=String(U),A(this.i,function(X){X[0]!==U&&B.push(X)}),this.i=B},t.entries=function U(){var B,X=this;return R(U,function(x){if(x.h==1&&(B=0),x.h!=3)return B<X.i.length?x=p(x,X.i[B]):(x.h=0,x=void 0),x;B++,x.h=2})},t.forEach=function(U,B){w(arguments,1);for(var X=a(this),x=X.next();!x.done;x=X.next()){var E=a(x.value);x=E.next().value,E=E.next().value,U.call(B,E,x,this)}},t.get=function(U){w(arguments,1);var B=this.i;U=String(U);for(var X=0;X<B.length;X++)if(B[X][0]===U)return B[X][1];return null},t.getAll=function(U){w(arguments,1);var B=[];return U=String(U),A(this.i,function(X){X[0]===U&&B.push(X[1])}),B},t.has=function(U){w(arguments,1),U=String(U);for(var B=0;B<this.i.length;B++)if(this.i[B][0]===U)return!0;return!1},t.keys=function U(){var B,X,x,E,I=this;return R(U,function(b){if(b.h==1&&(B=a(I),X=B.next()),b.h!=3)return X.done?void(b.h=0):(x=X.value,E=a(x),p(b,E.next().value));X=B.next(),b.h=2})},t.set=function(U,B,X){w(arguments,2),U=String(U);var x=[],E=O(U,B,X),I=!0;A(this.i,function(b){b[0]===U?I&&(I=!x.push(E)):x.push(b)}),I&&x.push(E),this.i=x},t.values=function U(){var B,X,x,E,I=this;return R(U,function(b){if(b.h==1&&(B=a(I),X=B.next()),b.h!=3)return X.done?void(b.h=0):(x=X.value,(E=a(x)).next(),p(b,E.next().value));X=B.next(),b.h=2})},Ft.prototype._asNative=function(){for(var U=new M,B=a(this),X=B.next();!X.done;X=B.next()){var x=a(X.value);X=x.next().value,x=x.next().value,U.append(X,x)}return U},Ft.prototype._blob=function(){var U="----formdata-polyfill-"+Math.random(),B=[],X="--"+U+`\r
Content-Disposition: form-data; name="`;return this.forEach(function(x,E){return typeof x=="string"?B.push(X+Kt(N(E))+`"\r
\r
`+N(x)+`\r
`):B.push(X+Kt(N(E))+'"; filename="'+Kt(x.name)+`"\r
Content-Type: `+(x.type||"application/octet-stream")+`\r
\r
`,x,`\r
`)}),B.push("--"+U+"--"),new Blob(B,{type:"multipart/form-data; boundary="+U})},Ft.prototype[Symbol.iterator]=function(){return this.entries()},Ft.prototype.toString=function(){return"[object FormData]"},lt&&!lt.matches&&(lt.matches=lt.matchesSelector||lt.mozMatchesSelector||lt.msMatchesSelector||lt.oMatchesSelector||lt.webkitMatchesSelector||function(U){for(var B=(U=(this.document||this.ownerDocument).querySelectorAll(U)).length;0<=--B&&U.item(B)!==this;);return-1<B}),rt&&(Ft.prototype[rt]="FormData"),j){var Ii=L.XMLHttpRequest.prototype.setRequestHeader;L.XMLHttpRequest.prototype.setRequestHeader=function(U,B){Ii.call(this,U,B),U.toLowerCase()==="content-type"&&(this.B=!0)},L.XMLHttpRequest.prototype.send=function(U){U instanceof Ft?(U=U._blob(),this.B||this.setRequestHeader("Content-Type",U.type),j.call(this,U)):j.call(this,U)}}H&&(L.fetch=function(U,B){return B&&B.body&&B.body instanceof Ft&&(B.body=B.body._blob()),H.call(this,U,B)}),ht&&(L.navigator.sendBeacon=function(U,B){return B instanceof Ft&&(B=B._asNative()),ht.call(this,U,B)}),L.FormData=Ft}})();const qc=()=>{const t=y("AREAS");return t.length===0&&t.push(At.GLOBAL),Tn(t).call(t,(e,i,n)=>{const r=Lw(i);return r?n===0?r:"".concat(e,",").concat(r):e},"")},Lw=t=>t===At.OVERSEA?"".concat(ze.ASIA,",").concat(ze.EUROPE,",").concat(ze.AFRICA,",").concat(ze.NORTH_AMERICA,",").concat(ze.SOUTH_AMERICA,",").concat(ze.OCEANIA):ze[t],fW=t=>{const e={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 t.map(i=>{const n=Uu[i],r=Object.keys(n);r&&r.map(o=>{o!=="CODE"&&(e[o]=e[o].concat(n[o]))})}),e},Ku={GLOBAL:{ASIA:[At.CHINA,At.JAPAN,At.INDIA,At.KOREA,At.HKMC],EUROPE:[],NORTH_AMERICA:[At.US],SOUTH_AMERICA:[],OCEANIA:[],AFRICA:[]}},Yu=Object.keys(Ku[At.GLOBAL]),xm=[At.CHINA,At.NORTH_AMERICA,At.EUROPE,At.ASIA,At.JAPAN,At.INDIA,At.OCEANIA,At.SOUTH_AMERICA,At.AFRICA,At.KOREA,At.HKMC,At.US],gW=function(t,e){let i=[];if(G(t).call(t,At.GLOBAL)){const o=[At.GLOBAL,At.OVERSEA],s=Object.keys(Uu);if(e===At.GLOBAL)throw new P(v.INVALID_PARAMS,"GLOBAL is an invalid excludedArea value");if(e===At.CHINA)i=[At.OVERSEA];else if(r=e,G(Yu).call(Yu,r)){const a=(n=e,Ku[At.GLOBAL][n]||[]),c=[...o,e,...a];i=s.filter(d=>!G(c).call(c,d))}else if(function(a){let c=!1;return Yu.forEach(d=>{var l;G(l=Ku[At.GLOBAL][d]).call(l,a)&&(c=!0)}),c}(e)){const a=function(d){let l;return Yu.forEach(u=>{var h;G(h=Ku[At.GLOBAL][u]).call(h,d)&&(l=u)}),l}(e),c=[...o,a,e];i=s.filter(d=>!G(c).call(c,d))}else i=t;i=function(a){const c=[];return xm.forEach(d=>{G(a).call(a,d)&&c.push(d)}),c.concat(a.filter(d=>!G(xm).call(xm,d)))}(i)}else i=t;var n,r;return i};function kw(t){var e,i;if(!t&&G(e=y("AREAS")).call(e,At.EXTENSIONS))return _.debug("update area from ap : reset"),void Vm(A3,!0);if(!G(i=y("AREAS")).call(i,At.GLOBAL)||!t)return;let n=Uu.EXTENSIONS;n&&(n={CODE:Lw(At.EXTENSIONS),WEBCS_DOMAIN:["ap-web-1-".concat(t,".agora.io")],WEBCS_DOMAIN_BACKUP_LIST:["ap-web-2-".concat(t,".ap.sd-rtn.com")],PROXY_CS:["proxy-ap-web-".concat(t,".agora.io")],CDS_AP:["cds-ap-web-1-".concat(t,".agora.io"),"cds-ap-web-2-".concat(t,".ap.sd-rtn.com")],ACCOUNT_REGISTER:["sua-ap-web-1-".concat(t,".agora.io"),"sua-ap-web-2-".concat(t,".ap.sd-rtn.com")],UAP_AP:["uap-ap-web-1-".concat(t,".agora.io"),"uap-ap-web-2-".concat(t,".ap.sd-rtn.com")],EVENT_REPORT_DOMAIN:["statscollector-1-".concat(t,".agora.io")],EVENT_REPORT_BACKUP_DOMAIN:["statscollector-2-".concat(t,".agora.io")],LOG_UPLOAD_SERVER:["logservice-".concat(t,".agora.io")],PROXY_SERVER_TYPE3:["webrtc-cloud-proxy-".concat(t,".agora.io")]},_.debug("update area from ap success: ".concat(t,",config is "),n),kt("AREAS",[At.EXTENSIONS],!0),Object.keys(n).map(r=>{r==="LOG_UPLOAD_SERVER"||r==="EVENT_REPORT_DOMAIN"||r==="EVENT_REPORT_BACKUP_DOMAIN"||r==="PROXY_SERVER_TYPE3"?kt(r,n[r][0]):kt(r,n[r])}))}function Vm(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const i=Z.reportApiInvoke(null,{name:_e.SET_AREA,options:t,tag:oe.TRACER});try{let n=[];if(typeof t=="string"&&(n=[t]),Array.isArray(t)&&(t.forEach(o=>{if(!G(ew).call(ew,o))throw new P(v.INVALID_PARAMS,"invalid area code")}),n=t),Object.prototype.toString.call(t)==="[object Object]"){const{areaCode:o,excludedArea:s}=t;if(!o)throw new P(v.INVALID_PARAMS,"area code is needed");let a=o;typeof o=="string"&&(a=[o]),n=s?gW(a,s):a}if(!e){if(Qn.AREAS){const o=new P(v.PROHIBITED_OPERATION,"setArea is prohibited because of config-distribute");return i.onError(o),void _.warning("setArea is prohibited because of config-distribute")}if(G(n).call(n,At.GLOBAL)&&y("AREAS")===At.EXTENSIONS){const o=new P(v.PROHIBITED_OPERATION,"setArea is prohibited because of ap extensions");return i.onError(o),void _.warning("setArea is prohibited because of ap extensions")}}kt("AREAS",n,e);const r=fW(n);Object.keys(r).map(o=>{o==="LOG_UPLOAD_SERVER"||o==="EVENT_REPORT_DOMAIN"||o==="EVENT_REPORT_BACKUP_DOMAIN"||o==="PROXY_SERVER_TYPE3"?kt(o,r[o][0]):kt(o,r[o])}),_.debug("set area success:",n.join(","))}catch(n){throw i.onError(n),n}i.onSuccess()}function Mw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function vr(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?Mw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):Mw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}let Fm=1;function SW(t,e,i,n,r){Fm+=1;const o={sid:i.sid,command:"convergeAllocateEdge",uid:"666",appId:i.appId,ts:Math.floor(Date.now()/1e3),seq:Fm,requestId:Fm,version:dn,cname:i.cname},s={service_name:e,json_body:JSON.stringify(o)};let a,c,d=t[0];return Jn(()=>C(this,null,function*(){a=Date.now();const l=yield er(d,{data:s,cancelToken:n,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"}});if(c=Date.now()-a,l.code!==0){const p=new P(v.UNEXPECTED_RESPONSE,"live streaming ap error, code"+l.code,{retry:!0,responseTime:c});throw _.error(p.toString()),p}const u=JSON.parse(l.json_body);if(u.code!==200){const p=new P(v.UNEXPECTED_RESPONSE,"live streaming app center error, code: ".concat(u.code,", reason: ").concat(u.reason),{code:u.code,responseTime:c});throw _.error(p.toString()),p}if(!u.servers||u.servers.length===0){const p=new P(v.UNEXPECTED_RESPONSE,"live streaming app center empty server",{code:u.code,responseTime:c});throw _.error(p.toString()),p}const h=function(p,g){return{addressList:p.servers.map(m=>"wss://".concat(m.address.replace(/\./g,"-"),".").concat(y("WORKER_DOMAIN"),":").concat(m.wss,"?serviceName=").concat(encodeURIComponent(g))),workerToken:p.workerToken,vid:p.vid}}(u,e);return y("LIVE_STREAMING_ADDRESS")&&(h.addressList=y("LIVE_STREAMING_ADDRESS")instanceof Array?y("LIVE_STREAMING_ADDRESS"):[y("LIVE_STREAMING_ADDRESS")]),vr(vr({},h),{},{responseTime:c})}),(l,u)=>(Z.apworkerEvent(i.sid,{success:!0,sc:200,serviceName:e,responseDetail:JSON.stringify(l.addressList),firstSuccess:u===0,responseTime:c,serverIp:t[u%t.length]}),!1),(l,u)=>(Z.apworkerEvent(i.sid,{success:!1,sc:l.data&&l.data.code||200,serviceName:e,responseTime:c,serverIp:t[u%t.length]}),!!(l.code!==v.OPERATION_ABORTED&&l.code!==v.UNEXPECTED_RESPONSE||l.data&&l.data.retry)&&(d=t[(u+1)%t.length],!0)),r)}let Bm=1;function Uw(t,e,i,n){let{url:r,areaCode:o}=t;const{clientId:s,sid:a}=e,c=Date.now();let d;const l=e.role,[u,h]=Gm(e,o,[me.CHOOSE_SERVER]);let p=Ee.networkState;return Jn(()=>C(this,null,function*(){p&&Ee.networkState===Fi.OFFLINE&&Ee.onlineWaiter&&(yield K.race([Ee.onlineWaiter,Ue(n&&n.maxRetryTimeout||ge.maxRetryTimeout)])),p=Ee.networkState;const{data:g,headers:m}=yield er(r,{data:u,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);d=m.http3==="1"?1:-1,Z.reportResourceTiming(r,a),Vw(g,r,e,c,[me.CHOOSE_SERVER],d);const f=Wc(g,me.CHOOSE_SERVER);return jm(f),Nm(f,r)}),g=>(g&&Z.joinChooseServer(a,{role:l,lts:c,succ:!0,csAddr:r,opid:h,serverList:g.gatewayAddrs.map(m=>m.address),ec:null,cid:g.cid.toString(),uid:g.uid.toString(),csIp:g.csIp,unilbsServerIds:[me.CHOOSE_SERVER].toString(),isHttp3:d,corssRegionTagReq:e.apRequestDetail,corssRegionTagRes:g.res.detail&&g.res.detail[38]}),!1),g=>g.code!==v.OPERATION_ABORTED&&(g.code===v.CAN_NOT_GET_GATEWAY_SERVER?g.data.retry:(Z.joinChooseServer(a,{role:l,lts:c,succ:!1,csAddr:r,serverList:null,opid:h,ec:g.code,csIp:g.data&&g.data.csIp,unilbsServerIds:[me.CHOOSE_SERVER].toString(),extend:JSON.stringify({networkState:p}),isHttp3:d,corssRegionTagReq:e.apRequestDetail}),_.warning("[".concat(s||"sid-".concat(a.slice(0,6)),"] Choose server network error, retry"),g),!0)),n)}function xw(t,e,i,n){let r,{url:o,areaCode:s,serviceIds:a}=t;const c=Date.now(),d=e.role,[l,u]=Gm(e,s,a);let h;return Jn(()=>C(this,null,function*(){h&&Ee.networkState===Fi.OFFLINE&&Ee.onlineWaiter&&(yield K.race([Ee.onlineWaiter,Ue(n&&n.maxRetryTimeout||ge.maxRetryTimeout)])),h=Ee.networkState;const{data:p,headers:g}=yield er(o,{data:l,cancelToken:i,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);r=g.http3==="1"?1:-1,Z.reportResourceTiming(o,e.sid),Vw(p,o,e,c,a,r);const m=Wc(p,me.CHOOSE_SERVER),f=Wc(p,e.cloudProxyServer==="proxy5"?me.CLOUD_PROXY_5:e.cloudProxyServer==="proxy3"||e.cloudProxyServer==="proxy4"?me.CLOUD_PROXY:me.CLOUD_PROXY_FALLBACK);return jm(m),{gatewayInfo:Nm(m,o),proxyInfo:f,url:o}}),p=>(p.gatewayInfo&&Z.joinChooseServer(e.sid,{role:d,lts:c,succ:!0,csAddr:o,serverList:p.gatewayInfo.gatewayAddrs.map(g=>g.address),ec:null,opid:u,cid:p.gatewayInfo.cid.toString(),uid:p.gatewayInfo.uid.toString(),csIp:p.gatewayInfo.csIp,unilbsServerIds:a.toString(),isHttp3:r,corssRegionTagReq:e.apRequestDetail,corssRegionTagRes:p.gatewayInfo.res.detail&&p.gatewayInfo.res.detail[38]}),p.proxyInfo&&Z.joinWebProxyAP(e.sid,{lts:c,sucess:1,apServerAddr:o,turnServerAddrList:p.proxyInfo.addresses.map(g=>g.ip).join(","),errorCode:null,eventType:e.cloudProxyServer,unilbsServerIds:a.toString()}),!1),p=>p.code!==v.OPERATION_ABORTED&&(p.code===v.CAN_NOT_GET_GATEWAY_SERVER?p.data.retry:(Z.joinWebProxyAP(e.sid,{lts:c,sucess:0,apServerAddr:o,turnServerAddrList:null,errorCode:p.code,eventType:e.cloudProxyServer,unilbsServerIds:a.toString(),extend:JSON.stringify({networkState:h})}),_.warning("[".concat(e.clientId,"] multi unilbs network error, retry"),p),!0)),n)}const Vw=(t,e,i,n,r,o)=>{const{sid:s,clientId:a,cloudProxyServer:c}=i,d=[],l=u=>{u.flag===4096?Z.joinChooseServer(s,{role:i.role,lts:n,succ:!1,csAddr:e,opid:t.opid,serverList:null,ec:u.error.message,csIp:u.error.data&&u.error.data.csIp,unilbsServerIds:r.toString(),isHttp3:o,corssRegionTagReq:i.apRequestDetail}):u.flag!==1048576&&u.flag!==4194304&&u.flag!==4194310||Z.joinWebProxyAP(s,{lts:n,sucess:0,apServerAddr:e,turnServerAddrList:null,errorCode:u.error.code,eventType:c,unilbsServerIds:r.toString()})};if(t.response_body.forEach(u=>{const h=u.buffer.code;if(u.uri===23&&h===0&&!u.buffer.edges_services)if(u.buffer.flag===4194310)_.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers"),u.buffer.edges_services=[];else{const p={error:new P(v.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:t.detail[502]}),flag:u.buffer.flag};d.push(p),l(p)}if(h!==0){const p=Ia(h),g={error:new P(v.CAN_NOT_GET_GATEWAY_SERVER,p.desc,{desc:p.desc,retry:p.retry,csIp:t.detail[502]}),flag:u.buffer.flag};u.buffer.flag===4194310?_.warning(g.error.toString()):d.push(g),l(g)}}),d.length)throw _.warning("[".concat(a||"sid-".concat(s.slice(0,6)),"] multi unilbs ").concat(e," failed, ").concat(d.map(u=>"flag: ".concat(u.flag,", message: ").concat(u.error.message,", retry: ").concat(u.error.data.retry)).join(" | "))),new P(v.CAN_NOT_GET_GATEWAY_SERVER,d.map(u=>"flag: ".concat(u.flag,", message: ").concat(u.error.message)).join(" | "),{retry:!!d.find(u=>u.error.data.retry),csIp:t.detail[502],desc:[...new Set(d.map(u=>{var h;return u==null||(h=u.error)===null||h===void 0||(h=h.data)===null||h===void 0?void 0:h.desc}).filter(u=>!!u))]})},jm=t=>{var e,i,n,r;if(t.addresses&&t.addresses.length===0&&t.code===0)throw new P(v.CAN_NOT_GET_GATEWAY_SERVER,"void gateway address",{retry:!0,csIp:t.detail&&t.detail[502]});if(y("AP_AREA")&&((n=t.detail)!==null&&n!==void 0&&n[23]&&typeof((r=t.detail)===null||r===void 0?void 0:r[23])=="string"?kw(t.detail[23].toLowerCase()):kw()),(e=t.detail)!==null&&e!==void 0&&e[19]&&typeof((i=t.detail)===null||i===void 0?void 0:i[19])=="string"){const s=t.detail[19],a=s==null?void 0:s.split(";");for(let c=0;c<a.length;c++){var o;const d=ni(o=a[c]).call(o);t.addresses[c]&&a&&(t.addresses[c].fingerprint=d)}}if(y("GATEWAY_ADDRESS")&&y("GATEWAY_ADDRESS").length>0){_.debug("assign gateway address to",y("GATEWAY_ADDRESS"));const s=y("GATEWAY_ADDRESS").map(a=>{var c,d;const l=(c=(d=t.addresses.find(u=>u.ip===a.ip&&u.port===a.port))===null||d===void 0?void 0:d.fingerprint)!==null&&c!==void 0?c:"";return{ip:a.ip,port:a.port,ticket:t.addresses[0]&&t.addresses[0].ticket,fingerprint:l}});t.addresses=s}},TW=(t,e)=>{if(t.response_body&&t.response_body.length){const i=t.response_body[0];if(i.buffer.code!==0){const n=Ia(i.buffer.code);throw new P(v.UPDATE_TICKET_FAILED,"[".concat(i.buffer.code,"]: ").concat(n.desc),{retry:n.retry})}return i.buffer.ticket}throw _.debug("update ticket request received ap response without response body:",e),new P(v.UPDATE_TICKET_FAILED,"cannot find response body from ap response",{retry:!1})},Gm=(t,e,i)=>{const n=Math.floor(Math.random()*1e12),r=t.role==="host"?"1":t.role==="audience"?"2":void 0,o={appid:t.appId,client_ts:Date.now(),opid:n,sid:t.sid,request_bodies:[{uri:22,buffer:{cname:t.cname,detail:vr(vr(vr({6:t.stringUid,11:e,12:y("USE_NEW_TOKEN")?"1":void 0},r?{17:r}:{}),{},{22:e},t.apRequestDetail?{33:t.apRequestDetail}:{}),t.apRTM?{26:"RTM2"}:{}),key:t.token,service_ids:i,uid:t.uid||0}}]};o.request_bodies.forEach(a=>{t.multiIP&&t.multiIP.gateway_ip&&(a.buffer.detail[5]=JSON.stringify({vocs_ip:[t.multiIP.uni_lbs_ip],vos_ip:[t.multiIP.gateway_ip]}))});const s=new FormData;return s.append("request",JSON.stringify(o)),[s,n]},RW=(t,e)=>{const i=Math.floor(Math.random()*1e12),n={appid:t.appId,client_ts:Date.now(),opid:i,sid:t.sid,request_bodies:[{uri:28,buffer:{cname:t.cname,detail:{1:"",6:t.stringUid,12:"1"},token:t.token,service_ids:e,uid:t.uid||0,edges_services:t.apResponse.addresses.map(o=>({ip:o.ip,port:o.port}))}}]},r=new FormData;return r.append("request",JSON.stringify(n)),[r,i]};let Oa=0;function Na(t){return K.all(t.map(e=>e.then(i=>{throw i},i=>i))).then(e=>{throw e},e=>e)}const zc=t=>C(this,null,function*(){let{fragementLength:e,referenceList:i,asyncMapHandler:n,allFailedhandler:r,promisesCollector:o}=t,s=0;const a=e;let c,d=0;const l=()=>C(this,null,function*(){const u=(()=>{const h=s*a,p=h+a;return i.slice(h,p).map(n)})();o&&o.push(...u);try{c=yield Na(u)}catch(h){if(d+=a,s++,!(d>=i.length))return void(yield l());r(h)}u.forEach(h=>h.cancel())});return yield l(),c}),Fw=t=>C(this,null,function*(){let{referenceList:e,asyncMapHandler:i,closeFn:n}=t;const r=e.length;let o=0;const s=()=>C(this,null,function*(){const a=i(e.shift());try{return yield a}catch(c){if(o++,o>=r||n!=null&&n(c))throw c;return s()}});return s()});function Wm(t,e,i,n){return C(this,null,function*(){return{gatewayInfo:yield function(o,s,a,c){return C(this,null,function*(){let d=null;const l=[],u=()=>C(this,null,function*(){const p=y("WEBCS_DOMAIN").slice(0,y("AJAX_REQUEST_CONCURRENT")).map(f=>({url:o.proxyServer?"https://".concat(o.proxyServer,"/ap/?url=").concat(f+"/api/v2/transpond/webrtc?v=2"):"https://".concat(f,"/api/v2/transpond/webrtc?v=2"),areaCode:qc()})),g=c.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:p.map(f=>f.url)}),m=yield zc({fragementLength:y("FRAGEMENT_LENGTH"),referenceList:p,asyncMapHandler:f=>(_.debug("[".concat(o.clientId,"] Connect to choose_server:"),f.url),Uw(f,o,s,a)),allFailedhandler:f=>{throw c.recordJoinChannelService({endTs:Date.now(),status:"error",errors:f},g),f[0]},promisesCollector:l});return c.recordJoinChannelService({endTs:Date.now(),status:"success"},g),m}),h=()=>C(this,null,function*(){if(yield Ue(1e3),d!==null)return d;const p=y("WEBCS_DOMAIN_BACKUP_LIST").map(f=>({url:o.proxyServer?"https://".concat(o.proxyServer,"/ap/?url=").concat(f+"/api/v2/transpond/webrtc?v=2"):"https://".concat(f,"/api/v2/transpond/webrtc?v=2"),areaCode:qc()})),g=c.recordJoinChannelService({endTs:void 0,startTs:Date.now(),status:"pending",service:"chooseServer",urls:p.map(f=>f.url)}),m=yield zc({fragementLength:y("FRAGEMENT_LENGTH"),referenceList:p,asyncMapHandler:f=>(_.debug("[".concat(o.clientId,"] Connect to backup choose_server:"),f.url),Uw(f,o,s,a)),allFailedhandler:f=>{throw c.recordJoinChannelService({endTs:Date.now(),status:"error",errors:f},g),f[0]},promisesCollector:l});return c.recordJoinChannelService({endTs:Date.now(),status:"success"},g),m});try{return d=yield Na([u(),h()]),l.length&&l.forEach(p=>p.cancel&&typeof p.cancel=="function"&&p.cancel()),d}catch(p){throw p[0]}})}(t,e,i,n)}})}function Bw(t,e,i,n,r){return C(this,null,function*(){const o=t.cloudProxyServer;if(o==="disabled"){if(t.useLocalAccessPoint)return yield Wm(t,e,i,r);if(y("JOIN_WITH_FALLBACK_MEDIA_PROXY")){const{gatewayInfo:h,proxyInfo:p}=yield Ww(t,e,i,r);if(t.turnServer&&t.turnServer.mode!=="auto")return{gatewayInfo:h};const g=p.map(m=>({turnServerURL:m.address,tcpport:m.tcpport||He.tcpport,udpport:m.udpport||He.udpport,username:m.username||He.username,password:m.password||He.password,forceturn:!1,security:!0}));if(r.useP2P){var s;const m=(s=t.uid)!==null&&s!==void 0?s:h.uid,f="glb:".concat(m.toString()),T=yield kE(f),R=p.map(A=>({turnServerURL:A.address,tcpport:A.tcpport||He.tcpport,udpport:A.udpport||He.udpport,username:f,password:T,forceturn:!1,security:!0}));g.push(...R)}return t.turnServer={mode:"manual",servers:g},{gatewayInfo:h}}return yield Wm(t,e,i,r)}const{proxyInfo:a,gatewayInfo:c}=yield Ww(t,e,i,r),d={gatewayInfo:c},l=a.map(h=>({turnServerURL:h.address,tcpport:o==="proxy3"?void 0:h.tcpport?h.tcpport:He.tcpport,udpport:o==="proxy4"?void 0:h.udpport?h.udpport:He.udpport,username:h.username||He.username,password:h.password||He.password,forceturn:o!=="proxy4",security:o==="proxy5"}));if(r.useP2P){var u;const h=(u=t.uid)!==null&&u!==void 0?u:c.uid,p="glb:".concat(h.toString()),g=yield kE(p),m=a.map(f=>({turnServerURL:f.address,tcpport:o==="proxy3"?void 0:f.tcpport||He.tcpport,udpport:o==="proxy4"?void 0:f.udpport||He.udpport,username:p,password:g,forceturn:o!=="proxy4",security:o==="proxy5"}));l.push(...m)}return t.turnServer={mode:"manual",servers:l},_.debug("[".concat(t.clientId,"] set proxy server: ").concat(t.proxyServer,", mode: ").concat(o)),d})}function jw(t,e,i,n,r){return C(this,null,function*(){const o=y("ACCOUNT_REGISTER").slice(0,y("AJAX_REQUEST_CONCURRENT"));let s=[];s=e.proxyServer?o.map(c=>"https://".concat(e.proxyServer,"/ap/?url=").concat(c+"/api/v1")):o.map(c=>"https://".concat(c,"/api/v1"));const a=r==null?void 0:r.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"stringUID",urls:s});try{const c=yield function(d,l,u,h,p){return C(this,null,function*(){const g=Date.now(),m={sid:u.sid,opid:10,appid:u.appId,string_uid:l};let f=d[0];const T=yield Jn(()=>er(f+"".concat(f.indexOf("?")===-1?"?":"&","action=stringuid"),{data:m,cancelToken:h,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}}),(R,A)=>{if(R.code===0){if(R.uid<=0||R.uid>=Math.pow(2,32))throw _.error("Invalid Uint Uid ".concat(l," => ").concat(R.uid),R),Z.reqUserAccount(m.sid,{lts:g,success:!1,serverAddr:f,stringUid:m.string_uid,uid:R.uid,errorCode:v.INVALID_UINT_UID_FROM_STRING_UID,extend:m}),new P(v.INVALID_UINT_UID_FROM_STRING_UID);return Z.reqUserAccount(m.sid,{lts:g,success:!0,serverAddr:f,stringUid:m.string_uid,uid:R.uid,errorCode:null,extend:m}),!1}const N=Ia(R.code);return N.retry&&(f=d[(A+1)%d.length]),Z.reqUserAccount(m.sid,{lts:g,success:!1,serverAddr:f,stringUid:m.string_uid,uid:R.uid,errorCode:N.desc,extend:m}),N.retry},(R,A)=>R.code!==v.OPERATION_ABORTED&&(Z.reqUserAccount(m.sid,{lts:g,success:!1,serverAddr:f,stringUid:m.string_uid,uid:null,errorCode:R.code,extend:m}),f=d[(A+1)%d.length],!0),p);if(T.code!==0){const R=Ia(T.code);throw new P(v.UNEXPECTED_RESPONSE,R.desc)}return T})}(s,t,e,i,n);return r==null||r.recordJoinChannelService({status:"success",endTs:Date.now()},a),c.uid}catch(c){throw r==null||r.recordJoinChannelService({status:"error",endTs:Date.now(),errors:[c]},a),c}})}function vW(t,e,i){return C(this,null,function*(){const n=y("ACCOUNT_REGISTER");let r=[];r=e.proxyServer?n.map(o=>"https://".concat(e.proxyServer,"/ap/?url=").concat(o+"/api/v1")):n.map(o=>"https://".concat(o,"/api/v1"));try{return yield Fw({referenceList:r,asyncMapHandler:s=>function(a,c,d,l){return C(this,null,function*(){const u=Date.now(),h={sid:d.sid,opid:10,appid:d.appId,string_uid:c};try{const p=yield er(a+"".concat(a.indexOf("?")===-1?"?":"&","action=stringuid"),{data:h,cancelToken:l,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":72}});if(p.code!==0){const g=Ia(p.code);throw new P(v.UNEXPECTED_RESPONSE,"preload sua error:".concat(g.desc),g)}if(p.uid<=0||p.uid>=Math.pow(2,32))throw new P(v.INVALID_UINT_UID_FROM_STRING_UID);return{requestTime:u,url:a,req:h,uid:p.uid,elapse:Date.now()-u}}catch(p){throw p}})}(s,t,e,i),closeFn:s=>s.code===v.OPERATION_ABORTED||s.code===v.UNEXPECTED_RESPONSE&&!s.data.retry})}catch(o){throw o}})}function CW(t,e,i){return C(this,null,function*(){const n=y("CDS_AP").slice(0,y("AJAX_REQUEST_CONCURRENT")).map(c=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(c+"/api/v1"):"https://".concat(c,"/api/v1?action=config")),r=n.map(c=>function(d,l,u,h){const p=vt(),g={flag:64,cipher_method:0,features:vr(vr(vr(vr(vr({install_id:YE(),device:p.name,system:p.os,system_general:navigator.userAgent,vendor:l.appId,version:dn,cname:l.cname,session_id:l.sid,proxyServer:l.proxyServer,sdk_type:_W.WEB_RTC,browser_name:p.name,browser_version:p.version,user_agent:navigator.userAgent,channel_name:l.cname},l.stringUid&&{string_uid:l.stringUid}),l.uid&&{uid:l.uid+""}),p.os&&{os_name:p.os}),p.osVersion&&{os_version:p.osVersion}),{},{detail:""})};return Jn(()=>er(d,{data:g,timeout:1e3,cancelToken:u,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":54}}),void 0,m=>m.code!==v.OPERATION_ABORTED,h)}(c,t,e,i));let o=null,s=null,a={};try{o=yield Na(r)}catch(c){if(c.code===v.OPERATION_ABORTED)throw c;s=c}if(r.forEach(c=>c.cancel()),Z.reportApiInvoke(t.sid,{name:_e.REQUEST_CONFIG_DISTRIBUTE,options:{error:s,res:o}}).onSuccess(),o&&o.test_tags)try{a=function(c){if(!c.test_tags)return{};const d=c.test_tags,l=Object.keys(d),u={};return l.forEach(h=>{var p;const g=ni(p=h.slice(4)).call(p),m=JSON.parse(d[h]),f=m[1];u[g]={tag:m[0]||"",value:f}}),u}(o)}catch(c){}return a})}function Gw(t,e){return C(this,null,function*(){const i=y("WEBCS_DOMAIN").concat(y("WEBCS_DOMAIN_BACKUP_LIST")).map(n=>({url:"https://".concat(n,"/api/v2/transpond/webrtc?v=2"),areaCode:qc(),serviceIds:[me.CHOOSE_SERVER,me.CLOUD_PROXY_FALLBACK]}));try{return yield Fw({referenceList:i,asyncMapHandler:r=>function(o,s,a){return C(this,null,function*(){let c,{url:d,areaCode:l,serviceIds:u}=o;const h=Date.now(),[p,g]=Gm(s,l,u);let m=Ee.networkState;try{m&&Ee.networkState===Fi.OFFLINE&&Ee.onlineWaiter&&(yield K.race([Ee.onlineWaiter,Ue(ge.maxRetryTimeout)])),m=Ee.networkState;const{data:f,headers:T}=yield er(d,{data:p,cancelToken:a,headers:{"Content-Type":"multipart/form-data;"}},!0,!0);c=T.http3==="1"?1:-1,(O=>{const w=[];if(O.response_body.forEach(L=>{const M=L.buffer.code;if(L.uri===23&&M===0&&!L.buffer.edges_services)if(L.buffer.flag===4194310)L.buffer.edges_services=[];else{const j={error:new P(v.CAN_NOT_GET_GATEWAY_SERVER,"no edge services in ap response",{retry:!0,csIp:O.detail[502]}),flag:L.buffer.flag};w.push(j)}if(M!==0){const j=Ia(M),H={error:new P(v.CAN_NOT_GET_GATEWAY_SERVER,j.desc,{desc:j.desc,retry:j.retry,csIp:O.detail[502]}),flag:L.buffer.flag};L.buffer.flag===4194310?_.warning(H.error.toString()):w.push(H)}}),w.length)throw new P(v.CAN_NOT_GET_GATEWAY_SERVER,w.map(L=>"flag: ".concat(L.flag,", message: ").concat(L.error.message)).join(" | "),{retry:!!w.find(L=>L.error.data.retry),csIp:O.detail[502],desc:[...new Set(w.map(L=>{var M;return L==null||(M=L.error)===null||M===void 0||(M=M.data)===null||M===void 0?void 0:M.desc}).filter(L=>!!L))]})})(f);const A=Wc(f,me.CHOOSE_SERVER),N=Wc(f,me.CLOUD_PROXY_FALLBACK);return jm(A),{gatewayInfo:Nm(A,d),proxyInfo:N,opid:g,requestTime:h,url:d,isHttp3:c,elapse:Date.now()-h}}catch(f){throw f}})}(r,t,e),closeFn:r=>r.code===v.OPERATION_ABORTED||r.code===v.CAN_NOT_GET_GATEWAY_SERVER&&!r.data.retry})}catch(n){throw n}})}function Ww(t,e,i,n){return C(this,null,function*(){const r=y("PROXY_SERVER_TYPE3"),o=(p,g,m)=>{let f=m||r;return Array.isArray(f)&&(f=g%2==0?r[1]:r[0]),"https://".concat(f,"/ap/?url=").concat(p)};let s=null;const a=[],c=()=>C(this,null,function*(){const p=y("WEBCS_DOMAIN").slice(0,y("AJAX_REQUEST_CONCURRENT")).map((f,T)=>{let R;return R=t.cloudProxyServer==="disabled"&&t.proxyServer?o("".concat(f,"/api/v2/transpond/webrtc?v=2"),T,t.proxyServer):t.cloudProxyServer==="disabled"||t.cloudProxyServer==="fallback"?"https://".concat(f,"/api/v2/transpond/webrtc?v=2"):o("".concat(f,"/api/v2/transpond/webrtc?v=2"),T),{url:R,areaCode:qc(),serviceIds:[me.CHOOSE_SERVER,t.cloudProxyServer==="proxy5"?me.CLOUD_PROXY_5:t.cloudProxyServer==="proxy3"||t.cloudProxyServer==="proxy4"?me.CLOUD_PROXY:me.CLOUD_PROXY_FALLBACK]}}),g=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:p.map(f=>f.url)}),m=yield zc({fragementLength:y("FRAGEMENT_LENGTH"),referenceList:p,asyncMapHandler:f=>(_.debug("[".concat(t.clientId,"] Connect to choose_server:"),f.url),xw(f,t,e,i)),allFailedhandler:f=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:f},g),f[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},g),m}),d=()=>C(this,null,function*(){if(yield Ue(1e3),s!==null)return s;const p=y("WEBCS_DOMAIN_BACKUP_LIST").map((f,T)=>{let R;return R=t.cloudProxyServer==="disabled"&&t.proxyServer?o("".concat(f,"/api/v2/transpond/webrtc?v=2"),T,t.proxyServer):t.cloudProxyServer==="disabled"||t.cloudProxyServer==="fallback"?"https://".concat(f,"/api/v2/transpond/webrtc?v=2"):o("".concat(f,"/api/v2/transpond/webrtc?v=2"),T),{url:R,areaCode:qc(),serviceIds:[me.CHOOSE_SERVER,t.cloudProxyServer==="proxy5"?me.CLOUD_PROXY_5:t.cloudProxyServer==="proxy3"||t.cloudProxyServer==="proxy4"?me.CLOUD_PROXY:me.CLOUD_PROXY_FALLBACK]}}),g=n.recordJoinChannelService({startTs:Date.now(),status:"pending",service:"chooseServer",urls:p.map(f=>f.url)}),m=yield zc({fragementLength:y("FRAGEMENT_LENGTH"),referenceList:p,asyncMapHandler:f=>(_.debug("[".concat(t.clientId,"] Connect to backup choose_server:"),f.url),xw(f,t,e,i)),allFailedhandler:f=>{throw n.recordJoinChannelService({endTs:Date.now(),status:"error",errors:f},g),f[0]},promisesCollector:a});return n.recordJoinChannelService({endTs:Date.now(),status:"success"},g),m});let l,u,h;try{({gatewayInfo:l,proxyInfo:u,url:h}=yield Na([c(),d()]))}catch(p){throw p[0]}if(a.length&&a.forEach(p=>p.cancel&&typeof p.cancel=="function"&&p.cancel()),!l||!u)throw new P(v.UNEXPECTED_ERROR,"missing gateway or proxy response").print();if(t.apUrl=h,t.cloudProxyServer!=="disabled"&&Array.isArray(r)&&h){const p=/^https?:\/\/(.+?)(\/.*)?$/.exec(h)[1];G(r).call(r,p)&&(t.proxyServer=p,_.setProxyServer(p),Z.setProxyServer(p))}return s={gatewayInfo:l,proxyInfo:yield pw(u,l.uid)},s})}function yW(t,e,i){return C(this,null,function*(){const n=y("UAP_AP").slice(0,y("AJAX_REQUEST_CONCURRENT")).map(o=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(o+"/api/v1?action=uap"):"https://".concat(o,"/api/v1?action=uap")),r=n.map(o=>function(s,a,c,d){const l={command:"convergeAllocateEdge",sid:a.sid,appId:a.appId,token:a.token,ts:Date.now(),version:dn,cname:a.cname,uid:a.uid.toString(),requestId:Bm,seq:Bm};Bm+=1;const u={service_name:"tele_channel",json_body:JSON.stringify(l)};return Jn(()=>C(this,null,function*(){const h=yield er(s,{data:u,cancelToken:c,headers:{"X-Packet-Service-Type":0,"X-Packet-URI":61}});if(h.code!==0){const g=new P(v.UNEXPECTED_RESPONSE,"cross channel ap error, code"+h.code,{retry:!0});throw _.error(g.toString()),g}const p=JSON.parse(h.json_body);if(p.code!==200){const g=new P(v.UNEXPECTED_RESPONSE,"cross channel app center error, code: ".concat(p.code,", reason: ").concat(p.reason));throw _.error(g.toString()),g}if(!p.servers||p.servers.length===0){const g=new P(v.UNEXPECTED_RESPONSE,"cross channel app center empty server");throw _.error(g.toString()),g}return{vid:p.vid,workerToken:p.workerToken,addressList:(y("CHANNEL_MEDIA_RELAY_SERVERS")||p.servers).map(g=>"wss://".concat(g.address.replace(/\./g,"-"),".").concat(y("WORKER_DOMAIN"),":").concat(g.wss))}}),void 0,h=>!!(h.code!==v.OPERATION_ABORTED&&h.code!==v.UNEXPECTED_RESPONSE||h.data&&h.data.retry),d)}(o,t,e,i));try{const o=yield Na(r);return r.forEach(s=>s.cancel()),o}catch(o){throw o[0]}})}function IW(t,e,i){return C(this,null,function*(){let n=null;const r=[],o=s=>C(this,null,function*(){const a=y(s?"WEBCS_DOMAIN_BACKUP_LIST":"WEBCS_DOMAIN").map(c=>t.proxyServer?"https://".concat(t.proxyServer,"/ap/?url=").concat(c+"/api/v2/transpond/webrtc?v=2"):"https://".concat(c,"/api/v2/transpond/webrtc?v=2"));return s&&(yield Ue(1e3),n!==null)?n:yield zc({fragementLength:y("FRAGEMENT_LENGTH"),referenceList:a,asyncMapHandler:c=>(_.debug("[".concat(t.clientId,"] update ticket, Connect to ").concat(s?"backup":""," choose_server:"),c),function(d,l,u,h){const[p]=RW(l,[me.CHOOSE_SERVER]);let g=Ee.networkState;return Jn(()=>C(this,null,function*(){g&&Ee.networkState===Fi.OFFLINE&&Ee.onlineWaiter&&(yield K.race([Ee.onlineWaiter,Ue(h&&h.maxRetryTimeout||ge.maxRetryTimeout)])),g=Ee.networkState;const m=yield er(d,{data:p,cancelToken:u,headers:{"Content-Type":"multipart/form-data;"}},!0);return TW(m,d)}),()=>!1,m=>m.code!==v.OPERATION_ABORTED&&(m.code===v.UPDATE_TICKET_FAILED?m.data.retry:(_.warning("[".concat(l.clientId,"] update ticket network error, retry"),m),!0)),h)}(c,t,e,i)),allFailedhandler:c=>{throw c[0]},promisesCollector:r})});try{return n=yield Na([o(!1),o(!0)]),r.length&&r.forEach(s=>s.cancel&&typeof s.cancel=="function"&&s.cancel()),n}catch(s){throw s[0]}})}function Hw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Hm(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?Hw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):Hw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}class AW extends $t{get isSuccess(){return!!this.configs}constructor(e,i){super(),S(this,"configs",void 0),S(this,"store",void 0),S(this,"joinInfo",void 0),S(this,"cancelToken",void 0),S(this,"retryConfig",{timeout:3e3,timeoutFactor:1.5,maxRetryCount:1,maxRetryTimeout:1e4}),S(this,"interval",void 0),S(this,"mutex",void 0),S(this,"mutableParamsRead",!1),S(this,"configCache",{}),S(this,"limit_bitrate",void 0),this.mutex=new qe("config-distribute",e),this.store=i}startGetConfigDistribute(e,i){this.joinInfo=e,this.cancelToken=i,this.interval&&this.stopGetConfigDistribute(),y("ENABLE_CONFIG_DISTRIBUTE")&&(this.updateConfigDistribute(),this.interval=window.setInterval(()=>{this.updateConfigDistribute()},y("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}awaitConfigDistributeComplete(){return C(this,null,function*(){this.mutex.isLocked&&(yield this.mutex.lock())()})}updateConfigDistribute(){return C(this,null,function*(){if(this.mutableParamsRead||(this.mutableParamsRead=!0,Z.reportApiInvoke(null,{options:void 0,name:_e.LOAD_CONFIG_FROM_LOCALSTORAGE,tag:oe.TRACER}).onSuccess(JSON.stringify(Qn))),!this.joinInfo||!this.cancelToken||!this.retryConfig)return void _.debug("[config-distribute] get config distribute interrupted have no joininfo");let e;const i=yield this.mutex.lock();try{e=yield CW(this.joinInfo,this.cancelToken,this.retryConfig),_.debug("[config-distribute] get config distribute",JSON.stringify(e));const n=function(r){var o;const s=jo(o=Object.keys(r).filter(d=>/^webrtc_ng_global_parameter/.test(d))).call(o);for(let d=0;d<s.length;d++)for(let l=s.length-1;l>d;l--){const u=s[l],h=r[u].value;if(typeof h.__priority=="number"){const p=h.__priority,g=s[l-1],m=r[g].value;if(typeof m.__priority=="number"){if(!(p>m.__priority))continue;{const f=u;s[l]=s[l-1],s[l-1]=f}}else{const f=u;s[l]=s[l-1],s[l-1]=f}}}const a=Date.now();let c={};return s.forEach(d=>{const l=r[d].value.__expires;l&&l<=a||(c[d]=r[d])}),c}(e);this.cacheGlobalParameterConfig(n),this.store.hasStartJoinChannel||(this.store.isABTestSuccess=!0),this.configs=n}catch(n){const r=new P(v.NETWORK_RESPONSE_ERROR,n);_.warning("[config-distribute] ".concat(r.toString()))}finally{i()}})}getBitrateLimit(){return this.limit_bitrate||void 0}handleBitrateLimit(e){iw(e)&&(this.limit_bitrate?this.limit_bitrate&&this.limit_bitrate.id!==e.id&&this.emit(Bc.UPDATE_BITRATE_LIMIT,e):this.emit(Bc.UPDATE_BITRATE_LIMIT,e))}getLowStreamConfigDistribute(){return this.limit_bitrate&&Hm({},this.limit_bitrate.low_stream_uplink)}handleABTestConfigDistribute(e){try{const i={},n=Object.keys(e),r=[];n.forEach(o=>{const s=e[o].value;i[o]=s;const a=s.__id;if(a&&this.configCache[o]&&this.configCache[o].__id===a)return;const c=s.__type,d=e[o].value,l=e[o].tag;let u=0;c?c===NI.REALTIME&&(u=1):Object.keys(d).some(h=>Object.prototype.hasOwnProperty.call(JE,h)||!Sm()&&Object.prototype.hasOwnProperty.call(_u,h)?(u=1,!0):void 0),r.push({tag:l,isApplied:u,feature:o,params:JSON.stringify(s)})}),r.forEach(o=>{let{tag:s,feature:a,params:c,isApplied:d}=o;this.store.sessionId&&Z.abTest(this.store.sessionId,{intSucc:1,isApplied:d,tag:s,feature:a,params:c,cid:this.store.cid,uid:this.store.intUid})}),this.configCache=i}catch(i){_.debug("handleABTestConfigDistribute error",i)}}cacheGlobalParameterConfig(e){const i=function(r){const o={};return Object.keys(r).forEach(s=>{const a=r[s].value,c=a.__expires,d=a.__type;Object.keys(a).forEach(l=>{l==="__id"||l==="__type"||l==="__priority"||l==="__expires"||Object.prototype.hasOwnProperty.call(o,l)||(o[l]=Hm(Hm({value:a[l]},c&&{expires:c}),d&&{type:d}))})}),o}(e);try{var n;const r=(n=i.LIMIT_BITRATE)===null||n===void 0?void 0:n.value;delete i.LIMIT_BITRATE,r&&iw(r)&&this.handleBitrateLimit(r),this.limit_bitrate=r,this.handleGlobalParameterConfig(i),this.handleABTestConfigDistribute(e),function(a){try{const c=Date.now();Object.keys(a).forEach(d=>{const{value:l,type:u,expires:h}=a[d];h&&h<=c||((u===NI.REALTIME||Object.prototype.hasOwnProperty.call(JE,d))&&(Qn[d]=l,Xt[d]=l,_.debug("Update realtime parameters from config distribute",d,l)),u||Sm()||!Object.prototype.hasOwnProperty.call(_u,d)||(Qn[d]=l,Xt[d]=l,_.debug("Update gateway parameters from config distribute",d,l)))})}catch(c){_.error("Error update config immediately: ".concat(a),c.message)}}(i);const o=JSON.stringify(i),s=window.btoa(o);window.localStorage.setItem("websdk_ng_global_parameter",s),_.debug("Caching global parameters ".concat(o))}catch(r){_.error("Error caching global parameters:",r.message)}}handleGlobalParameterConfig(e){try{const i=Date.now();Object.keys(e).forEach(n=>{if(n==="CLIENT_ROLE_OPTIONS"&&Object.prototype.hasOwnProperty.call(Xt,n)){const{value:r,expires:o}=e[n];if(o&&o<=i)return;(function(s,a){try{return typeof s=="object"&&typeof a=="object"&&JSON.stringify(s)===JSON.stringify(a)}catch(c){return!1}})(Xt[n],r)||(Qn[n]=r,Xt[n]=r,this.emit(Bc.UPDATE_CLIENT_ROLE_OPTIONS,r),_.debug("Updating client role options: ".concat(JSON.stringify(r))))}})}catch(i){_.error("Error handling global parameter config:",i.message)}}}class bW extends $t{constructor(){super(...arguments),S(this,"resultStorage",new Map)}setLocalAudioStats(e,i,n){this.record("AUDIO_INPUT_LEVEL_TOO_LOW",e,this.checkAudioInputLevel(n,i)),this.record("SEND_AUDIO_BITRATE_TOO_LOW",e,this.checkSendAudioBitrate(n,i))}setLocalVideoStats(e,i,n){this.record("SEND_VIDEO_BITRATE_TOO_LOW",e,this.checkSendVideoBitrate(n,i)),this.record("FRAMERATE_INPUT_TOO_LOW",e,this.checkFramerateInput(n,i)),this.record("FRAMERATE_SENT_TOO_LOW",e,this.checkFramerateSent(n))}setRemoteAudioStats(e,i){const n=e.getUserId();this.record("AUDIO_OUTPUT_LEVEL_TOO_LOW",n,this.checkAudioOutputLevel(i))}setRemoteVideoStats(e,i){const n=e.getUserId();this.record("RECV_VIDEO_DECODE_FAILED",n,this.checkVideoDecode(i))}record(e,i,n){if(y("STATS_UPDATE_INTERVAL")>500)return;this.resultStorage.has(e)||this.resultStorage.set(e,{result:[],isPrevNormal:!0});const r=this.resultStorage.get(e);if(r&&(r.result.push(n),r.result.length>=5)){var o;const s=G(o=r.result).call(o,!0);r.isPrevNormal&&!s&&this.emit("exception",Kw[e],e,i),!r.isPrevNormal&&s&&this.emit("exception",Kw[e]+2e3,e+"_RECOVER",i),r.isPrevNormal=s,r.result=[]}}checkAudioOutputLevel(e){return!(e.receiveBitrate>0&&e.receiveLevel===0)}checkAudioInputLevel(e,i){return i instanceof ve&&!i.isActive||!!i.muted||e.sendVolumeLevel!==0}checkFramerateInput(e,i){let n=null;i._encoderConfig&&i._encoderConfig.frameRate&&(n=Bi(i._encoderConfig.frameRate));const r=e.captureFrameRate;return!n||!r||!(n>10&&r<5||n<10&&n>=5&&r<=1)}checkFramerateSent(e){return!(e.captureFrameRate&&e.sendFrameRate&&e.captureFrameRate>5&&e.sendFrameRate<=1)}checkSendVideoBitrate(e,i){return!!i.muted||e.sendBitrate!==0}checkSendAudioBitrate(e,i){return i instanceof ve&&!i.isActive||!!i.muted||e.sendBitrate!==0}checkVideoDecode(e){return e.receiveBitrate===0||e.decodeFrameRate!==0}}const Kw={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},Je=new class{markSubscribeStart(t,e){performance.mark("agora-web-sdk/".concat(t,"/subscribe-").concat(e))}markPublishStart(t,e){performance.mark("agora-web-sdk/".concat(t,"/publish-").concat(e))}measureFromSubscribeStart(t,e){const i=performance.getEntriesByName("agora-web-sdk/".concat(t,"/subscribe-").concat(e));if(i.length>0){const n=i[i.length-1];return Math.round(performance.now()-n.startTime)}return 0}measureFromPublishStart(t,e){const i=performance.getEntriesByName("agora-web-sdk/".concat(t,"/publish-").concat(e));if(i.length>0){const n=i[i.length-1];return Math.round(performance.now()-n.startTime)}return 0}};function Yw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function cs(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?Yw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):Yw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}class Xc{constructor(e){S(this,"store",void 0),S(this,"onStatsException",void 0),S(this,"onUploadPublishDuration",void 0),S(this,"onStatsChanged",void 0),S(this,"onVideoCodecChanged",void 0),S(this,"localStats",new Map),S(this,"remoteStats",new Map),S(this,"updateStatsInterval",void 0),S(this,"trafficStats",void 0),S(this,"trafficStatsPeerList",[]),S(this,"uplinkStats",void 0),S(this,"exceptionMonitor",void 0),S(this,"p2pChannel",void 0),S(this,"scalabilityMode",pu.L1T1),S(this,"updateStats",()=>{this.p2pChannel&&(this.updateRemoteStats(this.p2pChannel),this.updateLocalStats(this.p2pChannel))}),this.store=e,this.exceptionMonitor=new bW,this.exceptionMonitor.on("exception",(i,n,r)=>{this.onStatsException&&this.onStatsException(i,n,r)})}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(V.LocalAudioTrack)||cs({},em)}getLocalVideoTrackStats(){return this.localStats.get(V.LocalVideoTrack)||cs({},im)}getRemoteAudioTrackStats(e){const i=(o,s)=>{if(!this.trafficStats)return s;const a=this.trafficStats.peer_delay.find(c=>c.peer_uid===o);return a&&(s.publishDuration=a.B_ppad+(Date.now()-this.trafficStats.timestamp)),s},n={};if(e){var r;const o=(r=this.remoteStats.get(e))===null||r===void 0?void 0:r.audioStats;o&&(n[e]=i(e,o))}else Array.from(this.remoteStats.entries()).forEach(o=>{let[s,{audioStats:a}]=o;a&&(n[s]=i(s,a))});return n}getRemoteNetworkQualityStats(e){const i={};if(e){var n;const r=(n=this.remoteStats.get(e))===null||n===void 0?void 0:n.networkStats;r&&(i[e]=r)}else Array.from(this.remoteStats.entries()).forEach(r=>{let[o,{networkStats:s}]=r;s&&(i[o]=s)});return i}getRemoteVideoTrackStats(e){const i=(o,s)=>{if(!this.trafficStats)return s;const a=this.trafficStats.peer_delay.find(c=>c.peer_uid===o);return a&&(s.publishDuration=a.B_ppvd+(Date.now()-this.trafficStats.timestamp)),s},n={};if(e){var r;const o=(r=this.remoteStats.get(e))===null||r===void 0?void 0:r.videoStats;o&&(n[e]=i(e,o))}else Array.from(this.remoteStats.entries()).forEach(o=>{let[s,{videoStats:a}]=o;a&&(n[s]=i(s,a))});return n}getRTCStats(){let e=0,i=0,n=0,r=0;const o=this.localStats.get(V.LocalAudioTrack);o&&(e+=o.sendBytes,i+=o.sendBitrate);const s=this.localStats.get(V.LocalVideoTrack);s&&(e+=s.sendBytes,i+=s.sendBitrate);const a=this.localStats.get(V.LocalVideoLowTrack);a&&(e+=a.sendBytes,i+=a.sendBitrate),this.remoteStats.forEach(d=>{let{audioStats:l,videoStats:u}=d;l&&(n+=l.receiveBytes,r+=l.receiveBitrate),u&&(n+=u.receiveBytes,r+=u.receiveBitrate)});let c=1;return this.trafficStats&&(c+=this.trafficStats.peer_delay.length),{Duration:0,UserCount:c,SendBitrate:i,SendBytes:e,RecvBytes:n,RecvBitrate:r,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(i=>i.B_ppad!==void 0||i.B_ppvd!==void 0),e.peer_delay.filter(i=>this.trafficStatsPeerList.indexOf(i.peer_uid)===-1).forEach(i=>{var n;const r=(n=this.p2pChannel)===null||n===void 0?void 0:n.getRemoteMedia(i.peer_uid),o=r!=null&&r.videoSSRC?Je.measureFromSubscribeStart(this.store.clientId,r.videoSSRC):0,s=r!=null&&r.audioSSRC?Je.measureFromSubscribeStart(this.store.clientId,r.audioSSRC):0;i.B_ppad!==void 0&&i.B_ppvd!==void 0&&(this.onUploadPublishDuration&&this.onUploadPublishDuration(i.peer_uid,i.B_ppad,i.B_ppvd,o>s?o:s),this.trafficStatsPeerList.push(i.peer_uid))}),this.trafficStats=e}updateUplinkStats(e){this.uplinkStats&&this.uplinkStats.B_fir!==e.B_fir&&_.debug("[".concat(this.store.clientId,"]: Period fir changes to ").concat(e.B_fir)),this.uplinkStats=e}static isRemoteVideoFreeze(e,i,n){if(!e)return!1;const r=!!n&&i.framesDecodeFreezeTime>n.framesDecodeFreezeTime,o=!n||i.framesDecodeCount>n.framesDecodeCount;return r||!o}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(i=>{let[n,r]=i;switch(n){case V.LocalVideoTrack:case V.LocalVideoLowTrack:{const a=r,c=cs({},im),d=e.getStats(),l=e.getLocalMedia(n);if(d){const u=d.videoSend.find(h=>h.ssrc===(l==null?void 0:l.ssrcs[0].ssrcId));if(u){const h=e.getLocalVideoSize(),p=e.getEncoderConfig(V.LocalVideoTrack);var o;(u.codec==="H264"||u.codec==="H265"||u.codec==="VP8"||u.codec==="VP9"||u.codec==="AV1X"||u.codec==="AV1")&&(c.codecType=u.codec,(a==null?void 0:a.codecType)!==u.codec&&((o=this.onVideoCodecChanged)===null||o===void 0||o.call(this,u.codec.toLocaleLowerCase()))),c.sendBytes=u.bytes,c.sendBitrate=a?8*Math.max(0,c.sendBytes-a.sendBytes):0,u.inputFrame?(c.captureFrameRate=u.inputFrame.frameRate,c.captureResolutionHeight=u.inputFrame.height,c.captureResolutionWidth=u.inputFrame.width):h&&(c.captureResolutionWidth=h.width,c.captureResolutionHeight=h.height),u.sentFrame?(c.sendFrameRate=u.sentFrame.frameRate,c.sendResolutionHeight=u.sentFrame.height,c.sendResolutionWidth=u.sentFrame.width):h&&(c.sendResolutionWidth=h.width,c.sendResolutionHeight=h.height),u.avgEncodeMs&&(c.encodeDelay=u.avgEncodeMs),p&&p.bitrateMax?c.targetSendBitrate=1e3*p.bitrateMax:u.targetBitrate&&(c.targetSendBitrate=u.targetBitrate),c.sendPackets=u.packets,c.sendPacketsLost=u.packetsLost,c.sendJitterMs=u.jitterMs,c.sendRttMs=u.rttMs,c.totalDuration=a?a.totalDuration+1:1,c.totalFreezeTime=a?a.totalFreezeTime:0,this.isLocalVideoFreeze(u)&&(c.totalFreezeTime+=1),u.scalabilityMode&&this.scalabilityMode!==u.scalabilityMode&&(_.debug("[".concat(this.store.clientId,"]: The scalabilityMode of the video sending stream is ").concat(u.scalabilityMode)),this.scalabilityMode=u.scalabilityMode)}this.trafficStats&&(c.currentPacketLossRate=(this.trafficStats.B_pvlr4||0)/100)}var s;this.localStats.set(n,c),((a==null?void 0:a.sendResolutionWidth)!==c.sendResolutionWidth||(a==null?void 0:a.sendResolutionHeight)!==c.sendResolutionHeight)&&((s=this.onStatsChanged)===null||s===void 0||s.call(this,"resolution",{width:c.sendResolutionWidth,height:c.sendResolutionHeight})),c&&l&&this.exceptionMonitor.setLocalVideoStats(this.store.uid,l.track,c);break}case V.LocalAudioTrack:{const a=r,c=cs({},em),d=e.getStats(),l=e.getLocalMedia(n);if(d){const u=d.audioSend.find(h=>h.ssrc===(l==null?void 0:l.ssrcs[0].ssrcId));if(u){if(u.codec!=="opus"&&u.codec!=="aac"&&u.codec!=="PCMU"&&u.codec!=="PCMA"&&u.codec!=="G722"||(c.codecType=u.codec),u.inputLevel)c.sendVolumeLevel=Math.round(32767*u.inputLevel);else{const h=e.getLocalAudioVolume();h&&(c.sendVolumeLevel=Math.round(32767*h))}c.sendBytes=u.bytes,c.sendPackets=u.packets,c.sendPacketsLost=u.packetsLost,c.sendJitterMs=u.jitterMs,c.sendRttMs=u.rttMs,c.sendBitrate=a?8*Math.max(0,c.sendBytes-a.sendBytes):0}}this.trafficStats&&(c.currentPacketLossRate=(this.trafficStats.B_palr4||0)/100),this.localStats.set(V.LocalAudioTrack,c),c&&l&&this.exceptionMonitor.setLocalAudioStats(this.store.uid,l.track,c);break}}})}updateRemoteStats(e){Array.from(this.remoteStats.entries()).forEach(i=>{var n,r;let[o,{videoStats:s,audioStats:a,videoPcStats:c}]=i;const d=a,l=s,u=c,h=cs({},jI),p=cs({},GI),g=cs({},l3),{audioTrack:m,videoTrack:f,audioSSRC:T,videoSSRC:R}=e.getRemoteMedia(o);let A;A=this.store.useP2P?e.getStats(!0):e.getStats();const N=(n=A)===null||n===void 0?void 0:n.audioRecv.find(M=>M.ssrc===T),O=(r=A)===null||r===void 0?void 0:r.videoRecv.find(M=>M.ssrc===R),w=this.trafficStats&&this.trafficStats.peer_delay.find(M=>M.peer_uid===o);if(N&&(N.codec!=="opus"&&N.codec!=="aac"&&N.codec!=="PCMU"&&N.codec!=="PCMA"&&N.codec!=="G722"||(h.codecType=N.codec),N.outputLevel?h.receiveLevel=Math.round(32767*N.outputLevel):m&&(h.receiveLevel=Math.round(32767*m.getVolumeLevel())),h.receiveBytes=N.bytes,h.receivePackets=N.packets,h.receivePacketsLost=N.packetsLost,h.receivePacketsDiscarded=N.packetsDiscarded,h.packetLossRate=h.receivePacketsLost/(h.receivePackets+h.receivePacketsLost),h.receiveBitrate=d?8*Math.max(0,h.receiveBytes-d.receiveBytes):0,h.totalDuration=d?d.totalDuration+1:1,h.totalFreezeTime=d?d.totalFreezeTime:0,h.freezeRate=h.totalFreezeTime/h.totalDuration,h.receiveDelay=N.jitterBufferMs,h.totalDuration>10&&Xc.isRemoteAudioFreeze(m)&&(h.totalFreezeTime+=1)),O){var L;O.codec!=="H264"&&O.codec!=="H265"&&O.codec!=="VP8"&&O.codec!=="VP9"&&O.codec!=="AV1X"&&O.codec!=="AV1"||(p.codecType=O.codec),p.receiveBytes=O.bytes,p.receiveBitrate=l?8*Math.max(0,p.receiveBytes-l.receiveBytes):0,p.decodeFrameRate=O.decodeFrameRate<0?0:O.decodeFrameRate,p.renderFrameRate=O.decodeFrameRate<0?0:O.decodeFrameRate,O.outputFrame&&(p.renderFrameRate=O.outputFrame.frameRate),O.receivedFrame?(p.receiveFrameRate=O.receivedFrame.frameRate,p.receiveResolutionHeight=O.receivedFrame.height,p.receiveResolutionWidth=O.receivedFrame.width):f&&(p.receiveResolutionHeight=f._videoHeight||0,p.receiveResolutionWidth=f._videoWidth||0),O.framesRateFirefox!==void 0&&(p.receiveFrameRate=Math.round(O.framesRateFirefox)),p.receivePackets=O.packets,p.receivePacketsLost=O.packetsLost,p.packetLossRate=p.receivePacketsLost/(p.receivePackets+p.receivePacketsLost);const M=l?l.totalFreezeTime:0,j=l?l.totalDuration:0;p.totalDuration=l?l.totalDuration+1:1,p.totalFreezeTime=(L=O.totalFreezesDuration)!==null&&L!==void 0?L:M||0,p.receiveDelay=O.jitterBufferMs||0;const H=!!R&&e.getRemoteVideoIsReady(R);O.totalFreezesDuration===void 0&&f&&H&&Xc.isRemoteVideoFreeze(f,O,u)&&(p.totalFreezeTime+=1),p.freezeRate=Math.max(0,Math.min((p.totalFreezeTime-M)/(p.totalDuration-j),1))}w&&(h.end2EndDelay=w.B_ad,p.end2EndDelay=w.B_vd,h.transportDelay=w.B_ed,p.transportDelay=w.B_ed,h.currentPacketLossRate=w.B_ealr4/100,p.currentPacketLossRate=w.B_evlr4/100,g.uplinkNetworkQuality=w.B_punq?w.B_punq:0,g.downlinkNetworkQuality=w.B_pdnq?w.B_pdnq:0),this.remoteStats.set(o,{audioStats:h,videoStats:p,videoPcStats:O,networkStats:g}),m&&this.exceptionMonitor.setRemoteAudioStats(m,h),f&&this.exceptionMonitor.setRemoteVideoStats(f,p)})}}class qw{constructor(){S(this,"destChannelMediaInfos",new Map),S(this,"srcChannelMediaInfo",void 0)}setSrcChannelInfo(e){tw(e),this.srcChannelMediaInfo=e}addDestChannelInfo(e){tw(e),this.destChannelMediaInfos.set(e.channelName,e)}removeDestChannelInfo(e){Lu(e),this.destChannelMediaInfos.delete(e)}getSrcChannelMediaInfo(){return this.srcChannelMediaInfo}getDestChannelMediaInfo(){return this.destChannelMediaInfos}}function zw(t){if(!(t instanceof qw))return new P(v.INVALID_PARAMS,"Config should be instance of [ChannelMediaRelayConfiguration]").throw();const e=t.getSrcChannelMediaInfo(),i=t.getDestChannelMediaInfo();if(!e)return new P(v.INVALID_PARAMS,"srcChannelMediaInfo should not be empty").throw();if(i.size===0)return new P(v.INVALID_PARAMS,"destChannelMediaInfo should not be empty").throw()}class Co{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,i){S(this,"uid",void 0),S(this,"_uintid",void 0),S(this,"_trust_in_room_",!0),S(this,"_trust_audio_enabled_state_",!0),S(this,"_trust_video_enabled_state_",!0),S(this,"_trust_audio_mute_state_",!0),S(this,"_trust_video_mute_state_",!0),S(this,"_audio_muted_",!1),S(this,"_video_muted_",!1),S(this,"_audio_enabled_",!0),S(this,"_video_enabled_",!0),S(this,"_audio_added_",!1),S(this,"_video_added_",!1),S(this,"_is_pre_created",!1),S(this,"_video_pre_subscribed",!1),S(this,"_audio_pre_subscribed",!1),S(this,"_trust_video_stream_added_state_",!0),S(this,"_trust_audio_stream_added_state_",!0),S(this,"_audioTrack",void 0),S(this,"_videoTrack",void 0),S(this,"_dataChannels",[]),S(this,"_audioSSRC",void 0),S(this,"_videoSSRC",void 0),S(this,"_audioOrtc",void 0),S(this,"_videoOrtc",void 0),S(this,"_cname",void 0),S(this,"_rtxSsrcId",void 0),S(this,"_videoMid",void 0),S(this,"_audioMid",void 0),this.uid=e,this._uintid=i}}function Xw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Jw(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?Xw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):Xw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}const Jc="9",Qw=4e4;function Zw(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Yr(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?Zw(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):Zw(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}var Da=function(t){return t[t.DOWN=0]="DOWN",t[t.UP=1]="UP",t}(Da||{});const qu=new Map;function $w(t,e,i,n){let{scale:r}=t;if(r===0&&n===Da.UP||r>=e.length-1&&n===Da.DOWN)return t;let o=Yr(Yr({},t),{},{scale:n===Da.DOWN?++r:--r});switch(i){case"maintain-framerate":o=Yr(Yr({},o),e[r].motion);break;case"maintain-resolution":o=Yr(Yr({},o),e[r].detail);break;case"balanced":o=Yr(Yr({},o),e[r].balanced)}return o}function t0(t,e){if(e){const i={overUse:0,underUse:0,adaptationList:e0(e)};qu.set(t,i)}else qu.delete(t)}function e0(t){const e=Yr({},t),{bitrateMax:i,frameRate:n,scaleResolutionDownBy:r,bitrateMin:o}=e,{MIN_FRAME_RATE:s,MAX_THRESHOLD_FRAMERATE:a,MAX_SCALE:c,BITRATE_MIN_THRESHOLD:d,BITRATE_MAX_THRESHOLD:l,BWE_SCALE_UP_THRESHOLD:u,BWE_SCALE_DOWN_THRESHOLD:h,PERF_SCALE_DOWN_THRESHOLD:p,PERF_SCALE_UP_THRESHOLD:g,BALANCE_BITRATE_FACTOR:m,BALANCE_FRAMERATE_FACTOR:f,BALANCE_RESOLUTION_FACTOR:T,MOTION_RESOLUTION_FACTOR:R,MOTION_BITRATE_FACTOR:A,DETAIL_FRAMERATE_FACTOR:N,DETAIL_BITRATE_FACTOR:O}=zE,w=Math.min(e.frameRate,a),L=[{scale:0,threshold:{bwe_down:Math.round(Math.pow(h,1)*i),bwe_up:i,fps_down:Math.round(Math.pow(p,1)*w),fps_up:n},balanced:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o},motion:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o},detail:{scaleResolutionDownBy:1,frameRate:n,bitrateMax:i,bitrateMin:o}}];for(let M=1;M<=c;M++){const j={bwe_up:Math.round(Math.pow(u,M)*i),bwe_down:Math.round(Math.pow(h,M+1)*i),fps_up:Math.round(Math.pow(g,M)*w),fps_down:Math.round(Math.pow(p,M+1)*w)},H={scaleResolutionDownBy:r/Math.pow(T,M),frameRate:Math.max(Math.round(Math.pow(f,M)*n),s),bitrateMax:Math.max(Math.round(Math.pow(m,M)*i),l),bitrateMin:Math.max(Math.round(Math.pow(m,M)*o),d)},ht={scaleResolutionDownBy:r/Math.pow(R,M),frameRate:n,bitrateMax:Math.max(Math.round(Math.pow(A,M)*i),l),bitrateMin:Math.max(Math.round(Math.pow(A,M)*o),d)},lt={scaleResolutionDownBy:1,frameRate:Math.max(Math.round(Math.pow(N,M)*n),s),bitrateMax:Math.max(Math.round(Math.pow(O,M)*i),l),bitrateMin:Math.max(Math.round(Math.pow(O,M)*o),d)};L.push({scale:M,threshold:j,balanced:H,motion:ht,detail:lt})}return L}function wW(t,e,i,n,r,o){const s=qu.get(t)||{overUse:0,underUse:0,adaptationList:e0(r)},{adaptationList:a}=s;qu.set(t,s);const{OVERUSE_TIMES_THRESHOLD:c,UNDERUSE_TIMES_THRESHOLD:d}=zE,{scale:l}=n;let u,h;return typeof e=="number"&&e>0&&function(p,g,m,f){if(g>=m.length)return!1;let{threshold:{fps_down:T}}=m[g];return y("FORCE_AG_HIGH_FRAMERATE")&&f==="maintain-framerate"&&(T=m[0].threshold.fps_down),p<T}(e,l,a,o)&&(s.overUse++,h=Lc.CPU,s.overUse>c)||typeof i=="number"&&i>0&&function(p,g,m){if(g>=m.length)return!1;const{threshold:{bwe_down:f}}=m[g];return p<f}(i,l,a)&&(s.overUse++,h=Lc.BANDWIDTH,s.overUse>c)?(s.overUse=0,s.underUse=0,u=$w(n,a,o,Da.DOWN),[u,h]):(typeof e=="number"&&e>0&&typeof i=="number"&&i>0&&function(p,g,m,f){if(g===0)return;let{threshold:{fps_up:T}}=m[g];return y("FORCE_AG_HIGH_FRAMERATE")&&f==="maintain-framerate"&&(T=m[1].threshold.fps_up),p>T}(e,l,a,o)&&function(p,g,m){if(g===0)return;const{threshold:{bwe_up:f}}=m[g];return p>f}(i,l,a)&&(s.underUse++,s.underUse>d&&(s.overUse=0,s.underUse=0,u=$w(n,a,o,Da.UP),u.scale===0&&(h=Lc.NONE))),[u,h])}function i0(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Km(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?i0(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):i0(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}function OW(t){var e;return!!y("ENABLE_AG_ADAPTATION")&&!!(t instanceof um||G(e=t._hints).call(e,Vt.CUSTOM_TRACK))&&(!!y("FORCE_SUPPORT_AG_ADAPTATION")||!!(function(i){const n=vt();if(n.os!==we.IOS||!n.osVersion)return!1;const r=n.osVersion.split(".");return Number(r[0])>=i}(14)&&Zy(17,4)||Qy(14)&&$y(17,4)))}const zu=new Map;function Xu(t,e){const i=zu.get(t);if(i){const{timer:n}=i;window.clearTimeout(n),zu.delete(t)}e.qualityLimitationReason=Lc.NONE,t0(t)}function NW(t,e){var i;let n;switch(e){case V.LocalAudioTrack:n=Ot.Audio;break;case V.LocalVideoTrack:n=G(i=t._hints).call(i,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High;break;case V.LocalVideoLowTrack:n=Ot.Low}return n}function Ym(t){const e=Ct();if(t.some(i=>i._bypassWebAudio))throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");if(!e.webAudioMediaStreamDest)throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks because your browser does not support audio mixing")}function qm(t,e){Ym(t);const i=new ve;return t.forEach(n=>i.addAudioTrack(n)),i}const DW=!Ct().supportUnifiedPlan||y("CHROME_FORCE_PLAN_B")&&Vr();function Ju(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};var i;return DW?(i={spec:e,store:t},Kr("PlanBConnection").create(i)):new Cr(e,t)}function zm(t){return t&&(t.iceConnectionState==="disconnected"||t.iceConnectionState==="checking"||t.iceConnectionState==="failed")}function n0(t){try{if(t.iceServers)return!1;if(t.turnServer&&t.turnServer.mode!=="off"){if(Nc(t.turnServer.servers))return!1;if(y("FORCE_TURN_TCP")||t.turnServer.servers.concat(t.turnServer.serversFromGateway||[]).some(e=>e.forceturn))return!0}return!1}catch(e){return!1}}var St;function r0(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function ir(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?r0(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):r0(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}let Cr=(St=class ys extends rw{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,i;return(e=(i=this.peerConnection.getReceivers()[0])===null||i===void 0||(i=i.transport)===null||i===void 0?void 0:i.state)!==null&&e!==void 0?e:null}get localCodecs(){return[...new Set(this.localCapabilities&&this.localCapabilities.send.videoCodecs.map(e=>e.rtpMap&&e.rtpMap.encodingName.toLowerCase()||"").filter(e=>{var i;return G(i=Object.keys(Eu)).call(i,e)}))]}constructor(e,i){super(e,i),S(this,"id",Gt(5,"connection-")),S(this,"store",void 0),S(this,"peerConnection",void 0),S(this,"forceTurn",!1),S(this,"remoteSDP",void 0),S(this,"initialOffer",void 0),S(this,"transportEventReceiver",void 0),S(this,"statsFilter",void 0),S(this,"extension",{useXR:y("USE_XR")}),S(this,"localCapabilities",void 0),S(this,"remoteCodecs",void 0),S(this,"localCandidateCount",0),S(this,"allCandidatesReceived",!1),S(this,"isPreallocation",!1),S(this,"preSSRCMap",new Map),S(this,"dataStreamChannelMap",new Map),S(this,"establishPromise",void 0),S(this,"recoveredDataChannelIds",[]),S(this,"currentDataChannelId",1),S(this,"supportAV1RtpSpec",!1),S(this,"mutex",void 0),S(this,"qualityLimitationReason",Lc.NONE),S(this,"isFirstConnected",!1),this.store=i,this.forceTurn=n0(e),this.mutex=new qe("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(ys.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.isFirstConnected=!1,this.statsFilter=KE(this.peerConnection,y("STATS_UPDATE_INTERVAL"),void 0,ne()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}getPreMedia(e){const i=this.preSSRCMap.get(e);if(i!==void 0){const n=this.peerConnection.getTransceivers().find(r=>r.mid===i);if(n)return{transceiver:n,track:n.receiver.track,id:i}}}updateRemoteRTPCapabilities(e,i){return C(this,null,function*(){if(this.remoteCodecs=i,!this.remoteSDP)return void _.debug("[P2PConnection] cannot updateRemoteRTPCapabilities before remote SDP created, local codecs: ".concat(this.localCodecs,", codecs: ").concat(i));if(this.remoteSDP.updateRemoteCodec(e,i,this.store.codec)){const n=yield this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");yield this.peerConnection.setLocalDescription(n);const o=this.remoteSDP.toString();r==null||r(o),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}else _.debug("[P2PConnection] updateRemoteRTPCapabilities no need to exchange SDP.")})}establish(){return C(this,null,function*(){try{this.peerConnection.addTransceiver("video",{direction:"recvonly"}),this.peerConnection.addTransceiver("audio",{direction:"recvonly"});const n=yield this.peerConnection.createOffer();if(!n.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const r=Ro(n.sdp),o=yield Cw({filterRTX:!y("USE_PUB_RTX")&&!y("USE_SUB_RTX"),filterVideoFec:y("FILTER_VIDEO_FEC"),filterAudioFec:y("FILTER_AUDIO_FEC"),filterVideoCodec:y("FILTER_VIDEO_CODEC")},this.extension);if(this.localCapabilities=Gu(o),this.initialOffer=n,y("ENABLE_SVC")&&this.store.codec=="av1"){const a=yield function(){return C(this,null,function*(){try{const c=new RTCPeerConnection;c.addTransceiver("video",{direction:"sendonly",sendEncodings:[{scalabilityMode:pu.L1T3}]});const d=yield c.createOffer();if(!d.sdp)return void c.close();const l=Ni(d.sdp).mediaDescriptions[0];if(!l)return;const u=l.attributes.extmaps.find(h=>h.extensionName==="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension");return c.close(),u}catch(c){return}})}();var e;a&&(this.supportAV1RtpSpec=!0,(e=o.send)===null||e===void 0||e.videoExtensions.push(a))}let s;return n.sdp&&bw(n.sdp)&&(s=te(o),(i=s).send&&(Aa(q.VIDEO,i.send.videoExtensions),Aa(q.AUDIO,i.send.audioExtensions)),i.recv&&(Aa(q.VIDEO,i.recv.videoExtensions),Aa(q.AUDIO,i.recv.audioExtensions)),i.sendrecv&&(Aa(q.VIDEO,i.sendrecv.videoExtensions),Aa(q.AUDIO,i.sendrecv.audioExtensions))),ir(ir({},r),{},{rtpCapabilities:s||o,offerSDP:n.sdp})}catch(n){throw new k(v.GET_LOCAL_CONNECTION_PARAMS_FAILED,n.toString())}var i})}connect(e){return C(this,null,function*(){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.initialOffer.sdp&&bw(this.initialOffer.sdp)&&(i=e.rtpCapabilities,n=this.localCapabilities,i.send&&(Fu(q.VIDEO,i.send.videoExtensions,n.send.videoExtensions),Fu(q.AUDIO,i.send.audioExtensions,n.send.audioExtensions)),i.recv&&(Fu(q.VIDEO,i.recv.videoExtensions,n.recv.videoExtensions),Fu(q.AUDIO,i.recv.audioExtensions,n.recv.audioExtensions))),this.remoteSDP=new class{get localCapabilities(){return te(this._localCapabilities)}get rtpCapabilities(){return te(this._rtpCapabilities)}get candidates(){return te(this._candidates)}get iceParameters(){return te(this._iceParameters)}get dtlsParameters(){return te(this._dtlsParameters)}constructor(d){let l=arguments.length>1&&arguments[1]!==void 0&&arguments[1];S(this,"sessionDesc",void 0),S(this,"_localCapabilities",void 0),S(this,"_rtpCapabilities",void 0),S(this,"_candidates",void 0),S(this,"_originCandidates",void 0),S(this,"_iceParameters",void 0),S(this,"_isUseExtmapAllowMixed",void 0),S(this,"_dtlsParameters",void 0),S(this,"setup",void 0),S(this,"currentMidIndex",void 0),S(this,"cname",void 0),S(this,"firefoxSsrcMidMap",new Map),this._isUseExtmapAllowMixed=l,d=te(d);const{iceParameters:u,dtlsParameters:h,candidates:p,rtpCapabilities:g,setup:m,localCapabilities:f,cname:T}=d;this._rtpCapabilities=g,this._candidates=p,this._originCandidates=te(p),this._iceParameters=u,this._dtlsParameters=h,this._localCapabilities=f,this.setup=m,this.cname=T,this.sessionDesc=this.updateRemoteRTPCapabilities(g),this.currentMidIndex=this.sessionDesc.mediaDescriptions.length-1}preloadRemoteMedia(d){const l=this.candidates,u=this.dtlsParameters,h=this.iceParameters,p=this.rtpCapabilities.send;let g=this.sessionDesc.mediaDescriptions.length-1;for(let m=1;m<d;m++){const f=2*m+2e4,T=2*m+Qw,{ssrcs:R,ssrcGroups:A}=as([{ssrcId:f}],this.cname),{ssrcs:N,ssrcGroups:O}=as([{ssrcId:T,rtx:y("USE_SUB_RTX")?T+1:void 0}],this.cname);this.sessionDesc.mediaDescriptions.push({media:{mediaType:"video",port:Jc,protos:["UDP","TLS","RTP","SAVPF"],fmts:p.videoCodecs.map(w=>w.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:h.iceUfrag,icePwd:h.icePwd,unrecognized:[],candidates:l,extmaps:p.videoExtensions,fingerprints:u.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:N,ssrcGroups:O,rtcpFeedbackWildcards:[],payloads:p.videoCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(++g)}}),this.sessionDesc.mediaDescriptions.push({media:{mediaType:"audio",port:Jc,protos:["UDP","TLS","RTP","SAVPF"],fmts:p.audioCodecs.map(w=>w.payloadType.toString(10))},connections:[{nettype:"IN",addrtype:"IP4",address:"127.0.0.1"}],bandwidths:[],attributes:{iceUfrag:h.iceUfrag,icePwd:h.icePwd,unrecognized:[],candidates:l,extmaps:p.audioExtensions,fingerprints:u.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:R,ssrcGroups:A,rtcpFeedbackWildcards:[],payloads:p.audioCodecs,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:"sendonly",rtcpMux:!0,rtcpRsize:!0,mid:"".concat(++g)}}),this.currentMidIndex+=2}this.updateBundleMids()}toString(){return mo(this.sessionDesc)}send(d,l,u,h){const{ssrcs:p,ssrcGroups:g}=as(l,this.cname,y("SYNC_GROUP")?u:void 0),m=this.findPreloadMediaDesc(p);if(m){if(ne()&&this.firefoxSsrcMidMap.set(p[0].ssrcId,m.attributes.mid),h&&(h.twcc||h.remb)){const f=this.sessionDesc.mediaDescriptions.indexOf(m);return this.sessionDesc.mediaDescriptions[f]=this.mungSendMediaDesc(m,h),{mid:m.attributes.mid,needExchangeSDP:!0}}return{mid:m.attributes.mid,needExchangeSDP:!1}}{const f=this.findAvailableMediaIndex(d,p);let T;return f===-1||f===1&&(je()||function(){const R=vt();return!(R.name!==It.CHROME||!R.osVersion)&&Number(R.version)<=90}()||y("ENABLE_ENCODED_TRANSFORM")&&xr())||f===0&&y("USE_SUB_RTX")||tI()?(T=this.createOrRecycleSendMedia(d,p,g,"sendonly",h),this.updateBundleMids()):(T=te(this.sessionDesc.mediaDescriptions[f]),T.attributes.direction="sendonly",T.attributes.ssrcs=p,T.attributes.ssrcGroups=g,this.sessionDesc.mediaDescriptions[f]=this.mungSendMediaDesc(T,h)),ne()&&this.firefoxSsrcMidMap.set(p[0].ssrcId,T.attributes.mid),{mid:T.attributes.mid,needExchangeSDP:!0}}}sendDataChannel(){const{mediaDesc:d,needExchangeSDP:l}=this.createOrRecycleDataChannel();return this.updateBundleMids(),{mid:d.attributes.mid,needExchangeSDP:l}}batchSend(d){const l=d.map(p=>{let{kind:g,ssrcMsg:m,mslabel:f}=p;return this.send(g,m,f)}),u=[];let h=!1;return l.forEach(p=>{let{mid:g,needExchangeSDP:m}=p;m&&(h=!0),u.push(g)}),{mids:u,needExchangeSDP:h}}stopSending(d){const l=this.sessionDesc.mediaDescriptions.filter(u=>u.attributes.mid&&d.indexOf(u.attributes.mid)!==-1);if(l.length!==d.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");l.forEach(u=>{u.attributes.mid==="0"||ne()||tI()?u.attributes.ssrcs=[]:(u.attributes.ssrcs=[],u.attributes.direction="inactive",u.media.port="0")}),this.updateBundleMids()}mute(d){const l=this.sessionDesc.mediaDescriptions.find(u=>u.attributes.mid===d);if(!l)throw new Error("mediaDescription not found with ".concat(d," in remote SDP when calling RemoteSDP.mute."));l.attributes.direction="inactive"}unmute(d){const l=this.sessionDesc.mediaDescriptions.find(u=>u.attributes.mid===d);if(!l)throw new Error("mediaDescription not found with ".concat(d," in remote SDP when calling RemoteSDP.unmute."));l.attributes.direction="sendonly"}muteRemote(d){const l=this.sessionDesc.mediaDescriptions.filter(u=>G(d).call(d,u.attributes.mid||""));if(l.length!==d.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");l.forEach(u=>{u.attributes.direction="inactive"})}unmuteRemote(d){const l=this.sessionDesc.mediaDescriptions.filter(u=>G(d).call(d,u.attributes.mid||""));if(l.length!==d.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");l.forEach(u=>{u.attributes.direction="recvonly"})}receive(d,l,u,h){d.forEach((p,g)=>{this.createOrRecycleRecvMedia(p,[],"recvonly",l,u,h[g])}),this.updateBundleMids()}stopReceiving(d){const l=this.sessionDesc.mediaDescriptions.filter(u=>d.indexOf(u.attributes.mid)!==-1);if(l.length!==d.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");l.forEach(u=>{u.media.port="0",u.attributes.direction="inactive"}),this.updateBundleMids()}updateRemoteRTPCapabilities(d){const l=this.sessionDesc||Ni((u=this._isUseExtmapAllowMixed,`v=0
o=- 0 0 IN IP4 127.0.0.1
s=AgoraGateway
t=0 0
a=group:BUNDLE 0 1
a=msid-semantic: WMS
a=ice-lite`.concat(u?`
a=extmap-allow-mixed`:"",`
m=video 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 127.0.0.1
a=rtcp:9 IN IP4 0.0.0.0
a=sendonly
a=rtcp-mux
a=rtcp-rsize
a=mid:0
m=audio 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 127.0.0.1
a=rtcp:9 IN IP4 0.0.0.0
a=sendonly
a=rtcp-mux
a=rtcp-rsize
a=mid:1
`)));var u;this._rtpCapabilities=d;const h=this.rtpCapabilities.send,p=this.localCapabilities.send;for(const g of l.mediaDescriptions){if(g.attributes.iceUfrag=this._iceParameters.iceUfrag,g.attributes.icePwd=this._iceParameters.icePwd,g.attributes.fingerprints=this._dtlsParameters.fingerprints,g.attributes.candidates=this._candidates,g.attributes.setup=this.setup,g.media.mediaType==="application"&&(g.attributes.sctpPort="5000"),g.media.mediaType==="video"){if(h.videoCodecs.length===0){const m=p.videoCodecs.filter(f=>{var T,R;return(T=f.rtpMap)===null||T===void 0?void 0:G(R=T.encodingName.toLowerCase()).call(R,"vp8")})||[p.videoCodecs[0]];g.media.fmts=m.map(f=>f.payloadType.toString(10)),g.attributes.payloads=m,g.attributes.extmaps=[]}else if(g.media.fmts=h.videoCodecs.map(m=>m.payloadType.toString(10)),g.attributes.payloads=h.videoCodecs,g.attributes.extmaps=h.videoExtensions,y("PRELOAD_MEDIA_COUNT")>0){const{ssrcs:m,ssrcGroups:f}=as([{ssrcId:Qw,rtx:y("USE_SUB_RTX")?40001:void 0}],this.cname);g.attributes.ssrcs=m,g.attributes.ssrcGroups=f}}if(g.media.mediaType==="audio"){if(h.audioCodecs.length===0){const m=p.audioCodecs.filter(f=>{var T,R;return(T=f.rtpMap)===null||T===void 0?void 0:G(R=T.encodingName.toLowerCase()).call(R,"opus")})||[p.audioCodecs[0]];g.media.fmts=m.map(f=>f.payloadType.toString(10)),g.attributes.payloads=m,g.attributes.extmaps=[]}else if(g.media.fmts=h.audioCodecs.map(m=>m.payloadType.toString(10)),g.attributes.payloads=h.audioCodecs,g.attributes.extmaps=h.audioExtensions,wa(g),y("PRELOAD_MEDIA_COUNT")>0){const{ssrcs:m,ssrcGroups:f}=as([{ssrcId:2e4}],this.cname);g.attributes.ssrcs=m,g.attributes.ssrcGroups=f}}}return this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1,this.sessionDesc}updateCandidates(d){const l=this._originCandidates.filter(h=>h.transport==="udp"),u=[];if(l.forEach(h=>{u.push(Jw(Jw({},h),{},{foundation:"tcpcandidate",priority:Number(h.priority)-1+"",transport:"tcp",port:Number(h.port)+90+""}))}),l.length!==0){switch(d){case Xe.TCP_RELAY:this._candidates=u;break;case Xe.UDP_TCP_RELAY:case Xe.RELAY:this._candidates=[...l,...u];break;default:this._candidates=l}for(const h of this.sessionDesc.mediaDescriptions)h.attributes.candidates=this.candidates}}restartICE(d){d=te(d),this._iceParameters=d,this.sessionDesc.mediaDescriptions.forEach(l=>{l.attributes.iceUfrag=d.iceUfrag,l.attributes.icePwd=d.icePwd})}predictReceivingMids(d){const l=[];for(let u=0;u<d;u++)l.push((this.currentMidIndex+u+1).toString(10));return l}findAvailableMediaIndex(d,l){return this.sessionDesc.mediaDescriptions.findIndex(u=>{const h=u.media.mediaType===d&&u.media.port!=="0"&&(u.attributes.direction==="sendonly"||u.attributes.direction==="sendrecv")&&u.attributes.ssrcs.length===0;if(ne()){if(h){const p=this.firefoxSsrcMidMap.get(l[0].ssrcId);return!(p||u.attributes.mid!=="0"&&u.attributes.mid!=="1")||!(!p||p!==u.attributes.mid)}return!1}return h})}createOrRecycleDataChannel(){for(const u of this.sessionDesc.mediaDescriptions)if(u.media.mediaType==="application")return{mediaDesc:u,needExchangeSDP:!1};this.currentMidIndex+=1;const d="".concat(this.currentMidIndex),l={media:{mediaType:"application",port:Jc,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(d),sctpPort:"5000"}};return this.sessionDesc.mediaDescriptions.push(l),{mediaDesc:l,needExchangeSDP:!0}}createOrRecycleRecvMedia(d,l,u,h,p,g){const m=d._mediaStreamTrack.kind,f=this.rtpCapabilities.recv,T=Kc(m,f,this.localCapabilities.send,m===q.VIDEO?h:p),R=m===q.VIDEO?f.videoExtensions:f.audioExtensions;this.currentMidIndex+=1;const A="".concat(this.currentMidIndex);let N={media:{mediaType:m,port:Jc,protos:["UDP","TLS","RTP","SAVPF"],fmts:T.map(w=>w.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:R,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:l,ssrcGroups:[],rtcpFeedbackWildcards:[],payloads:T,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:u,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(A)}};N=this.mungRecvMediaDsec(N,d,g);const O=this.findFirstClosedMedia(m);if(O){const w=this.sessionDesc.mediaDescriptions.indexOf(O);this.sessionDesc.mediaDescriptions[w]=N}else this.sessionDesc.mediaDescriptions.push(N);return N}updateRemoteCodec(d,l,u){const h=[...new Set(this._rtpCapabilities.recv.videoCodecs.map(N=>N.rtpMap&&N.rtpMap.encodingName.toLowerCase()||"").filter(N=>{var O;return G(O=Object.keys(Eu)).call(O,N)}))],p=new Set(l);if(h.every(N=>p.has(N)))return _.debug("codecs has not changed, no need to updateRemoteCodec, codecs: ".concat(l)),!1;const g=this._rtpCapabilities.recv.videoCodecs.filter(N=>l.some(O=>{var w;return G(w=N.rtpMap&&N.rtpMap.encodingName.toLowerCase()||"").call(w,O)}));if(g.length===0)return _.debug("updateRemoteCodec failed, because cannot find matched codec, remoteCapabilities codecs: ".concat(h," codecs: ").concat(l)),!1;const m=[...new Set(g.map(N=>N.rtpMap&&N.rtpMap.encodingName.toLowerCase()||""))];let f;if(_.debug("updateRemoteCodec, from ".concat(h," to ").concat(m)),d.length===0)f=this.sessionDesc.mediaDescriptions.filter(N=>N.media.mediaType==="video"&&N.attributes.direction==="recvonly");else if(f=this.sessionDesc.mediaDescriptions.filter(N=>N.attributes.mid&&N.media.mediaType==="video"&&G(d).call(d,N.attributes.mid)&&N.attributes.direction==="recvonly"),f.length!==d.length)return _.debug("updateRemoteCodec failed, because cannot find mids, mids: ".concat(d,", codecs: ").concat(l)),!1;if(y("USE_PUB_RTX")||y("USE_SUB_RTX")){const N=km(g,this.rtpCapabilities.recv.videoCodecs);g.push(...N)}this._rtpCapabilities.recv.videoCodecs=g;const T=this.localCapabilities.send,R=this.rtpCapabilities.recv,A=Kc(q.VIDEO,R,T,u);return f.forEach(N=>{const O=A.map(w=>w.payloadType.toString(10));_.debug("updateRemoteCodec mid: ".concat(N.attributes.mid,", from"),N.attributes.payloads,"to",A),N.attributes.payloads=A,N.media.fmts=O}),!0}createOrRecycleSendMedia(d,l,u,h,p){const g=this.rtpCapabilities.send,m=d===q.VIDEO?g.videoCodecs:g.audioCodecs,f=d===q.VIDEO?g.videoExtensions:g.audioExtensions;this.currentMidIndex+=1;const T="".concat(this.currentMidIndex);let R={media:{mediaType:d,port:Jc,protos:["UDP","TLS","RTP","SAVPF"],fmts:m.map(N=>N.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:f,fingerprints:this.dtlsParameters.fingerprints,imageattr:[],msids:[],remoteCandidatesList:[],rids:[],ssrcs:l,ssrcGroups:u,rtcpFeedbackWildcards:[],payloads:m,rtcp:{port:"9",netType:"IN",addressType:"IP4",address:"0.0.0.0"},setup:this.setup,direction:h,rtcpMux:!0,rtcpRsize:!0,mid:"".concat(T)}};R=this.mungSendMediaDesc(R,p);const A=this.findFirstClosedMedia(d);if(A){const N=this.sessionDesc.mediaDescriptions.indexOf(A);this.sessionDesc.mediaDescriptions[N]=R}else this.sessionDesc.mediaDescriptions.push(R);return R}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(d=>d.media.port!=="0").map(d=>d.attributes.mid)}mungRecvMediaDsec(d,l,u){const h=te(d);return Pm(h),ba(h,l),Lm(h,l),Rw(h),ju(h,u,this.localCapabilities.send),h}mungSendMediaDesc(d,l){const u=te(d);return ju(u,l,this.localCapabilities.recv),wa(u),u}updateRecvMedia(d,l){const u=this.sessionDesc.mediaDescriptions.findIndex(h=>h.attributes.mid===d);if(u!==-1){const h=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[u],l);this.sessionDesc.mediaDescriptions[u]=h}}bumpMid(d){this.currentMidIndex+=d}findFirstClosedMedia(d){return this.sessionDesc.mediaDescriptions.find(l=>ne()?l.media.port==="0"&&l.media.mediaType===d:l.media.port==="0")}findPreloadMediaDesc(d){return this.sessionDesc.mediaDescriptions.find(l=>{var u;return((u=l.attributes)===null||u===void 0||(u=u.ssrcs[0])===null||u===void 0?void 0:u.ssrcId)===d[0].ssrcId})}getSSRC(d){var l;return(l=this.sessionDesc.mediaDescriptions.find(u=>u.attributes.mid===d))===null||l===void 0?void 0:l.attributes.ssrcs}}(ir(ir({},e),{},{localCapabilities:this.localCapabilities}),this.supportAV1RtpSpec),e.preallocation&&(this.isPreallocation=!0),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const r=this.remoteSDP.toString(),o=Iw(this.initialOffer.sdp,this.extension),s=this.logSDPExchange(o||"","offer","local","connect");this.store.descriptionStart(),yield this.peerConnection.setLocalDescription({type:"offer",sdp:o}),s==null||s(r),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:r});const a=this.peerConnection.getTransceivers()[0];if(a!=null&&a.receiver&&this.tryBindTransportEvents(a.receiver),y("PRELOAD_MEDIA_COUNT")>0){this.remoteSDP.preloadRemoteMedia(y("PRELOAD_MEDIA_COUNT"));const d=this.remoteSDP.toString();yield this.peerConnection.setRemoteDescription({type:"offer",sdp:d});const l=yield this.peerConnection.createAnswer();yield this.peerConnection.setLocalDescription(l)}const{preSSRCs:c}=e;if(Array.isArray(c)&&c.length>0){const{mids:d}=this.remoteSDP.batchSend(c.map(l=>({kind:l.kind,ssrcMsg:[{ssrcId:l.ssrcId,rtx:l.rtx}],mslabel:l.mslabel})));d.forEach((l,u)=>{this.preSSRCMap.set(c[u].ssrcId,l)}),yield Yc(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [P2PConnection] pre-batchReceive exchange SDP."))}}catch(r){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(r.toString()))}var i,n})}updateRemoteConnect(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateRemoteConnect before remote SDP created");const{rtpCapabilities:i}=e;this.remoteSDP.updateRemoteRTPCapabilities(i),Array.isArray(this.remoteCodecs)&&this.remoteCodecs.length>0&&this.remoteSDP.updateRemoteCodec([],this.remoteCodecs,this.store.codec);const{preSSRCs:n}=e;if(Array.isArray(n)&&n.length>0){const{mids:r}=this.remoteSDP.batchSend(n.map(o=>Object.assign({},{kind:o.kind,ssrcMsg:[{ssrcId:o.ssrcId,rtx:o.rtx}],mslabel:o.mslabel})));r.forEach((o,s)=>{this.preSSRCMap.set(n[s].ssrcId,o)})}yield Yc(this.peerConnection,this.remoteSDP,this.extension),_.debug("[P2PConnection] updateRemoteRTPCapabilities by exchanging SDP.")}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.updateRemoteConnect failed; ".concat(i.toString()))}})}send(e,i,n){var r=this;return cn(function*(){const o=yield Rt(r.mutex.lock("From P2PConnection.send"));try{if(!r.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],a=Vu();e.forEach(f=>{const T=r.peerConnection.addTransceiver(f._mediaStreamTrack,ir({direction:"sendonly"},f.trackMediaType==="video"&&r.supportAV1RtpSpec&&a?{sendEncodings:[{scalabilityMode:a}]}:{}));s.push(T),f._updateRtpTransceiver(T)}),ne()&&y("SIMULCAST")===!0&&(yield Rt(r.applySimulcastForFirefox(s,e)));const c=yield Rt(r.peerConnection.createOffer()),d=r.remoteSDP.predictReceivingMids(e.length),l=r.mungSendOfferSDP(c.sdp,e,d),u=Ni(l),h=d.map(f=>{const T=u.mediaDescriptions.find(R=>R.attributes.mid===f);if(!T)throw new Error("Cannot extract ssrc from mediaDescription.");return gw(T,y("USE_PUB_RTX"))});let p;try{p=yield h}catch(f){p=[],r.remoteSDP.receive(e,i,n,p);const T=r.remoteSDP.toString();throw yield Rt(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield Rt(r.peerConnection.setRemoteDescription({type:"answer",sdp:T})),yield Rt(r.stopSending(d,!0)),f}r.remoteSDP.receive(e,i,n,p);const g=r.remoteSDP.toString(),m=r.logSDPExchange(l,"offer","local","send");return yield Rt(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield Rt(r.applySimulcastEncodings(s,e)),yield Rt(r.applySendEncodings(s,e)),m==null||m(g),yield Rt(r.peerConnection.setRemoteDescription({type:"answer",sdp:g})),s.map((f,T)=>{const R=d[T];return{localSSRC:h[T],id:R,transceiver:f}})}catch(s){throw s instanceof k?s:new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(s.toString()))}finally{o()}})()}createDataChannels(e,i){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.createDataChannels before remote SDP created");let n=this.dataStreamChannelMap.get(e);if(n&&n.readyState==="open")_.debug("[P2PConnection] Channels are already available and can be reused directly.");else{const o=this.currentDataChannelId<1023?this.currentDataChannelId++:this.recoveredDataChannelIds.shift();if(typeof o!="number")throw new Error("create DataChannel error, because cannot get dc id");n=this.peerConnection.createDataChannel("datastream-channel",{id:o,negotiated:!0,ordered:!1,maxRetransmits:y("DATASTREAM_MAX_RETRANSMITS")}),n.binaryType="arraybuffer",this.dataStreamChannelMap.set(e,n)}i.forEach(o=>{o._updateOriginDataChannel(n)});const{needExchangeSDP:r}=this.remoteSDP.sendDataChannel();if(r){const o=this.remoteSDP.toString();yield this.peerConnection.setRemoteDescription({type:"offer",sdp:o});const s=yield this.peerConnection.createAnswer();yield this.peerConnection.setLocalDescription(s),_.debug("[P2PConnection] createDataChannels by exchanging SDP.")}else _.debug("[P2PConnection] createDataChannels no need to exchange SDP.");return}catch(n){throw n instanceof k?n:new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.createDataChannels failed; ".concat(n.toString()))}})}stopDataChannels(e){return C(this,null,function*(){try{const i=this.dataStreamChannelMap.get(e);return i&&(i.id&&this.recoveredDataChannelIds.push(i.id),i.close()),void this.dataStreamChannelMap.delete(e)}catch(i){throw i instanceof k?i:new k(v.DATACHANNEL_FAILED,"P2PConnection.stopDataChannels failed; ".concat(i.toString()))}})}stopSending(e,i){return C(this,null,function*(){const n=i?void 0:yield this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const r=this.peerConnection.getTransceivers().filter(c=>e.indexOf(c.mid)!==-1);if(r.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");r.map(c=>{var d;Xu(this.id+c.mid,this),c.direction="inactive",(d=c.stop)===null||d===void 0||d.call(c)});const o=yield this.peerConnection.createOffer(),s=this.logSDPExchange(o.sdp||"","offer","local","stopSending");yield this.peerConnection.setLocalDescription(o),this.remoteSDP.stopReceiving(e);const a=this.remoteSDP.toString();s==null||s(a),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:a})}catch(r){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(r.toString()))}finally{n&&n()}})}receive(e,i,n,r){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(e,i,n,r);s&&(yield Yc(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP.")));const a=this.peerConnection.getTransceivers().find(c=>c.mid===o);if(!a)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,id:o,transceiver:a}}catch(o){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}})}batchReceive(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const{mids:i,needExchangeSDP:n}=this.remoteSDP.batchSend(e);return n&&(yield Yc(this.peerConnection,this.remoteSDP,this.extension),_.debug("[".concat(this.store.clientId,"] [P2PConnection] batchReceive by exchanging SDP."))),i.map(r=>{const o=this.peerConnection.getTransceivers().find(s=>s.mid===r);if(!o)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:o.receiver.track,id:r,transceiver:o}})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(i.toString()))}})}stopReceiving(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");e.forEach(o=>{Array.from(this.preSSRCMap.entries()).some(s=>{let[a,c]=s;if(c===o)return this.preSSRCMap.delete(a),!0})}),this.remoteSDP.stopSending(e);const i=this.remoteSDP.toString(),n=this.logSDPExchange(i,"offer","remote","stopReceiving");yield this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const r=yield this.peerConnection.createAnswer();n==null||n(r.sdp||""),yield this.peerConnection.setLocalDescription(r)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(i.toString()))}})}muteRemote(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.mute(e);const i=this.remoteSDP.toString(),n=this.logSDPExchange(i,"offer","remote","muteRemote");yield this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const r=yield this.peerConnection.createAnswer();n==null||n(r.sdp||""),yield this.peerConnection.setLocalDescription(r)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.muteRemote failed; ".concat(i.toString()))}})}unmuteRemote(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteRemote mid=".concat(e," before remote SDP created."));this.remoteSDP.unmute(e);const i=this.remoteSDP.toString(),n=this.logSDPExchange(i,"offer","remote","unmuteRemote");yield this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const r=yield this.peerConnection.createAnswer();n==null||n(r.sdp||""),yield this.peerConnection.setLocalDescription(r)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteRemote failed; ".concat(i.toString()))}})}muteLocal(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const i=this.peerConnection.getTransceivers().filter(s=>s.mid&&e.indexOf(s.mid)!==-1);if(i.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");i.map(s=>{s.direction="inactive"});const n=yield this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");yield this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const o=this.remoteSDP.toString();r==null||r(o),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(i.toString()))}})}unmuteLocal(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const i=this.peerConnection.getTransceivers().filter(s=>s.mid&&e.indexOf(s.mid)!==-1);if(i.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");i.map((s,a)=>C(this,null,function*(){s.direction="sendonly"}));const n=yield this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");yield 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 o=this.remoteSDP.toString();r==null||r(o),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(i.toString()))}})}restartICE(e){var i=this;return cn(function*(){const n=yield Rt(i.mutex.lock("From P2PConnection.restartICE"));try{if(!i.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const r=Ct().supportPCSetConfiguration,o=y("FORCE_TURN_TCP")||i.forceTurn;if(e===Xe.RELAY&&!r)return;if(r&&!o){const u=e===Xe.RELAY?"relay":"all",h=i.peerConnection.getConfiguration();h.iceTransportPolicy!==u&&(_.debug("[".concat(i.store.clientId,"] restartICE change iceTransportPolicy from [").concat(h.iceTransportPolicy,"] to [").concat(u,"]")),h.iceTransportPolicy=u,i.peerConnection.setConfiguration(h))}i.remoteSDP.updateCandidates(e);const s=yield Rt(i.peerConnection.createOffer({iceRestart:!0}));if(!s.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const a=Ro(s.sdp),{remoteIceParameters:c}=yield a.iceParameters;i.remoteSDP.restartICE(c);const d=i.remoteSDP.toString(),l=i.logSDPExchange(s.sdp||"","offer","local","restartICE");i.store.descriptionStart(),yield Rt(i.peerConnection.setLocalDescription(s)),l==null||l(d),yield Rt(i.peerConnection.setRemoteDescription({type:"answer",sdp:d}))}catch(r){_.warning("[".concat(i.store.clientId,"] restart ICE failed, abort operation"),r)}finally{n()}})()}extendCandidate(){return C(this,null,function*(){if(!this.remoteSDP||this.isFirstConnected)return;const e=yield this.mutex.lock("From P2PConnection.extendCandidate");try{this.remoteSDP.updateCandidates(Xe.TCP_RELAY),yield Yc(this.peerConnection,this.remoteSDP,this.extension)}catch(i){_.warning("[".concat(this.store.clientId,"] extend candidate failed, abort operation"),i)}finally{e()}})}close(){var e;this.peerConnection.getTransceivers().forEach(i=>{Xu(this.id+i.mid,this)}),this.preSSRCMap.clear(),this.peerConnection.close(),(e=this.onConnectionStateChange)===null||e===void 0||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 ir(ir({},this.statsFilter.getStats()),{},{qualityLimitationReason:this.qualityLimitationReason})}getRemoteVideoIsReady(e){return this.statsFilter.getVideoIsReady(e)}updateEncoderConfig(e,i){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const n=yield this.peerConnection.createOffer(),r=this.mungSendOfferSDP(n.sdp,[i],[e]);this.remoteSDP.updateRecvMedia(e,i);const o=this.remoteSDP.toString(),s=this.logSDPExchange(r,"offer","local","updateEncoderConfig");yield this.peerConnection.setLocalDescription({type:"offer",sdp:r}),s==null||s(o),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new k(v.EXCHANGE_SDP_FAILED,n.toString())}})}updateSendParameters(e,i){return C(this,null,function*(){const n=this.peerConnection.getTransceivers().filter(r=>r.mid===e);n.length===1&&(this.isVP8Simulcast(i)?ne()||(yield this.applySimulcastEncodings(n,[i])):yield this.applySendEncodings(n,[i]))})}setStatsRemoteVideoIsReady(e,i){this.statsFilter.setVideoIsReady2(e,i)}replaceTrack(e,i){return C(this,null,function*(){const n=this.peerConnection.getTransceivers().find(r=>r.mid===i);n&&(yield n.sender.replaceTrack(e._mediaStreamTrack))})}getSelectedCandidatePair(){return C(this,null,function*(){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 i=e[0].transport.iceTransport,{local:n,remote:r}=i.getSelectedCandidatePair();return{local:ir(ir({},mr),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:ir(ir({},mr),{},{candidateType:r.type,protocol:r.protocol,address:r.address,port:r.port})}}return this.statsFilter.getSelectedCandidatePair()})}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;(e=this.onICEConnectionStateChange)===null||e===void 0||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;this.peerConnection.connectionState==="connected"&&(this.isFirstConnected=!0),(e=this.onConnectionStateChange)===null||e===void 0||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidateerror=e=>{if(e&&(e.errorCode||e.errorText)){var i;const n="code: ".concat(e.errorCode,", message: ").concat(e.errorText),r=e.port?"local: ".concat(e.port):"";_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICECandidateError(").concat(n,"), url: ").concat(e.url||"",", host_candidate:").concat(r)),(i=this.onICECandidateError)===null||i===void 0||i.call(this,n)}},this.peerConnection.onicegatheringstatechange=e=>{e&&e.target&&"iceGatheringState"in e.target&&_.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,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},y("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(e){const i={iceServers:[]};return e.iceServers?i.iceServers=e.iceServers:e.turnServer&&(Nc(e.turnServer.servers)?i.iceServers=e.turnServer.servers:y("NEW_TURN_MODE")&&i.iceServers?(y("USE_TURN_SERVER_OF_GATEWAY")?e.turnServer.serversFromGateway&&i.iceServers.push(...ys.newTurnServerConfigToIceServers(e.turnServer.serversFromGateway)):i.iceServers.push(...ys.newTurnServerConfigToIceServers(e.turnServer.servers)),y("NEW_FORCE_TURN")&&(i.iceTransportPolicy="relay")):e.turnServer.mode!=="off"&&(i.iceServers&&i.iceServers.push(...ys.turnServerConfigToIceServers(e.turnServer.servers)),y("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&e.turnServer.serversFromGateway&&i.iceServers.push(...ys.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),y("FORCE_TURN_TCP")?i.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(n=>{n.forceturn&&(i.iceTransportPolicy="relay")}))),y("ENABLE_ENCODED_TRANSFORM")&&Ct().supportWebRTCEncodedTransform&&(i.encodedInsertableStreams=!0),i}static turnServerConfigToIceServers(e){const i=[];return e.forEach(n=>{n.security?n.tcpport&&i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turns:".concat(So(n.turnServerURL),":").concat(n.tcpport,"?transport=tcp")}):(n.udpport&&!y("FORCE_TURN_TCP")&&i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turn:".concat(n.turnServerURL,":").concat(n.udpport,"?transport=udp")}),n.tcpport&&i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turn:".concat(n.turnServerURL,":").concat(n.tcpport,"?transport=tcp")}))}),i}static newTurnServerConfigToIceServers(e){const i=[];return e.forEach(n=>{const r=y("NEW_TURN_MODE");r===1?i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turn:".concat(n.turnServerURL,":3478?transport=udp")}):r===2?i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turn:".concat(n.turnServerURL,":3478?transport=tcp")}):r===3?i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turns:".concat(So(n.turnServerURL),":443?transport=tcp")}):r===4&&(i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turn:".concat(n.turnServerURL,":3478?transport=udp")}),i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turn:".concat(n.turnServerURL,":3478?transport=tcp")}),i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turns:".concat(So(n.turnServerURL),":443?transport=tcp")}))}),i}tryBindTransportEvents(e){const i=e.transport;if(i){this.transportEventReceiver=e,i.onstatechange=()=>{var r;i!=null&&i.state&&((r=this.onDTLSTransportStateChange)===null||r===void 0||r.call(this,i.state))},i.onerror=r=>{var o;(o=this.onDTLSTransportError)===null||o===void 0||o.call(this,"error"in r?r.error:r)};const n=i.iceTransport;n&&(n.onstatechange=()=>{const r=i==null?void 0:i.iceTransport.state;var o;r&&((o=this.onICETransportStateChange)===null||o===void 0||o.call(this,r))},n.getSelectedCandidatePair&&(n.onselectedcandidatepairchange=()=>{if(n.getSelectedCandidatePair()){const{local:r,remote:o}=n.getSelectedCandidatePair();_.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:r.type,protocol:r.protocol}),", remote ").concat(JSON.stringify({candidateType:o.type,protocol:o.protocol,address:o.address,port:o.port})," )"))}}))}}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))}updateRtpSenderEncodings(e,i){return C(this,null,function*(){var n,r;if(i||(i=this.peerConnection.getSenders().find(f=>f.track===e._mediaStreamTrack)),!i)return _.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return _.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!Ct().supportSetRtpSenderParameters)return _.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const o={},s={};switch(e._optimizationMode){case"motion":o.degradationPreference="maintain-framerate";break;case"detail":o.degradationPreference="maintain-resolution";break;case"balanced":o.degradationPreference="balanced"}const a=function(m,f){return m.getTransceivers().find(T=>T.sender.track===f||T.receiver.track===f)}(this.peerConnection,e._mediaStreamTrack),c=E3(e);if(OW(e)&&a&&i&&c&&this.getLocalVideoStats&&G(n=["vp8","vp9"]).call(n,this.store.codec)){var d;const m=o.degradationPreference||(G(d=e._hints).call(d,Vt.CUSTOM_TRACK)?y("CUSTOM_ADAPTATION_DEFAULT_MODE"):"maintain-framerate");(function(f,T,R,A,N,O){if(Xu(f,R),N(T),A!=="balanced"&&A!=="maintain-framerate"&&A!=="maintain-resolution")return;let w=-1;t0(f,T);const L=window.setInterval(()=>{const j=zu.get(f);if(!y("ENABLE_AG_ADAPTATION")||!j)return Xu(f,R),void N(T);const H=O();if(H.sendPackets>0&&H.OutgoingAvailableBandwidth>0){if(w===-1)return void(w=Date.now());if(Date.now()-w<1e3)return;const ht=H.sendFrameRate,lt=H.OutgoingAvailableBandwidth,[rt,Kt]=wW(f,ht,lt,j.adaptationConfig,T,A);Kt&&(R.qualityLimitationReason=Kt),rt&&j.adaptationConfig.scale!==rt.scale&&(_.debug("[".concat(f,"] applyAdaptation: ").concat(R.qualityLimitationReason,`
sendFps `).concat(ht,", bwe ").concat(lt,", switch from ").concat(j.adaptationConfig.scale," to ").concat(rt.scale," ")),j.adaptationConfig=Km(Km({},j.adaptationConfig),rt),N(rt))}},y("CHECK_LOCAL_STATS_INTERVAL")),M=Km({},T);zu.set(f,{timer:L,adaptationConfig:M,originConfig:T,adaptationFunc:N}),_.debug("[".concat(f,"] start adaptation, originConfig: ").concat(JSON.stringify(T),", degradationPreference: ").concat(A))})(this.id+a.mid,c,this,m,f=>{i&&this.updateAdaptation(i,f)},this.getLocalVideoStats.bind(this))}if(e._encoderConfig){var l;const{bitrateMax:m,frameRate:f,scaleResolutionDownBy:T}=e._encoderConfig;m&&(s.maxBitrate=1e3*m),(G(l=e._hints).call(l,Vt.LOW_STREAM)||e.isUseScaleResolutionDownBy)&&(f&&(s.maxFramerate=Bi(f)),T&&T>=1&&(s.scaleResolutionDownBy=T))}const{maxFramerate:u}=y("ENCODER_CONFIG_LIMIT");if(u&&typeof u=="number"&&(s.maxFramerate=s.maxFramerate?Math.min(s.maxFramerate,u):u),y("DSCP_TYPE")&&Vr()){var h;const m=y("DSCP_TYPE");G(h=["very-low","low","medium","high"]).call(h,m)&&(s.networkPriority=m)}const p=i.getParameters(),g=(r=p.encodings)===null||r===void 0?void 0:r[0];ne()&&!g&&(o.encodings=[s]),g&&Object.assign(g,s),Object.assign(p,o),_.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(p.encodings))),yield i.setParameters(p),yield function(m,f,T){return C(this,null,function*(){try{var R;if(!Ct().supportSetRtpSenderParameters||!function(L){return L==="vp9"||L==="av1"}(m)||!y("ENABLE_SVC"))return;const A={},N={},O=f.getParameters(),w=(R=O.encodings)===null||R===void 0?void 0:R[0];N.scalabilityMode=Vu(T),w&&Object.assign(w,N),Object.assign(O,A),yield f.setParameters(O),_.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode success: ".concat(JSON.stringify(O.encodings)))}catch(A){_.debug("[updateAdaptation] updateRtpSenderEncodings scalabilityMode failed",A)}})}(this.store.codec,i,y("SVC_MODE"))})}updateAdaptation(e,i){return C(this,null,function*(){var n,r;if(!e)return _.debug("[updateAdaptation] no rtpSender found");if(!Ct().supportSetRtpSenderParameters)return _.debug("[updateAdaptation] Browser not support set rtp-sender parameters");const o={},{bitrateMax:s,frameRate:a,scaleResolutionDownBy:c}=i;s&&(o.maxBitrate=1e3*s),a&&(o.maxFramerate=Bi(a)),c&&c>=1&&G(n=["vp8","vp9"]).call(n,this.store.codec)&&(o.scaleResolutionDownBy=c);const d=e.getParameters(),l=(r=d.encodings)===null||r===void 0?void 0:r[0];l&&Object.assign(l,o),Object.assign(d,{});try{yield e.setParameters(d),_.debug("[updateAdaptation] updateRtpSenderEncodings: ".concat(JSON.stringify(d.encodings)))}catch(u){!("transport"in e)||e.transport&&e.transport.state==="connected"?this.peerConnectionState!=="connected"?_.debug("[updateAdaptation] peerConnection not connected}"):_.debug("[updateAdaptation] updateRtpSenderEncodings failed",u):_.debug("[updateAdaptation] rtpSender transport not connected}")}})}applySendEncodings(e,i){return C(this,null,function*(){try{if(!Ct().supportSetRtpSenderParameters||e.length!==i.length)return;for(let n=0;n<e.length;n++){const r=e[n],o=i[n];o instanceof Yt&&!this.isVP8Simulcast(o)&&(yield this.updateRtpSenderEncodings(o,r.sender))}}catch(n){_.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}})}mungSendOfferSDP(e,i,n){const r=Ni(e);return i.forEach((o,s)=>{const a=n[s],c=r.mediaDescriptions.find(d=>d.attributes.mid===a);c&&(ba(c,o),vw(c,o,this.store.codec))}),mo(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var i;(i=this.onFirstAudioReceived)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var i;(i=this.onFirstVideoReceived)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var i;(i=this.onFirstAudioDecoded)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,i,n)=>{var r;(r=this.onFirstVideoDecoded)===null||r===void 0||r.call(this,e,i,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,i)=>{var n;(n=this.onSelectedLocalCandidateChanged)===null||n===void 0||n.call(this,e,i)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,i)=>{var n;(n=this.onSelectedRemoteCandidateChanged)===null||n===void 0||n.call(this,e,i)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var i;(i=this.onFirstVideoDecodedTimeout)===null||i===void 0||i.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}applySimulcastForFirefox(e,i){return C(this,null,function*(){if(e.length===i.length)for(let c=0;c<e.length;c++){var n,r,o,s,a;const d=e[c],l=i[c];if(l instanceof Yt&&!G(n=l._hints).call(n,Vt.LOW_STREAM)&&(r=l._encoderConfig)!==null&&r!==void 0&&r.bitrateMax&&((o=l._encoderConfig)===null||o===void 0?void 0:o.bitrateMax)>200&&(s=l._scalabilityMode)!==null&&s!==void 0&&s.numSpatialLayers&&((a=l._scalabilityMode)===null||a===void 0?void 0:a.numSpatialLayers)>1&&this.store.codec==="vp8"){const u={},h={high:1e3*(l._encoderConfig.bitrateMax-50),medium:5e4};u.encodings=[{rid:"m",active:!0,maxBitrate:h.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:h.high}];const p=d.sender.getParameters();yield d.sender.setParameters(Object.assign(p,u))}}})}applySimulcastEncodings(e,i){return C(this,null,function*(){if(!ne()&&e.length===i.length)for(let n=0;n<e.length;n++){const r=i[n];if(r instanceof Yt&&this.isVP8Simulcast(r)){const o=e[n],s={},a={high:1e3*(r._encoderConfig.bitrateMax-50),medium:5e4};s.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:a.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:a.medium,scaleResolutionDownBy:4}];const c=o.sender.getParameters();yield o.sender.setParameters(Object.assign(c,s))}}})}isVP8Simulcast(e){var i,n,r,o,s;return!!(e instanceof Yt&&y("SIMULCAST")&&this.store.codec==="vp8"&&!G(i=e._hints).call(i,Vt.LOW_STREAM)&&(n=e._encoderConfig)!==null&&n!==void 0&&n.bitrateMax&&((r=e._encoderConfig)===null||r===void 0?void 0:r.bitrateMax)>200&&(o=e._scalabilityMode)!==null&&o!==void 0&&o.numSpatialLayers&&((s=e._scalabilityMode)===null||s===void 0?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,i,n,r){if(y("SDP_LOGGING"))return _.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(i," SDP during P2PConnection.").concat(r,`
`),e),i==="offer"?o=>{this.logSDPExchange(o,"answer",n==="local"?"remote":"local",r)}:void 0}getRemoteSSRC(e){return C(this,null,function*(){if(!this.remoteSDP)return;const i=this.remoteSDP.getSSRC(e);return i&&i.length!==0?i[0].ssrcId:void 0})}setConfiguration(e){if(Ct().supportPCSetConfiguration){const i=ys.resolvePCConfiguration(e);this.peerConnection.setConfiguration(i)}}},Q(St.prototype,"updateRemoteRTPCapabilities",[vi],Object.getOwnPropertyDescriptor(St.prototype,"updateRemoteRTPCapabilities"),St.prototype),Q(St.prototype,"connect",[vi],Object.getOwnPropertyDescriptor(St.prototype,"connect"),St.prototype),Q(St.prototype,"updateRemoteConnect",[vi],Object.getOwnPropertyDescriptor(St.prototype,"updateRemoteConnect"),St.prototype),Q(St.prototype,"createDataChannels",[vi],Object.getOwnPropertyDescriptor(St.prototype,"createDataChannels"),St.prototype),Q(St.prototype,"receive",[vi],Object.getOwnPropertyDescriptor(St.prototype,"receive"),St.prototype),Q(St.prototype,"batchReceive",[vi],Object.getOwnPropertyDescriptor(St.prototype,"batchReceive"),St.prototype),Q(St.prototype,"stopReceiving",[vi],Object.getOwnPropertyDescriptor(St.prototype,"stopReceiving"),St.prototype),Q(St.prototype,"muteRemote",[vi],Object.getOwnPropertyDescriptor(St.prototype,"muteRemote"),St.prototype),Q(St.prototype,"unmuteRemote",[vi],Object.getOwnPropertyDescriptor(St.prototype,"unmuteRemote"),St.prototype),Q(St.prototype,"muteLocal",[vi],Object.getOwnPropertyDescriptor(St.prototype,"muteLocal"),St.prototype),Q(St.prototype,"unmuteLocal",[vi],Object.getOwnPropertyDescriptor(St.prototype,"unmuteLocal"),St.prototype),Q(St.prototype,"close",[vi],Object.getOwnPropertyDescriptor(St.prototype,"close"),St.prototype),Q(St.prototype,"updateEncoderConfig",[vi],Object.getOwnPropertyDescriptor(St.prototype,"updateEncoderConfig"),St.prototype),Q(St.prototype,"updateSendParameters",[vi],Object.getOwnPropertyDescriptor(St.prototype,"updateSendParameters"),St.prototype),Q(St.prototype,"replaceTrack",[vi],Object.getOwnPropertyDescriptor(St.prototype,"replaceTrack"),St.prototype),Q(St.prototype,"updateAdaptation",[vi],Object.getOwnPropertyDescriptor(St.prototype,"updateAdaptation"),St.prototype),Q(St.prototype,"getRemoteSSRC",[vi],Object.getOwnPropertyDescriptor(St.prototype,"getRemoteSSRC"),St.prototype),St);function vi(t,e,i){const n=t[e];if(typeof n!="function")throw new Error("Cannot use mutex on object property.");return i.value=function(){return C(this,arguments,function*(){const r=this.mutex,o=yield r.lock("From P2PConnection.".concat(e));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return yield n.apply(this,a)}finally{o()}})},i}function Xm(t,e){let i=document.createElement("video"),n=document.createElement("canvas");i.setAttribute("style","display:none"),n.setAttribute("style","display:none"),i.setAttribute("muted",""),i.muted=!0,i.setAttribute("autoplay",""),i.autoplay=!0,i.setAttribute("playsinline",""),n.width=Bi(e.width),n.height=Bi(e.height);const r=Bi(e.framerate||15);document.body.append(i),document.body.append(n);let o=t._mediaStreamTrack;i.srcObject=new MediaStream([o]),i.play();const s=n.getContext("2d");if(!s)throw new P(v.UNEXPECTED_ERROR,"can not get canvas context");const a=Ct(),c=n.captureStream(a.supportRequestFrame?0:r).getVideoTracks()[0];c.canvas||(c.canvas=n),n.startCapture=()=>{if(!i)return n.stopCapture&&n.stopCapture();if(i.paused&&i.play(),i.videoHeight>2&&i.videoWidth>2){const l=i.videoWidth,u=i.videoHeight/l,h=n.width*u;Math.abs(h-n.height)>=2&&(_.debug("adjust low stream resolution","".concat(n.width,"x").concat(n.height," -> ").concat(n.width,"x").concat(h)),n.height=h)}s.drawImage(i,0,0,n.width,n.height),c.requestFrame&&c.requestFrame(),o!==t._mediaStreamTrack&&(o=t._mediaStreamTrack,i.srcObject=new MediaStream([o]))},n.stopCapture=om(()=>n.startCapture&&n.startCapture(),r);const d=c.stop;return c.stop=()=>{d.call(c),i&&(i.remove(),i.srcObject=null,i=null),n&&(n.width=0,n.remove(),n.stopCapture&&n.stopCapture(),n.startCapture=void 0,n.stopCapture=void 0,n=null),_.debug("clean low stream renderer")},c}var Mn=function(t){return t[t.Video_Send_Qp_Sum=2143]="Video_Send_Qp_Sum",t[t.Video_Send_Freeze=2082]="Video_Send_Freeze",t[t.Video_Recv_Qp_Sum=2144]="Video_Recv_Qp_Sum",t[t.Video_Recv_Freeze=2084]="Video_Recv_Freeze",t[t.Video_Render_Freeze_Time=2109]="Video_Render_Freeze_Time",t[t.Video_Render_Freeze_Time_Render=2147]="Video_Render_Freeze_Time_Render",t[t.Video_Render_Freeze_Time_Render2=2223]="Video_Render_Freeze_Time_Render2",t[t.Audio_Recv_Freeze=2083]="Audio_Recv_Freeze",t[t.Video_Send_Type=2225]="Video_Send_Type",t}(Mn||{}),at=function(t){return t[t.Video_Send_Retransmit=2062]="Video_Send_Retransmit",t[t.Video_Send_Target_Encoded=2064]="Video_Send_Target_Encoded",t[t.Video_Send_Actual_Encoded=2060]="Video_Send_Actual_Encoded",t[t.Video_Send_Transmit=2066]="Video_Send_Transmit",t[t.Video_Send_Bandwidth=2061]="Video_Send_Bandwidth",t[t.Video_Capture_Height=2033]="Video_Capture_Height",t[t.Video_Capture_Width=2035]="Video_Capture_Width",t[t.Video_Capture_Frame_Rate=2034]="Video_Capture_Frame_Rate",t[t.Video_Send_Low_Height=2073]="Video_Send_Low_Height",t[t.Video_Send_Low_Frame_Rate=2075]="Video_Send_Low_Frame_Rate",t[t.Video_Send_Low_Width=2077]="Video_Send_Low_Width",t[t.Video_Send_Low_Bitrate=2069]="Video_Send_Low_Bitrate",t[t.Video_Send_Low_Package_Lost=2070]="Video_Send_Low_Package_Lost",t[t.Video_Send_Low_Package_Rate=2071]="Video_Send_Low_Package_Rate",t[t.Video_Send_Frame_Rate=2002]="Video_Send_Frame_Rate",t[t.Video_Send_Width=2003]="Video_Send_Width",t[t.Video_Send_Height=2004]="Video_Send_Height",t[t.Video_Send_Disabled=2095]="Video_Send_Disabled",t[t.Video_Send_Adaptation=2032]="Video_Send_Adaptation",t[t.Video_Send_Player_Status=2128]="Video_Send_Player_Status",t[t.Video_Send_Nacks=2009]="Video_Send_Nacks",t[t.Video_Send_Plis=2010]="Video_Send_Plis",t[t.Video_Send_Firs=2011]="Video_Send_Firs",t[t.Video_Send_Avg_Encode=2007]="Video_Send_Avg_Encode",t[t.Video_Send_Huge_Frame_Sent=2174]="Video_Send_Huge_Frame_Sent",t[t.Video_Send_Bytes_Retransmit=2173]="Video_Send_Bytes_Retransmit",t[t.Video_Send_Packages_Retransmit=2172]="Video_Send_Packages_Retransmit",t[t.Video_Send_Key_Frames_Encoded=2207]="Video_Send_Key_Frames_Encoded",t[t.Video_Send_Bitrate=2012]="Video_Send_Bitrate",t[t.Video_Send_Package_Rate=2031]="Video_Send_Package_Rate",t[t.Video_Send_Package_Lost=2005]="Video_Send_Package_Lost",t[t.Audio_Capture_PCM_Level=2104]="Audio_Capture_PCM_Level",t[t.Audio_Send_Level=2038]="Audio_Send_Level",t[t.Audio_Send_Bitrate=2039]="Audio_Send_Bitrate",t[t.Audio_Send_Package_Rate=2040]="Audio_Send_Package_Rate",t[t.Audio_Send_AEC_Return_Loss=2041]="Audio_Send_AEC_Return_Loss",t[t.Audio_Send_AEC_Return_Loss_Enhancement=2042]="Audio_Send_AEC_Return_Loss_Enhancement",t[t.Audio_Send_Freeze=2081]="Audio_Send_Freeze",t[t.Audio_Send_Disabled=2096]="Audio_Send_Disabled",t[t.Audio_Send_Bytes_Retransmit=2179]="Audio_Send_Bytes_Retransmit",t[t.Audio_Send_Packages_Retransmit=2180]="Audio_Send_Packages_Retransmit",t[t.Video_Recv_Height=2019]="Video_Recv_Height",t[t.Video_Recv_Width=2018]="Video_Recv_Width",t[t.Video_Recv_Frame_Rate_Output=2155]="Video_Recv_Frame_Rate_Output",t[t.Video_Recv_Jitter_Buffer=2023]="Video_Recv_Jitter_Buffer",t[t.Video_Recv_Current_Delay=2024]="Video_Recv_Current_Delay",t[t.Video_Recv_Nacks=2026]="Video_Recv_Nacks",t[t.Video_Recv_Plis=2027]="Video_Recv_Plis",t[t.Video_Recv_Firs=2028]="Video_Recv_Firs",t[t.Video_Recv_Disabled=2101]="Video_Recv_Disabled",t[t.Video_Recv_Player_Status=2129]="Video_Recv_Player_Status",t[t.Video_Recv_I_Frame_Delay=2149]="Video_Recv_I_Frame_Delay",t[t.Video_Render_Frame_Rate_Render=2022]="Video_Render_Frame_Rate_Render",t[t.Video_Render_Freeze_Duration=2156]="Video_Render_Freeze_Duration",t[t.Audio_Render_Level=2043]="Audio_Render_Level",t[t.Audio_Render_Freeze_Time_80ms=2226]="Audio_Render_Freeze_Time_80ms",t[t.Audio_Render_Freeze_Time_200ms=2227]="Audio_Render_Freeze_Time_200ms",t[t.Audio_Render_Freeze_Samples_80ms=2228]="Audio_Render_Freeze_Samples_80ms",t[t.Audio_Render_Freeze_Samples_200ms=2229]="Audio_Render_Freeze_Samples_200ms",t[t.Audio_Recv_PCM_Level=2105]="Audio_Recv_PCM_Level",t[t.Audio_Recv_Disabled=2102]="Audio_Recv_Disabled",t[t.Audio_Recv_Jitter_Buffer=2054]="Audio_Recv_Jitter_Buffer",t[t.Audio_Recv_Current_Delay=2047]="Audio_Recv_Current_Delay",t[t.Audio_Recv_Player_Status=2130]="Audio_Recv_Player_Status",t[t.Audio_Recv_Bitrate=2044]="Audio_Recv_Bitrate",t[t.Audio_Recv_Concealed_Samples=2148]="Audio_Recv_Concealed_Samples",t[t.Audio_Recv_Total_Samples_Received=2224]="Audio_Recv_Total_Samples_Received",t}(at||{}),Fe=function(t){return t[t.Video_Render_Frame_Rate_Decode=2021]="Video_Render_Frame_Rate_Decode",t[t.Video_Recv_Frame_Rate=2020]="Video_Recv_Frame_Rate",t[t.Video_Recv_Frame_Dropped=2181]="Video_Recv_Frame_Dropped",t[t.Video_Recv_Bytes_Retransmit=2175]="Video_Recv_Bytes_Retransmit",t[t.Video_Recv_Packages_Retransmit=2176]="Video_Recv_Packages_Retransmit",t[t.Video_Recv_Packages_Discarded=2198]="Video_Recv_Packages_Discarded",t[t.Video_Recv_Avg_Decode=2200]="Video_Recv_Avg_Decode",t[t.Video_Recv_Avg_Processing_Delay=2202]="Video_Recv_Avg_Processing_Delay",t[t.Video_Recv_Avg_Assembly_Time=2203]="Video_Recv_Avg_Assembly_Time",t[t.Video_Recv_Avg_Inter_Frame_Delay=2204]="Video_Recv_Avg_Inter_Frame_Delay",t[t.Video_Recv_Key_Frames_Decoded=2206]="Video_Recv_Key_Frames_Decoded",t[t.Video_Recv_Package_Lost=2014]="Video_Recv_Package_Lost",t[t.Video_Recv_Bitrate=2029]="Video_Recv_Bitrate",t[t.Video_Recv_Package_Rate=2078]="Video_Recv_Package_Rate",t[t.Audio_Recv_Jitter=2055]="Audio_Recv_Jitter",t[t.Audio_Recv_Bytes_Retransmit=2178]="Audio_Recv_Bytes_Retransmit",t[t.Audio_Recv_Packages_Retransmit=2177]="Audio_Recv_Packages_Retransmit",t[t.Audio_Recv_Packages_Discarded=2199]="Audio_Recv_Packages_Discarded",t[t.Audio_Recv_Avg_Processing_Delay=2201]="Audio_Recv_Avg_Processing_Delay",t[t.Audio_Recv_Package_Rate=2046]="Audio_Recv_Package_Rate",t[t.Audio_Recv_Package_Lost=2045]="Audio_Recv_Package_Lost",t}(Fe||{}),Ci=function(t){return t[t.RTT=2006]="RTT",t[t.CONN_TYPE=801]="CONN_TYPE",t[t.STATS_UPDATE_INTERVAL=2205]="STATS_UPDATE_INTERVAL",t}(Ci||{}),Qu=function(t){return t[t.RTC_PEER_CONNECTION_STATE=2219]="RTC_PEER_CONNECTION_STATE",t}(Qu||{});const ds=1e3,Zu=6,Qc=3,PW=Math.max(Zu,Qc);function et(t,e,i){i!=null&&Number.isFinite(i)&&(t[e]=Math.round(Math.max(0,i)))}function o0(t){const e={[Ci.CONN_TYPE]:0,[Ci.RTT]:t.rtt,[Ci.STATS_UPDATE_INTERVAL]:t.updateInterval?Math.round(Math.max(0,t.updateInterval)):void 0};switch(t.selectedCandidatePair.localCandidate.candidateType){case"relay":{const i=t.selectedCandidatePair.localCandidate.relayProtocol;i==="udp"&&(e[Ci.CONN_TYPE]=1),i==="tcp"&&(e[Ci.CONN_TYPE]=3),i==="tls"&&(e[Ci.CONN_TYPE]=4);break}case"srflx":e[Ci.CONN_TYPE]=2;break;case"unknown":e[Ci.CONN_TYPE]=5;break;default:e[Ci.CONN_TYPE]=0}return e}function s0(t){let e=0;switch(t){case"none":e=0;break;case"cpu":e=1;break;case"bandwidth":e=2;break;case"other":e=3}return e}class a0 extends $t{constructor(e){super(),S(this,"store",void 0),S(this,"uploadWRTCStatsTimer",void 0),S(this,"uploadOutboundDenoiserStatsTimer",void 0),S(this,"uploadExtStatsTimer",void 0),S(this,"uploadExtUsageStatsTimer",void 0),S(this,"uploadInboundExtStatsTimer",void 0),S(this,"requestStats",void 0),S(this,"requestTransportStats",void 0),S(this,"requestLocalMedia",void 0),S(this,"requestRemoteMedia",void 0),S(this,"requestAllTracks",void 0),S(this,"requestVideoIsReady",void 0),S(this,"requestUploadStats",void 0),S(this,"requestUpload",void 0),S(this,"uploadOutboundStarted",!1),S(this,"uploadInboundStarted",!1),S(this,"uploadTransportStarted",!1),S(this,"uploadBaseStatsStarted",!1),S(this,"uploadExtensionUsageStarted",!1),S(this,"lastRecvStats",void 0),S(this,"lastSendStats",void 0),S(this,"lastRefRecvStats",void 0),S(this,"lastRefSendStats",void 0),S(this,"lastNormalRecvStats",void 0),S(this,"lastNormalSendStats",void 0),S(this,"needUploadRenderFreezeTime",!0),S(this,"lastUploadCompensateTime",-1),S(this,"uploadCompensateDeltaTime",0),this.store=e}uploadWRTCStats(e){if(!this.requestStats||!this.requestUploadStats)return;const i=e%Qc==0,n=e%Zu==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 d=this.getTransportStats(r,o,i);d&&(a.misc=[d])}if(this.uploadOutboundStarted&&r){const d=this.getOutboundStats(r,n?this.lastNormalSendStats:void 0,i?this.lastRefSendStats:void 0,this.lastSendStats);d&&(a.outbound=[d])}if(this.uploadInboundStarted&&o){this.uploadCompensateStats(e);const d=this.getInboundStats(o,n?this.lastNormalRecvStats:void 0,i?this.lastRefRecvStats:void 0,this.lastRecvStats);d&&(a.inbound=d)}const c=(s=this.requestTransportStats)===null||s===void 0?void 0:s.call(this).connectState;c&&(Array.isArray(a.misc)?a.misc[0]&&a.misc[0].addition&&(a.misc[0].addition[Qu.RTC_PEER_CONNECTION_STATE]=HE[c]):a.misc=[{addition:{[Qu.RTC_PEER_CONNECTION_STATE]:HE[c]}}]),this.requestUploadStats(a)}this.lastRecvStats=o,this.lastSendStats=r,n&&(this.lastNormalRecvStats=o,this.lastNormalSendStats=r),i&&(this.lastRefRecvStats=o,this.lastRefSendStats=r)}startUploadWRTCStats(){if(this.uploadWRTCStatsTimer)return;this.uploadBaseStatsStarted=!0;let e=1;this.uploadWRTCStatsTimer=window.setInterval(()=>{if(!this.uploadTransportStarted&&!this.uploadInboundStarted&&!this.uploadOutboundStarted){if(this.uploadBaseStatsStarted){var i,n;const r=(i=this.requestTransportStats)===null||i===void 0?void 0:i.call(this);return void(r&&((n=this.requestUploadStats)===null||n===void 0||n.call(this,{misc:[{addition:{[Qu.RTC_PEER_CONNECTION_STATE]:HE[r.connectState]}}]})))}return this.stopUploadWRTCStats()}this.uploadWRTCStats(e),++e===PW+1&&(e=1)},ds)}uploadCompensateStats(e){if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const i=e%Qc==0&&this.needUploadRenderFreezeTime;if(!this.uploadInboundStarted||!i)return;if(this.lastUploadCompensateTime===-1)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 r=Math.min(Math.floor(this.uploadCompensateDeltaTime/6e3),10);this.uploadCompensateDeltaTime-=6e3*r;const o=this.requestStats(!0);new Array(r).fill(0).forEach(()=>{if(!this.requestStats||!this.requestUploadStats||!this.requestRemoteMedia)return;const s={};if(this.uploadInboundStarted&&o){const a=this.requestRemoteMedia()||[],c=[];a.forEach(d=>{let[l,u]=d;const h={peer:l.uid};if(l._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(l._videoSSRC)&&u.has(q.VIDEO)&&l.videoTrack){const p=function(g,m,f){if(!m.videoRecv.find(R=>R.ssrc===g))return;const T={};if(f&&f._player){const R=f._player,{renderFreezeAccTime2:A,videoElementStatus:N}=R;if(Sr.visibility==="visible"&&N===ii.PLAYING&&Ct().supportRequestVideoFrameCallback){const O=Math.min(6e3,A);R.renderFreezeAccTime2=Math.max(0,A-O),et(T,Mn.Video_Render_Freeze_Time_Render2,O),y("USE_NEW_RENDER_FREEZE_TIME")&&et(T,Mn.Video_Render_Freeze_Time_Render,O)}}return T}(l._videoSSRC,o,l.videoTrack);p&&(h.video=p)}h.video&&c.push(h)}),c.length>0&&(s.inbound=c,this.requestUploadStats(s))}})}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.lastUploadCompensateTime=-1,this.uploadCompensateDeltaTime=0,this.needUploadRenderFreezeTime=!0}getTransportStats(e,i,n){if(!this.requestStats)return;if(!n)return e.rtt==null?void 0:{addition:{[Ci.RTT]:e.rtt,[Ci.CONN_TYPE]:void 0,[Ci.STATS_UPDATE_INTERVAL]:e.updateInterval||void 0}};const r=o0(e);if(this.store.useP2P){if(i){const o=o0(i);r[Ci.CONN_TYPE]+=o[Ci.CONN_TYPE]<<3}r[Ci.CONN_TYPE]+=110}else r[Ci.CONN_TYPE]+=100;return{addition:r}}getOutboundStats(e,i,n,r){if(!this.requestUploadStats||!this.requestLocalMedia)return;const o=this.requestLocalMedia();if(!o||o.length===0)return;let s,a,c;return o.forEach(d=>{let[l,{track:u,ssrcs:h}]=d;switch(l){case V.LocalVideoLowTrack:case V.LocalVideoTrack:if(l===V.LocalVideoTrack){const p=function(f,T,R,A,N,O){const w=T.videoSend.find(ht=>ht.ssrc===f);if(!w)return;const L={},{sentFrame:M,inputFrame:j}=w;if(A&&(et(L,Mn.Video_Send_Qp_Sum,w.qpSumPerFrame),j&&M)){var H;const ht=j.frameRate,lt=M.frameRate;L[Mn.Video_Send_Freeze]=function(rt,Kt){let Ft=!0;return Ft=!(rt<=5)&&(rt<=10?Kt<3:rt<=20?Kt<4:Kt<5),Ft}(ht,lt)?1:0,L[Mn.Video_Send_Type]=R.__className__==="CameraVideoTrack"?0:G(H=R._hints).call(H,Vt.SCREEN_TRACK)?1:2}if(N){switch(M&&(et(L,at.Video_Send_Height,M.height),et(L,at.Video_Send_Width,M.width),et(L,at.Video_Send_Frame_Rate,M.frameRate)),L[at.Video_Send_Disabled]=R._originMediaStreamTrack&&!R._originMediaStreamTrack.enabled||R._mediaStreamTrack&&!R._mediaStreamTrack.enabled?1:0,w.adaptionChangeReason){case"none":L[at.Video_Send_Adaptation]=0;break;case"cpu":L[at.Video_Send_Adaptation]=1;break;case"bandwidth":L[at.Video_Send_Adaptation]=2;break;case"other":L[at.Video_Send_Adaptation]=3}let ht=0;w.adaptionChangeReason&&(ht+=s0(w.adaptionChangeReason)),T.qualityLimitationReason&&(ht+=s0(T.qualityLimitationReason)<<3),L[at.Video_Send_Adaptation]=ht,L[at.Video_Send_Player_Status]=nm[R._player?R._player.videoElementStatus:"uninit"],et(L,at.Video_Send_Nacks,w.nacksCount),et(L,at.Video_Send_Plis,w.plisCount),et(L,at.Video_Send_Firs,w.firsCount),et(L,at.Video_Send_Avg_Encode,w.avgEncodeMs),et(L,at.Video_Send_Huge_Frame_Sent,w.hugeFramesSent),et(L,at.Video_Send_Bytes_Retransmit,w.retransmittedBytesSent),et(L,at.Video_Send_Packages_Retransmit,w.retransmittedPacketsSent),et(L,at.Video_Send_Key_Frames_Encoded,w.keyFramesEncoded);const lt=N.videoSend.find(rt=>rt.ssrc===f);if(lt){let rt=ds*Qc;lt.timestamp&&w.timestamp&&(rt=w.timestamp-lt.timestamp),lt.packets!=null&&w.packets!=null&&et(L,at.Video_Send_Package_Rate,1e3*(w.packets-lt.packets)/rt),w.packetsLost!=null&&lt.packetsLost!=null&&et(L,at.Video_Send_Package_Lost,w.packetsLost-lt.packetsLost),lt.bytes!=null&&w.bytes!=null&&et(L,at.Video_Send_Bitrate,8*(w.bytes-lt.bytes)/rt)}}return L}(h[0].ssrcId,e,u,i,n),g=u&&function(f,T,R,A){const N=T.videoSend.find(w=>w.ssrc===f);if(!N)return null;const O={};if(A){const w=N.inputFrame,L=w&&w.height||R.videoHeight||0,M=w&&w.width||R.videoWidth||0,j=w&&w.frameRate||0;et(O,at.Video_Capture_Height,L),et(O,at.Video_Capture_Width,M),et(O,at.Video_Capture_Frame_Rate,j)}return O}(h[0].ssrcId,e,u,!!n),m=function(f,T){const R={};return T&&(et(R,at.Video_Send_Retransmit,f.bitrate.retransmit),et(R,at.Video_Send_Target_Encoded,f.bitrate.targetEncoded),et(R,at.Video_Send_Actual_Encoded,f.bitrate.actualEncoded),et(R,at.Video_Send_Transmit,f.bitrate.transmit),et(R,at.Video_Send_Bandwidth,f.sendBandwidth)),R}(e,!!n);a=Object.assign({},p,g,m)}else c=function(p,g,m,f,T){const R=g.videoSend.find(N=>N.ssrc===p);if(!R)return;const A={};if(f){const N=R.sentFrame;N&&(et(A,at.Video_Send_Low_Height,N.height),et(A,at.Video_Send_Low_Width,N.width),et(A,at.Video_Send_Low_Frame_Rate,N.frameRate));const O=f.videoSend.find(w=>w.ssrc===p);if(O){let w=ds*Zu;O.timestamp&&R.timestamp&&(w=R.timestamp-O.timestamp),O.packets!=null&&R.packets!=null&&et(A,at.Video_Send_Low_Package_Rate,1e3*(R.packets-O.packets)/w),R.packetsLost!=null&&O.packetsLost!=null&&et(A,at.Video_Send_Low_Package_Lost,R.packetsLost-O.packetsLost),O.bytes!=null&&R.bytes!=null&&et(A,at.Video_Send_Low_Bitrate,8*(R.bytes-O.bytes)/w)}}return A}(h[0].ssrcId,e,0,n);break;case V.LocalAudioTrack:s=u&&function(p,g,m,f,T,R){const A=g.audioSend.find(O=>O.ssrc===p);if(!A)return;const N={};if(T){N[at.Audio_Send_Disabled]=m._originMediaStreamTrack&&!m._originMediaStreamTrack.enabled||m._mediaStreamTrack&&!m._mediaStreamTrack.enabled?1:0;const O=100*m._source.getAccurateVolumeLevel(),w=A.inputLevel;if(w!=null){const M=Math.ceil(50*Math.log10(100*w+1));et(N,at.Audio_Send_Level,M)}et(N,at.Audio_Capture_PCM_Level,O),et(N,at.Audio_Send_AEC_Return_Loss,A.aecReturnLoss),et(N,at.Audio_Send_AEC_Return_Loss_Enhancement,A.aecReturnLossEnhancement),et(N,at.Audio_Send_Bytes_Retransmit,A.retransmittedBytesSent),et(N,at.Audio_Send_Packages_Retransmit,A.retransmittedPacketsSent),N[at.Audio_Send_Freeze]=0;const L=T.audioSend.find(M=>M.ssrc===p);if(L){let M=ds*Zu;L.timestamp&&A.timestamp&&(M=A.timestamp-L.timestamp),L.bytes!=null&&A.bytes!=null&&et(N,at.Audio_Send_Bitrate,8*(A.bytes-L.bytes)/M),L.packets!=null&&A.packets!=null&&et(N,at.Audio_Send_Package_Rate,1e3*(A.packets-L.packets)/M)}}return N}(h[0].ssrcId,e,u,0,n)}}),{high:a,low:c,audio:s}}getInboundStats(e,i,n,r){if(!this.requestRemoteMedia)return;const o=this.requestRemoteMedia()||[],s=[];return o.forEach(a=>{let[c,d]=a;const l={peer:c.uid};if(d.has(q.VIDEO)&&c.videoTrack){const u=c._videoSSRC&&this.requestVideoIsReady&&this.requestVideoIsReady(c._videoSSRC)||!1,h=c.videoTrack?function(p,g,m,f,T,R,A,N){const O=g.videoRecv.find(rt=>rt.ssrc===p);if(!O)return;const w={},{receivedFrame:L,outputFrame:M,decodeFrameRate:j}=O;et(w,Fe.Video_Render_Frame_Rate_Decode,j),O.framesRateFirefox&&et(w,Fe.Video_Recv_Frame_Rate,O.framesRateFirefox),L&&et(w,Fe.Video_Recv_Frame_Rate,L.frameRate),et(w,Fe.Video_Recv_Frame_Dropped,O.framesDroppedCount),et(w,Fe.Video_Recv_Bytes_Retransmit,O.retransmittedBytesReceived),et(w,Fe.Video_Recv_Packages_Retransmit,O.retransmittedPacketsReceived),et(w,Fe.Video_Recv_Packages_Discarded,O.packetsDiscarded),et(w,Fe.Video_Recv_Avg_Decode,O.avgDecodeMs),et(w,Fe.Video_Recv_Avg_Processing_Delay,O.avgProcessingDelayMs),et(w,Fe.Video_Recv_Avg_Assembly_Time,O.avgFramesAssembledFromMultiplePacketsMs),et(w,Fe.Video_Recv_Avg_Inter_Frame_Delay,O.avgInterFrameDelayMs),et(w,Fe.Video_Recv_Key_Frames_Decoded,O.keyFramesDecoded);const H=N&&N.videoRecv.find(rt=>rt.ssrc===p);if(H){const rt=g.timestamp-N.timestamp||ds;O.packetsLost!=null&&H.packetsLost!=null&&et(w,Fe.Video_Recv_Package_Lost,O.packetsLost-H.packetsLost),H.bytes!=null&&O.bytes!=null&&et(w,Fe.Video_Recv_Bitrate,8*(O.bytes-H.bytes)/rt),H.packets!=null&&O.packets!=null&&et(w,Fe.Video_Recv_Package_Rate,1e3*(O.packets-H.packets)/rt)}const ht=R&&R.videoRecv.find(rt=>rt.ssrc===p);if(ht&&(et(w,Mn.Video_Recv_Qp_Sum,O.qpSumPerFrame),w[Mn.Video_Recv_Freeze]=f&&Xc.isRemoteVideoFreeze(m,O,ht)?1:0),A){var lt;const rt=A.videoRecv.find(Ft=>Ft.ssrc===p);L?(et(w,at.Video_Recv_Height,L.height),et(w,at.Video_Recv_Width,L.width)):m&&(et(w,at.Video_Recv_Height,m._videoHeight||0),et(w,at.Video_Recv_Width,m._videoWidth||0)),M&&et(w,at.Video_Recv_Frame_Rate_Output,M.frameRate);const Kt=(lt=m._player)===null||lt===void 0?void 0:lt.rendFrameRate.toFixed(0);if(Kt&&et(w,at.Video_Render_Frame_Rate_Render,+Kt),et(w,at.Video_Recv_Jitter_Buffer,O.jitterBufferMs),et(w,at.Video_Recv_Current_Delay,O.currentDelayMs),et(w,at.Video_Recv_Firs,O.firsCount),et(w,at.Video_Recv_Nacks,O.nacksCount),et(w,at.Video_Recv_Plis,O.plisCount),m){w[at.Video_Recv_Disabled]=m._originMediaStreamTrack.enabled&&m._mediaStreamTrack.enabled?0:1;const Ft=m._player;if(Ft){const{freezeTimeCounterList:Ii,renderFreezeAccTime:U,renderFreezeAccTime2:B,videoElementStatus:X}=Ft;if(Ii&&Ii.length>0&&et(w,Mn.Video_Render_Freeze_Time,Ii.splice(0,1)[0]),T&&Sr.visibility==="visible"&&X===ii.PLAYING&&Ct().supportRequestVideoFrameCallback){const x=Math.min(6e3,B);Ft.renderFreezeAccTime2=Math.max(0,B-x),et(w,Mn.Video_Render_Freeze_Time_Render2,x);const E=Math.min(6e3,U);Ft.renderFreezeAccTime=Math.max(0,U-E),et(w,Mn.Video_Render_Freeze_Time_Render,y("USE_NEW_RENDER_FREEZE_TIME")?x:E)}if(typeof O.totalFreezesDuration=="number"){const x=rt&&rt.totalFreezesDuration?O.totalFreezesDuration-rt.totalFreezesDuration:O.totalFreezesDuration;et(w,at.Video_Render_Freeze_Duration,1e3*x)}}}if(w[at.Video_Recv_Player_Status]=nm[m._player?m._player.videoElementStatus:"uninit"],rt&&O.totalInterFrameDelay!==void 0&&O.totalSquaredInterFrameDelay!==void 0&&rt.totalInterFrameDelay!==void 0&&rt.totalSquaredInterFrameDelay!==void 0){const Ft=O.totalInterFrameDelay-rt.totalInterFrameDelay,Ii=O.totalSquaredInterFrameDelay-rt.totalSquaredInterFrameDelay,U=O.framesDecodeCount-rt.framesDecodeCount,B=Ft/U*1e3,X=Math.round(1e3*Math.sqrt((Ii-Math.pow(Ft,2)/U)/U));!isNaN(X)&&B+X>Math.max(3*B,B+150)&&(w[at.Video_Recv_I_Frame_Delay]=X)}}return w}(c._videoSSRC,e,c.videoTrack,u===!0,this.needUploadRenderFreezeTime,i,n,r):void 0;h&&(l.video=h)}if(d.has(q.AUDIO)&&c.audioTrack){const u=c.audioTrack?function(h,p,g,m,f,T){const R=p.audioRecv.find(w=>w.ssrc===h);if(!R)return;const A={};et(A,Fe.Audio_Recv_Jitter,R.jitterMs),et(A,Fe.Audio_Recv_Bytes_Retransmit,R.retransmittedBytesReceived),et(A,Fe.Audio_Recv_Packages_Retransmit,R.retransmittedPacketsReceived),et(A,Fe.Audio_Recv_Packages_Discarded,R.packetsDiscarded),et(A,Fe.Audio_Recv_Avg_Processing_Delay,R.avgProcessingDelayMs);const N=T&&T.audioRecv.find(w=>w.ssrc===h);if(N){const w=ds;R.packets!=null&&N.packets!=null&&et(A,Fe.Audio_Recv_Package_Rate,1e3*(R.packets-N.packets)/w),R.packetsLost!=null&&N.packetsLost!=null&&et(A,Fe.Audio_Recv_Package_Lost,R.packetsLost-N.packetsLost)}if(m){const{receivedFrames:w,droppedFrames:L}=R;w!=null&&L!=null&&(A[Mn.Audio_Recv_Freeze]=(O=w)===0||100*L/O>20?1:0)}var O;if(f){const w=100*g._source.getAccurateVolumeLevel(),L=R.outputLevel;if(L!=null){const j=Math.ceil(50*Math.log10(100*L+1));et(A,at.Audio_Render_Level,j)}et(A,at.Audio_Recv_PCM_Level,w),g&&(A[at.Audio_Recv_Disabled]=g._originMediaStreamTrack.enabled&&g._mediaStreamTrack.enabled?0:1),et(A,at.Audio_Recv_Jitter_Buffer,R.jitterBufferMs),et(A,at.Audio_Recv_Current_Delay,R.jitterBufferMs),A[at.Audio_Recv_Player_Status]=nm[Ri.getPlayerState(g.getTrackId())];const M=f.audioRecv.find(j=>j.ssrc===h);if(M){M.bytes!=null&&R.bytes!=null&&et(A,at.Audio_Recv_Bitrate,8*(R.bytes-M.bytes)/(ds*Qc));const j=R.concealedSamples-M.concealedSamples;j>0&&et(A,at.Audio_Recv_Concealed_Samples,j);const H=R.totalSamplesReceived-M.totalSamplesReceived;H>0&&et(A,at.Audio_Recv_Total_Samples_Received,H);const ht=R.freezeSamples80-M.freezeSamples80;ht>0&&et(A,at.Audio_Render_Freeze_Samples_80ms,ht);const lt=R.freezeSamples200-M.freezeSamples200;lt>0&&et(A,at.Audio_Render_Freeze_Samples_200ms,lt);const rt=R.freezeMs80-M.freezeMs80;et(A,at.Audio_Render_Freeze_Time_80ms,rt<0?0:rt);const Kt=R.freezeMs200-M.freezeMs200;et(A,at.Audio_Render_Freeze_Time_200ms,Kt<0?0:Kt)}}return A}(c._audioSSRC,e,c.audioTrack,i,n,r):void 0;u&&(l.audio=u)}(l.video||l.audio)&&s.push(l)}),this.needUploadRenderFreezeTime=!this.needUploadRenderFreezeTime,s}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(i=>i instanceof xc);if(e&&e._external.getDenoiserStats){const i=e._external.getDenoiserStats();i&&this.requestUpload(Fc.DENOISER_STATS,i)}},2e3),this.uploadExtStatsTimer&&window.clearInterval(this.uploadExtStatsTimer),this.uploadExtStatsTimer=window.setInterval(()=>{!this.requestAllTracks||!this.requestUpload||this.requestAllTracks().forEach(e=>{e.getProcessorStats().forEach(i=>{this.requestUpload&&this.requestUpload(i.type,i.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.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(()=>{!this.requestUpload||!this.requestRemoteMedia||(this.requestRemoteMedia()||[]).forEach(e=>{let[i,n]=e;n.has(q.VIDEO)&&i.videoTrack&&i.videoTrack.getProcessorStats().forEach(r=>{this.requestUpload&&this.requestUpload(r.type,r.stats)}),n.has(q.AUDIO)&&i.audioTrack&&i.audioTrack.getProcessorStats().forEach(r=>{this.requestUpload&&this.requestUpload(r.type,r.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(()=>C(this,null,function*(){const i=Date.now(),n={connectionInterval:y("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3,details:[],lts:i};let r=[];const o=this.requestAllTracks&&this.requestAllTracks()||[];for(const d of o)!d.muted&&d.enabled&&(r=r.concat(yield d.getProcessorUsage()));const s=this.requestRemoteMedia&&this.requestRemoteMedia()||[];for(const[d,l]of s)l.has(q.VIDEO)&&d.videoTrack&&(r=r.concat(yield d.videoTrack.getProcessorUsage())),l.has(q.AUDIO)&&d.audioTrack&&(r=r.concat(yield d.audioTrack.getProcessorUsage()));if(r.length===0)return;n.details=function(d,l){const u={};for(const{id:m,value:f,level:T,direction:R}of d){var h;const A=(h=l.get(m))!==null&&h!==void 0?h:0,N=f===2?A+y("EXTENSION_USAGE_UPLOAD_INTERVAL")/1e3:A;var p,g;l.set(m,N),u[m]?(f===2&&(u[m].value=f),T>u[m].level&&(u[m].level=T),R==="remote"&&(u[m].remoteUidCount+=1),u[m].totalTs=(p=l.get(m))!==null&&p!==void 0?p:0):u[m]={value:f,level:T,remoteUidCount:R==="local"?0:1,totalTs:(g=l.get(m))!==null&&g!==void 0?g:0}}return Object.keys(u).map(m=>{const{level:f,value:T,totalTs:R}=u[m];return{id:m,level:f,value:T,totalTs:R}})}(r,e);const a=Date.now(),c=a>i?a:i+1;this.requestUpload&&this.requestUpload(Fc.EXTENSION_USAGE_STATS,{usageStats:n,sendTs:c})}),y("EXTENSION_USAGE_UPLOAD_INTERVAL"))}stopUploadExtensionUsageStats(){this.uploadExtensionUsageStarted&&(this.uploadExtensionUsageStarted=!1,this.uploadExtUsageStatsTimer&&window.clearInterval(this.uploadExtUsageStatsTimer),this.uploadExtUsageStatsTimer=void 0)}stopUploadBaseStats(){this.uploadBaseStatsStarted=!1}}const LW=y("ICE_RESTART_INTERVAL");let $u=new Map,Pa=new Map,yo=[Xe.UDP_TCP_RELAY,Xe.TCP_RELAY,Xe.RELAY],Jm=y("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&Ct().supportPCSetConfiguration;function c0(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const i=$u.get(t.id);i&&(window.clearTimeout(i),$u.delete(t.id));const n=Pa.get(t.id);e&&n&&n.index===yo.length-1&&(_.debug("[".concat(t.id,"] reset ICE restart policy")),Pa.delete(t.id))}function d0(t,e,i){if($u.size===0&&Pa.size===0&&(Array.isArray(y("RESTART_SEQUENCE"))&&y("RESTART_SEQUENCE").length>0&&!function(a,c){if(a.length!==c.length)return!1;for(let d=0;d<a.length;d+=1){const l=a[d];if(a.filter(u=>u===l).length!==c.filter(u=>u===l).length)return!1}return!0}(yo,y("RESTART_SEQUENCE"))&&(yo=y("RESTART_SEQUENCE").filter(a=>{var c;if(G(c=Object.values(Xe)).call(c,a))return!0}),_.debug("use reconnection policy from config distribution, queues: ".concat(yo.join(" => ")))),Jm=y("JOIN_WITH_FALLBACK_MEDIA_PROXY_FORCE")&&Ct().supportPCSetConfiguration),yo.length===0)return void i();let n,{index:r=0,type:o}=Pa.get(t.id)||{};if(Jm&&o===Xe.RELAY)return void i();let s=o&&r>=yo.length-1;if(Jm)o=Xe.RELAY;else{if(s)return void i();o?(r++,o=yo[r]):(o=yo[0],r=0)}_.debug("[".concat(t.id,"] choose ICE restart policy: ").concat(o,", index: ").concat(r)),e(o),Pa.set(t.id,{index:r,type:o}),n=window.setTimeout(()=>d0(t,e,i),LW),$u.set(t.id,n)}var pt;function l0(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function yr(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?l0(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):l0(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}function u0(t){var e,i,n,r=2;for(typeof Symbol!="undefined"&&(i=gE,n=Symbol.iterator);r--;){if(i&&(e=t[i])!=null)return e.call(t);if(n&&(e=t[n])!=null)return new th(e.call(t));i="@@asyncIterator",n="@@iterator"}throw new TypeError("Object is not async iterable")}function th(t){function e(i){if(Object(i)!==i)return K.reject(new TypeError(i+" is not an object."));var n=i.done;return K.resolve(i.value).then(function(r){return{value:r,done:n}})}return th=function(i){this.s=i,this.n=i.next},th.prototype={s:null,n:null,next:function(){return e(this.n.apply(this.s,arguments))},return:function(i){var n=this.s.return;return n===void 0?K.resolve({value:i,done:!0}):e(n.apply(this.s,arguments))},throw:function(i){var n=this.s.return;return n===void 0?K.reject(i):e(n.apply(this.s,arguments))}},new th(t)}let Zc=(pt=class extends $t{get state(){return this._state}set state(t){const e=this._state;this._state=t,this.emit($.StateChange,e,this._state)}constructor(t,e){super(),S(this,"isPlanB",void 0),S(this,"store",void 0),S(this,"statsUploader",void 0),S(this,"connection",void 0),S(this,"localTrackMap",new Map),S(this,"remoteUserMap",new Map),S(this,"localDataChannels",[]),S(this,"remoteDataChannelMap",new Map),S(this,"pendingLocalTracks",[]),S(this,"pendingRemoteTracks",[]),S(this,"pendingLocalDataChannels",[]),S(this,"pendingRemoteDataChannels",[]),S(this,"statsCollector",void 0),S(this,"shouldForwardP2PCreation",void 0),S(this,"iceFailedCount",0),S(this,"dtlsFailedCount",0),S(this,"mutex",void 0),S(this,"_state",wt.Disconnected),S(this,"_pcStatsUploadType",y("NEW_ICE_RESTART")?Hr.FIRST_CONNECTION:Hr.OLD_FIRST_CONNECTION),S(this,"_isStartRestartIce",!1),S(this,"_restartTimer",void 0),S(this,"_isTryConnecting",!1),S(this,"_iceError",null),S(this,"_forceTurn",!1),S(this,"_isWaitPcToRePub",!1),S(this,"handleMuteLocalTrack",(i,n,r)=>C(this,null,function*(){const o=yield this.mutex.lock("Locking from P2PChannel.handleMuteLocalTrack");try{if(!this.connection||this.state!==wt.Connected)return void r(new k(v.INVALID_OPERATION,"Cannot call P2PChannel.handleMuteLocalTrack before connection established."));const s=this.filterTobeMutedTracks(i);if(s.length===0)return void n();const a=s.find(d=>d[0]==="videoLowTrack");a&&a[1].track._originMediaStreamTrack.stop(),yield this.connection.muteLocal(s.map(d=>{let[,{id:l}]=d;return l}));const c=this.createMuteMessage(s);yield Bt(this,$.RequestMuteLocal,c),n()}catch(s){r(s)}finally{o()}})),S(this,"handleUnmuteLocalTrack",(i,n,r)=>C(this,null,function*(){const o=yield this.mutex.lock("Locking from P2PChannel.handleUnmuteLocalTrack");try{if(!this.connection||this.state!==wt.Connected)return void r(new k(v.INVALID_OPERATION,"Cannot call P2PChannel.handleUnmuteLocalTrack before connection established."));const s=this.filterTobeUnmutedTracks(i);if(s.length===0)return void n();const a=s.find(d=>d[0]==="videoLowTrack");if(a){const d=a[1];if(d.track._originMediaStreamTrack.stop(),!y("DISABLE_DUAL_STREAM_USE_ENCODING")&&Ct().supportDualStreamEncoding){const l=i._mediaStreamTrack.clone();d.track._mediaStreamTrack=l,d.track._originMediaStreamTrack=l}else{const l=Xm(i,Dc(this,$.RequestLowStreamParameter));d.track._mediaStreamTrack=l,d.track._originMediaStreamTrack=l}yield new K((l,u)=>{this.handleReplaceTrack(d.track,l,u,!0)})}yield this.connection.unmuteLocal(s.map(d=>{let[,{id:l}]=d;return l}));const c=this.createUnmuteMessage(s);yield Bt(this,$.RequestUnmuteLocal,c),n()}catch(s){r(s)}finally{o()}})),S(this,"handleUpdateVideoEncoder",(i,n,r,o)=>C(this,null,function*(){let s;o||(s=yield this.mutex.lock("Locking from P2PChannel.handleUpdateVideoEncoder"));try{const c=this.localTrackMap.get(V.LocalVideoTrack);if(!this.connection||!c||c.track!==i||this.state!==wt.Connected)return void n();const{id:d,track:l}=c;yield this.connection.updateSendParameters(d,l),yield this.connection.updateEncoderConfig(d,l),this.emit($.UpdateVideoEncoder,l),n()}catch(c){r(c)}finally{var a;(a=s)===null||a===void 0||a()}})),S(this,"handleUpdateVideoSendParameters",(i,n,r)=>C(this,null,function*(){const o=yield this.mutex.lock("Locking from P2PChannel.handleUpdateVideoSendParameters");try{const s=this.localTrackMap.get(V.LocalVideoTrack);if(!this.connection||!s||s.track!==i||this.state!==wt.Connected)return void n();const{id:a,track:c}=s;yield this.connection.updateSendParameters(a,c),n()}catch(s){r(s)}finally{o()}})),S(this,"handleReplaceMixingTrack",(i,n,r,o)=>C(this,null,function*(){if(!this.connection||this.state!==wt.Connected)return void n();const s=qm([i]);let a;_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(s.getTrackId(),"]")),typeof o=="boolean"&&o||(a=yield this.mutex.lock("From P2PChannel.handleReplaceMixingTrack"));try{yield this.replaceTrack(i,s),n()}catch(d){r(d)}finally{var c;(c=a)===null||c===void 0||c()}})),S(this,"handleReplaceTrack",(i,n,r,o)=>C(this,null,function*(){let s;_.debug("[".concat(this.store.clientId,"] P2PChannel handleReplaceTrack for [track-id-").concat(i.getTrackId(),"]")),typeof o=="boolean"&&o||(s=yield this.mutex.lock("From P2PChannel.handleReplaceTrack"));try{var a;const d=Array.from(this.localTrackMap.entries()).find(l=>{let[,{track:u}]=l;return i===u});if(!this.connection||!d||this.state!==wt.Connected)return void n();if(yield(a=this.connection)===null||a===void 0?void 0:a.replaceTrack(i,d[1].id),this.isPlanB){const l=d[1];l.id=i._mediaStreamTrack.id,this.localTrackMap.set(d[0],l)}if(d[0]===V.LocalVideoTrack&&!y("DISABLE_DUAL_STREAM_USE_ENCODING")&&Ct().supportDualStreamEncoding){const l=this.localTrackMap.get(V.LocalVideoLowTrack);if(l){const u=i._mediaStreamTrack.clone();l.track._originMediaStreamTrack.stop(),l.track._mediaStreamTrack=u,l.track._originMediaStreamTrack=u,yield new K((h,p)=>{this.handleReplaceTrack(l.track,h,p,!0)})}}n()}catch(d){r(d)}finally{var c;(c=s)===null||c===void 0||c()}})),S(this,"handleGetRTCStats",i=>{i(this.statsCollector.getRTCStats())}),S(this,"handleGetLocalVideoStats",i=>{i(this.statsCollector.getLocalVideoTrackStats())}),S(this,"handleGetLocalAudioStats",i=>{i(this.statsCollector.getLocalAudioTrackStats())}),S(this,"handleGetRemoteVideoStats",i=>this.statsCollector.getRemoteVideoTrackStats(i.uid)[i.uid]),S(this,"handleGetRemoteAudioStats",i=>this.statsCollector.getRemoteAudioTrackStats(i.uid)[i.uid]),this.store=t,this.statsCollector=e,this.statsCollector.addP2PChannel(this),this.statsUploader=new a0(this.store),this.bindStatsUploaderEvents(),this.mutex=new qe("P2PChannel-mutex",this.store.clientId),this.isPlanB=!Ct().supportUnifiedPlan||y("CHROME_FORCE_PLAN_B")&&Vr(),this.shouldForwardP2PCreation=y("FORWARD_P2P_CREATION")&&Ct().supportPCSetConfiguration&&NE(),this.shouldForwardP2PCreation&&(this.connection=Ju(this.store),this.emit($.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection))}startP2PConnection(t){return C(this,null,function*(){var e;this.state=wt.New,this._forceTurn=n0(t),_.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] forceTurn: ").concat(this._forceTurn));const i=this.shouldForwardP2PCreation&&((e=this.connection)===null||e===void 0?void 0:e.peerConnectionState)==="closed";if(this.shouldForwardP2PCreation&&!i||(i&&this.connection&&(_.warning("[".concat(this.store.clientId,"] P2PChannel.startP2PConnection ForwardP2P closed.")),this.resetConnection(this.connection)),this.connection=Ju(this.store,t),this.emit($.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),!this.connection)throw new k(v.UNEXPECTED_ERROR,"Cannot P2PChannel.startConnection before P2PConnection initialization .");return this._pcStatsUploadType=y("NEW_ICE_RESTART")?Hr.FIRST_CONNECTION:Hr.OLD_FIRST_CONNECTION,this._isTryConnecting=!0,this._isStartRestartIce=!1,this._iceError=null,this.connection.setConfiguration(t),this.connection.establishPromise})}connect(t){return C(this,null,function*(){if(!this.connection)throw new k(v.UNEXPECTED_ERROR,"Cannot P2PChannel.connect before P2PChannel.startP2PConnection .");y("ENABLE_PREALLOC_PC")&&this.state===wt.Connected?yield this.connection.updateRemoteConnect(t):(this.store.peerConnectionStart(),yield this.connection.connect(t),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=wt.Connected)})}updateRemoteRTPCapabilities(t){const e=Array.from(this.localTrackMap.entries()).filter(r=>{var o;let[s]=r;return G(o=[V.LocalVideoLowTrack,V.LocalVideoTrack]).call(o,s)}),i=e.map(r=>{let[,{id:o}]=r;return o}),n=e.map(r=>{let[o]=r;return o});if(this.connection instanceof Cr){if(Z.updateRemoteRTPCapabilities(this.store.sessionId,{trackTypes:JSON.stringify(n),localCodecs:JSON.stringify(this.connection.localCodecs),remoteCodecs:JSON.stringify(t)}),!G(t).call(t,this.store.codec)){const r=["vp9","vp8","h264"].find(o=>G(t).call(t,o));r&&(this.store.codec=r,_.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId," updateRemoteRTPCapabilities] default codec is not available, hence the fallback to ").concat(r,".")))}this.connection.updateRemoteRTPCapabilities(i,t)}}getEstablishParams(){return C(this,null,function*(){var t;if(this.connection instanceof Cr&&this.connection.peerConnectionState!=="closed"&&G(t=[wt.New,wt.Connected]).call(t,this.state))return this.connection.establishPromise})}publishDataChannel(t){return C(this,null,function*(){if(!this.connection||this.state!==wt.Connected){if(this.state===wt.Disconnected)throw new k(v.UNEXPECTED_ERROR,"PeerConnection already disconnected.");return t.forEach(i=>{var n;G(n=this.pendingLocalDataChannels).call(n,i)||this.pendingLocalDataChannels.push(i)}),[]}const e=this.filterTobePublishedDataChannels(t);return e.length===0?[]:(e.forEach(i=>{const n=Date.now();this.store.publish(i.id.toString(),"datachannel",n)}),yield this.connection.createDataChannels(this.store.uid,e),e.forEach(i=>{this.localDataChannels.push(i);const n=Date.now();this.store.publish(i.id+"","datachannel",void 0,n)}),t.map(i=>({streamId:i.id,ordered:i.ordered,maxRetransmits:i.maxRetransmits,metadata:i.metadata,channelId:i._originDataChannelId})))})}publish(t,e,i){var n=this;return cn(function*(){const r=yield Rt(n.mutex.lock("From P2PChannel.publish"));try{var o;const s=n.connection&&G(o=["disconnected","failed"]).call(o,n.connection.peerConnectionState);if(!n.connection||n.state!==wt.Connected||s){if(n.state===wt.Disconnected)throw new k(v.UNEXPECTED_ERROR,"PeerConnection already disconnected.");n.throwIfTrackTypeNotMatch(t);const c=t.filter(d=>n.pendingLocalTracks.indexOf(d)===-1);return n.pendingLocalTracks=n.pendingLocalTracks.concat(c),void(s&&(n._isWaitPcToRePub=!0))}n.store.pubId=n.store.pubId+1,Je.markPublishStart(n.store.clientId,n.store.pubId);const a=n.filterTobePublishedTracks(t,e,i);if(a.length===0)return void(yield Rt(n.tryToUnmuteAudio(t)));yield*vd(Xl(u0(n.doPublish(n.connection,a))))}finally{r()}})()}doPublish(t,e){var i=this;return cn(function*(){e.forEach(h=>{let{track:p,type:g}=h;const m=Date.now();i.store.publish(p.getTrackId(),g===V.LocalAudioTrack?"audio":"video",m)}),i.bindLocalTrackEvents(e);const n=e.map(h=>{let{track:p}=h;return p}),r=yield Rt(t.send(n,i.store.codec,i.store.audioCodec)),o=(yield Rt(r.next())).value,s=i.createGatewayPublishMessage(e,o);let a;try{a=yield s}catch(h){throw r.throw(h),(h==null?void 0:h.code)===v.WS_ABORT&&e.forEach(p=>{let{track:g}=p;i.pendingLocalTracks.indexOf(g)===-1&&i.pendingLocalTracks.push(g)}),i.unbindLocalTrackEvents(e),h}const c=i.mapPubResToRemoteConfig(s,a,n),d=(yield Rt(r.next(c))).value;if(i.state===wt.Disconnected)throw new k(v.UNEXPECTED_ERROR,"PeerConnection already disconnected.");y("ENABLE_VIDEO_SEI");const l=y("ENABLE_ENCODED_TRANSFORM"),u=y("ENABLE_AUDIO_METADATA");n.forEach(h=>C(this,null,function*(){const p=h.getRTCRtpTransceiver();if(!p||!l)return;const{interceptLocalVideoFrame:g,interceptLocalAudioFrame:m}=Wu();h.trackMediaType===q.VIDEO?yield g(p.sender,h):h.trackMediaType===q.AUDIO&&(yield m(p.sender,{metadata:u?()=>{const f=h.metadata.shift();return f&&f.value}:void 0}))})),e.forEach(h=>{let{type:p}=h;i.statsCollector.addLocalStats(p)}),i.assignLocalTracks(e,d),i.statsUploader.startUploadOutboundStats(),e.forEach(h=>{let{track:p,type:g}=h;const m=Date.now();i.store.publish(p.getTrackId(),g===V.LocalAudioTrack?"audio":"video",void 0,m)})})()}updateVideoStreamParameter(t,e){return C(this,null,function*(){const i=this.localTrackMap.get(e);if(!i||!this.connection)return;if(!(i.track instanceof Yt))return _.warn("[updateVideoStreamParameter]: track is not an instance of LocalVideoTrack");const{track:n}=i,r=function(o,s){const a={};return o.height&&o.width&&(a.scaleResolutionDownBy=Dm(o,s)),a.maxFramerate=o.framerate?Bi(o.framerate):void 0,a.maxBitrate=o.bitrate?1e3*o.bitrate:void 0,a}(t,n);if(n._encoderConfig||(n._encoderConfig={}),e!==V.LocalVideoLowTrack||!y("DISABLE_DUAL_STREAM_USE_ENCODING")&&Ct().supportDualStreamEncoding)r.scaleResolutionDownBy!=null&&(n._encoderConfig.scaleResolutionDownBy=r.scaleResolutionDownBy);else{const o=n._originMediaStreamTrack;if(!o.canvas)return _.warn("[".concat(n.getTrackId(),"] no canvas on track"));(function(s,a){const c=s.canvas;a.width&&(c.width=Bi(a.width)),a.height&&(c.height=Bi(a.height)),a.framerate&&(c.stopCapture&&c.stopCapture(),c.stopCapture=om(()=>{!c.startCapture&&c.stopCapture&&c.stopCapture(),c.startCapture&&c.startCapture()},Bi(a.framerate)))})(o,t)}r.maxBitrate!=null&&(n._encoderConfig.bitrateMax=r.maxBitrate/1e3),r.maxFramerate!=null&&(n._encoderConfig.frameRate&&typeof n._encoderConfig.frameRate=="object"?n._encoderConfig.frameRate.max=r.maxFramerate:n._encoderConfig.frameRate={max:r.maxFramerate}),_.debug("[".concat(n.getTrackId(),"] LowStreamEncoderConfig: , ").concat(JSON.stringify(n._encoderConfig))),yield this.connection.updateRtpSenderEncodings(n)})}publishLowStream(t){var e=this;return cn(function*(){if(!e.connection||e.state!==wt.Connected)return;const i=yield Rt(e.mutex.lock("Locking from P2PChannel.publishLowStream"));try{const r=e.localTrackMap.get(V.LocalVideoTrack);if(!r)throw new k(v.UNEXPECTED_ERROR,"Could not find high stream");if(e.localTrackMap.has(V.LocalVideoLowTrack))throw new k(v.UNEXPECTED_ERROR,"[".concat(e.store.clientId,"] Can't publish low stream when stream already publish"));const o=[{track:e.getLowVideoTrack(r.track,t),type:V.LocalVideoLowTrack}];if(yield*vd(Xl(u0(e.doPublish(e.connection,o)))),r.track.muted||!r.track.enabled){var n;const s=(n=e.localTrackMap.get(V.LocalVideoLowTrack))===null||n===void 0?void 0:n.id;s!==void 0&&(yield Rt(e.connection.muteLocal([s])))}}finally{i()}})()}republish(){return C(this,null,function*(){this.pendingLocalTracks.length>0&&(_.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),yield We(this,$.RequestRePublish,this.pendingLocalTracks),this.emit($.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[]),this.pendingLocalDataChannels.length>0&&(_.debug("Emit P2PChannelEvents.RequestRePublishDataChannel to republish datachannels."),yield We(this,$.RequestRePublishDataChannel,this.pendingLocalDataChannels),this.pendingLocalDataChannels=[]),this._isWaitPcToRePub=!1})}reSubscribe(t){return C(this,null,function*(){for(let e=this.pendingRemoteTracks.length-1;e>=0;e--){const{user:i,kind:n}=this.pendingRemoteTracks[e];(n!==q.AUDIO||i._audio_added_&&i._audioSSRC)&&(n!==q.VIDEO||i._video_added_&&i._videoSSRC)||this.pendingRemoteTracks.splice(e,1)}if(t)yield We(this,$.RequestReSubscribe,this.pendingRemoteTracks);else for(const{user:e,kind:i}of this.pendingRemoteTracks)yield this.subscribe(e,i,i===q.VIDEO?e._videoSSRC:e._audioSSRC);this.pendingRemoteTracks.forEach(e=>{let{user:i}=e;this.emit($.MediaReconnectEnd,i.uid)}),this.pendingRemoteTracks=[]})}unpublish(t){return C(this,null,function*(){if(!this.connection||this.state!==wt.Connected)return void t.forEach(n=>{const r=this.pendingLocalTracks.indexOf(n);r!==-1&&this.pendingLocalTracks.splice(r,1)});const e=this.filterTobeUnpublishedTracks(t);if(e.length===0)return;const i=e.find(n=>n[0]==="videoLowTrack");return i&&i[1].track.close(),this.doUnpublish(this.connection,e)})}unpublishDataChannel(t){return C(this,null,function*(){if(!this.connection||this.state!==wt.Connected)return void t.forEach(i=>{const n=this.pendingLocalDataChannels.indexOf(i);n!==-1&&this.pendingLocalDataChannels.splice(n,1)});const e=this.filterTobeUnpublishedDataChannels(t);return e.length!==0?(e.forEach(i=>{const n=this.localDataChannels.indexOf(i);n!==-1&&this.localDataChannels.splice(n,1)}),this.localDataChannels.length===0&&(yield this.connection.stopDataChannels(this.store.uid)),e.map(i=>i.id)):void 0})}unpublishLowStream(){return C(this,null,function*(){if(!this.connection||this.state!==wt.Connected)return;const t=this.localTrackMap.get(V.LocalVideoLowTrack);if(!t)return;t.track.close();const e=[[V.LocalVideoLowTrack,t]];return this.doUnpublish(this.connection,e)})}doUnpublish(t,e){return C(this,null,function*(){const i=this.createGatewayUnpublishMessage(e);return yield t.stopSending(e.map(n=>{let[,{id:r}]=n;return r})),this.withdrawLocalTracks(e),this.unbindLocalTrackEvents(e.map(n=>{let[r,{track:o}]=n;return{type:r,track:o}})),e.forEach(n=>{let[r]=n;this.statsCollector.removeLocalStats(r)}),this.localTrackMap.size===0&&this.statsUploader.stopUploadOutboundStats(),i})}subscribeDataChannel(t,e){return C(this,null,function*(){if(!this.connection||this.state!==wt.Connected)throw new k(v.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");const i=e.filter(n=>{var r;return!((r=this.remoteDataChannelMap.get(t))!==null&&r!==void 0&&r.get(n.id))});if(i.length!==0)return yield this.connection.createDataChannels(t.uid,i),i.forEach(n=>{var r;this.remoteDataChannelMap.has(t)?(r=this.remoteDataChannelMap.get(t))===null||r===void 0||r.set(n.id,n):this.remoteDataChannelMap.set(t,new Map([[n.id,n]]));const o=this.pendingRemoteDataChannels.findIndex(s=>{let{user:a,id:c}=s;return a.uid===t.uid&&c===n.id});o!==-1&&this.pendingRemoteDataChannels.splice(o,1)}),i.map(n=>n.id)})}subscribe(t,e,i,n,r){return C(this,null,function*(){var o;if(!this.connection||this.state!==wt.Connected)throw new k(v.INVALID_OPERATION,"Cannot subscribe remote user when peerConnection disconnected.");if((o=this.remoteUserMap.get(t))!==null&&o!==void 0&&o.has(e))return;let s,a,c;const d=this.connection.getPreMedia(i);if(d)_.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] preSSRCMap has ssrcId: ").concat(i,", no need to send sub to gateway.")),c=d.transceiver,s=d.track,a=d.id;else if(r){const h=r.find(g=>{let{stream_type:m}=g;return m===e});if(!h)throw new k(v.UNEXPECTED_ERROR,"Cannot subscribe to remote ".concat(e," for user: ").concat(t.uid," because subscribe answer from gateway does not contain stream_type: ").concat(e,"."));const p=yield this.connection.receive(e,h.ssrcs,String(t._uintid),h.attributes);this.connection instanceof Cr&&(c=p.transceiver),s=p.track,a=p.id}else{const h=yield this.connection.receive(e,[{ssrcId:i,rtx:n}],String(t._uintid),void 0);this.connection instanceof Cr&&(c=h.transceiver),s=h.track,a=h.id}if(e===q.AUDIO?(t._audioTrack?t._audioTrack._updateOriginMediaStreamTrack(s):(t._audioTrack=new Sa(s,t.uid,t._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(t._audioTrack.getTrackId()))),c&&t._audioTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(t,t._audioTrack)):(t._videoTrack?t._videoTrack._updateOriginMediaStreamTrack(s):(t._videoTrack=new ga(s,t.uid,t._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(t._videoTrack.getTrackId()))),c&&t._videoTrack._updateRtpTransceiver(c),this.bindRemoteTrackEvents(t,t._videoTrack)),c&&y("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:h,interceptRemoteAudioFrame:p}=Wu();e==q.VIDEO?yield h(c.receiver,{onSei:y("ENABLE_VIDEO_SEI")&&(g=>{var m;return(m=t._videoTrack)===null||m===void 0?void 0:m._onSei(g)})}):e==q.AUDIO&&(yield p(c.receiver,{enableTopn:!!y("ENABLE_AUDIO_TOPN"),enableMetadata:!!y("ENABLE_AUDIO_METADATA"),onMetadata:g=>{this.safeEmit($.AudioMetadata,g)}}))}const l=this.remoteUserMap.get(t);l?l.set(e,a):this.remoteUserMap.set(t,new Map([[e,a]])),this.statsCollector.addRemoteStats(t.uid),this.statsUploader.startUploadInboundStats();const u=this.pendingRemoteTracks.findIndex(h=>{let{user:p,kind:g}=h;return p.uid===t.uid&&e===g});u!==-1&&(this.pendingRemoteTracks.splice(u,1),this.emit($.MediaReconnectEnd,t.uid))})}massSubscribe(t){return C(this,null,function*(){return this.massSubscribeNoLock(t)})}massSubscribeNoLock(t){return C(this,null,function*(){if(!this.connection||this.state!==wt.Connected)throw new k(v.INVALID_OPERATION,"Cannot subscribeAll remote users when peerConnection disconnected.");t=t.filter(r=>{var o;let{user:s,mediaType:a}=r;return!((o=this.remoteUserMap.get(s))!==null&&o!==void 0&&o.has(a))});const e=[],i=new Map;t.forEach(r=>{if(!this.connection)return;const o=this.connection.getPreMedia(r.ssrcId);o?i.set(r.ssrcId,o):e.push(r)});const n=yield this.connection.batchReceive(e.map(r=>{let{user:o,mediaType:s,ssrcId:a,rtxSsrcId:c}=r;return{kind:s,ssrcMsg:[{ssrcId:a,rtx:c}],mslabel:String(o._uintid)}}));e.forEach((r,o)=>{i.set(r.ssrcId,n[o])});for(const{user:r,mediaType:o,ssrcId:s}of t){const a=i.get(s);if(!a)return void _.debug("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] cannot find ").concat(r.uid," subscribe data,").concat(o,", ").concat(s));const{track:c,id:d,transceiver:l}=a;if(l&&y("ENABLE_ENCODED_TRANSFORM")){const{interceptRemoteVideoFrame:p,interceptRemoteAudioFrame:g}=Wu();o==q.VIDEO?yield p(l.receiver,{onSei:y("ENABLE_VIDEO_SEI")&&(m=>{var f;return(f=r._videoTrack)===null||f===void 0?void 0:f._onSei(m)})}):o==q.AUDIO&&(yield g(l.receiver,{enableTopn:!!y("ENABLE_AUDIO_TOPN"),enableMetadata:!!y("ENABLE_AUDIO_METADATA"),onMetadata:m=>{this.safeEmit($.AudioMetadata,m)}}))}if(o===q.AUDIO?(r._audioTrack?r._audioTrack._updateOriginMediaStreamTrack(c):(r._audioTrack=new Sa(c,r.uid,r._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(r._audioTrack.getTrackId()))),l&&r._audioTrack._updateRtpTransceiver(l),this.bindRemoteTrackEvents(r,r._audioTrack)):(r._videoTrack?r._videoTrack._updateOriginMediaStreamTrack(c):(r._videoTrack=new ga(c,r.uid,r._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(r._videoTrack.getTrackId()))),l&&r._videoTrack._updateRtpTransceiver(l),this.bindRemoteTrackEvents(r,r._videoTrack)),y("ENABLE_VIDEO_SEI")&&l){const{interceptRemoteVideoFrame:p,interceptRemoteAudioFrame:g}=Wu();o==q.VIDEO?yield p(l.receiver,{onSei:m=>{var f;(f=r._videoTrack)===null||f===void 0||f._onSei(m)}}):o==q.AUDIO&&(yield g(l.receiver))}const u=this.remoteUserMap.get(r);u?u.set(o,d):this.remoteUserMap.set(r,new Map([[o,d]])),this.statsCollector.addRemoteStats(r.uid),this.statsUploader.startUploadInboundStats();const h=this.pendingRemoteTracks.findIndex(p=>{let{user:g,kind:m}=p;return g.uid===r.uid&&o===m});h!==-1&&(this.pendingRemoteTracks.splice(h,1),this.emit($.MediaReconnectEnd,r.uid))}})}unsubscribe(t,e,i){return C(this,null,function*(){const n=this.pendingRemoteTracks.filter(s=>{let{user:a,kind:c}=s;return e!==void 0?a.uid===t.uid&&e===c:a.uid===t.uid});if(n.forEach(s=>{const a=this.pendingRemoteTracks.indexOf(s);this.pendingRemoteTracks.splice(a,1)}),this.connection&&this.state===wt.Connected||i||n.forEach(s=>{let{kind:a}=s;var c;if(a===q.AUDIO)(c=t._audioTrack)===null||c===void 0||c._destroy(),t._audioTrack=void 0;else if(a===q.VIDEO){var d;(d=t._videoTrack)===null||d===void 0||d._destroy(),t._videoTrack=void 0}}),!this.connection||this.state!==wt.Connected)return;const r=this.filterTobeUnSubscribedTracks(t,e);if(r.length===0)return;yield this.connection.stopReceiving(r.map(s=>{let[,{id:a}]=s;return a}));const o=this.createUnsubscribeMessage(r);return this.withdrawRemoteTracks(r),this.remoteUserMap.size===0&&this.statsUploader.stopUploadInboundStats(),r.forEach(s=>{let[a,{kind:c}]=s;var d,l;if(c===q.VIDEO&&a._videoSSRC&&((d=this.connection)===null||d===void 0||d.setStatsRemoteVideoIsReady(a._videoSSRC,!1)),c===q.VIDEO)this.unbindRemoteTrackEvents(a._videoTrack),i||((l=a._videoTrack)===null||l===void 0||l._destroy(),a._videoTrack=void 0);else if(c===q.AUDIO){var u;this.unbindRemoteTrackEvents(a._audioTrack),!i&&((u=a._audioTrack)===null||u===void 0||u._destroy(),a._audioTrack=void 0)}}),o})}unsubscribeDataChannel(t,e){return C(this,null,function*(){if(e.forEach(r=>{const o=this.pendingRemoteDataChannels.findIndex(s=>s.id===r.id);o!==-1&&this.pendingRemoteDataChannels.splice(o,1)}),!this.connection)return;const i=this.filterTobeUnSubscribedDataChannels(t,e);if(i.length===0)return;e.forEach(r=>{r._close()});const n=this.remoteDataChannelMap.get(t);return i.forEach(r=>{n&&n.delete(r.id)}),n&&n.size===0&&(this.remoteDataChannelMap.delete(t),yield this.connection.stopDataChannels(t.uid)),i.map(r=>r.id)})}massUnsubscribe(t){return C(this,null,function*(){return this.massUnsubscribeNoLock(t)})}massUnsubscribeNoLock(t){return C(this,null,function*(){let e=[];for(const{user:r,mediaType:o}of t){const s=this.pendingRemoteTracks.filter(a=>{let{user:c,kind:d}=a;return o!==void 0?c.uid===r.uid&&o===d:c.uid===r.uid});s.forEach(a=>{const c=this.pendingRemoteTracks.indexOf(a);this.pendingRemoteTracks.splice(c,1)}),e=e.concat(s)}if(!this.connection||this.state!==wt.Connected)return void e.forEach(r=>{let{user:o,kind:s}=r;var a;if(s===q.AUDIO)(a=o._audioTrack)===null||a===void 0||a._destroy(),o._audioTrack=void 0;else if(s===q.VIDEO){var c;(c=o._videoTrack)===null||c===void 0||c._destroy(),o._videoTrack=void 0}});const i=Tn(t).call(t,(r,o)=>{let{user:s,mediaType:a}=o;const c=this.filterTobeUnSubscribedTracks(s,a);return r.concat(c)},[]);if(i.length===0)return;yield this.connection.stopReceiving(i.map(r=>{let[,{id:o}]=r;return o}));const n=this.createUnsubscribeAllMessage(i);return this.withdrawRemoteTracks(i),this.remoteUserMap.size===0&&this.statsUploader.stopUploadInboundStats(),i.forEach(r=>{let[o,{kind:s}]=r;var a,c;if(s===q.VIDEO&&o._videoSSRC&&((a=this.connection)===null||a===void 0||a.setStatsRemoteVideoIsReady(o._videoSSRC,!1)),s===q.VIDEO)this.unbindRemoteTrackEvents(o._videoTrack),(c=o._videoTrack)===null||c===void 0||c._destroy(),o._videoTrack=void 0;else if(s===q.AUDIO){var d;this.unbindRemoteTrackEvents(o._audioTrack),(d=o._audioTrack)===null||d===void 0||d._destroy(),o._audioTrack=void 0}}),n})}isPreSubScribe(t){return!this.connection||this.state!==wt.Connected?!1:!!this.connection.getPreMedia(t)}muteRemote(t,e){return C(this,null,function*(){if(!this.connection)return;const i=this.remoteUserMap.get(t);if(!i)return void _.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(t.uid,"."));if(!i.get(e))return void _.warning("[".concat(this.store.clientId,"] P2PChannel.muteRemote has no remote user ").concat(t.uid," media type ").concat(e,"."));const n=e===q.VIDEO?t._videoSSRC:t._audioSSRC;n!==void 0&&this.connection.setStatsRemoteVideoIsReady(n,!1)})}unmuteRemote(t,e){return C(this,null,function*(){return this.unmuteRemoteNoLock(t,e)})}unmuteRemoteNoLock(t,e){return C(this,null,function*(){if(!this.connection)return;const i=this.remoteUserMap.get(t);if(!i)return void _.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(t.uid,"."));i.get(e)||_.warning("[".concat(this.store.clientId,"] P2PChannel.unmuteRemote has no remote user ").concat(t.uid," media type ").concat(e,"."))})}addAudioMetadata(t){const e=this.localTrackMap.get(V.LocalAudioTrack),i=e&&e.track;i&&i.metadata.push(t)}getAllTracks(t){const e=this.localTrackMap.get(V.LocalAudioTrack);if((e==null?void 0:e.track)instanceof ve){const i=e.track;return Array.from(this.localTrackMap.entries()).filter(n=>{let[r]=n;return r!==V.LocalAudioTrack}).filter(n=>{let[r]=n;return!(t&&r===V.LocalVideoLowTrack)}).map(n=>{let[,{track:r}]=n;return r}).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter(i=>{let[n]=i;return!(t&&n===V.LocalVideoLowTrack)}).map(i=>{let[,{track:n}]=i;return n})}getAllDataChannels(){return this.localDataChannels}reportPublishEvent(t,e,i,n,r){if(t){const s=this.localTrackMap.get(V.LocalAudioTrack),a=n?this.localTrackMap.get(V.LocalVideoLowTrack):this.localTrackMap.get(V.LocalVideoTrack);Z.publish(this.store.sessionId,{eventElapse:Je.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:t,ec:e,audioName:s==null?void 0:s.track.getTrackLabel(),videoName:a==null?void 0:a.track.getTrackLabel(),screenshare:(a==null?void 0:a.track._hints.indexOf(Vt.SCREEN_TRACK))!==-1,audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;i||(i=[]);const s=i.find(c=>c instanceof ae),a=n?(o=this.localTrackMap.get(V.LocalVideoTrack))===null||o===void 0?void 0:o.track:i.find(c=>c instanceof Yt);Z.publish(this.store.sessionId,{eventElapse:Je.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:t,ec:e,audioName:s==null?void 0:s.getTrackLabel(),videoName:a==null?void 0:a.getTrackLabel(),screenshare:(a==null?void 0:a._hints.indexOf(Vt.SCREEN_TRACK))!==-1,audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(t,e,i,n){const r=n===q.VIDEO?i._videoSSRC:i._audioSSRC;r&&Z.subscribe(this.store.sessionId,{succ:t,ec:e,video:n===q.VIDEO,audio:n===q.AUDIO,peerid:i.uid,subscribeRequestid:r,p2pid:this.store.p2pId,eventElapse:Je.measureFromSubscribeStart(this.store.clientId,r),preSsrc:this.isPreSubScribe(r)})}reset(){_.debug("[".concat(this.store.clientId,"] P2PChannel.reset")),this.mutex=new qe("P2PChannel-mutex",this.store.clientId),this.connection&&(this.resetConnection(this.connection),this.connection=void 0),this.shouldForwardP2PCreation&&(this.connection=Ju(this.store),this.emit($.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),this.statsUploader.stopUploadExtensionUsageStats(),this.statsUploader.stopUploadBaseStats(),this.unbindLocalTrackEvents(),this.unbindAllRemoteTrackEvents(),this.unbindRtpTransceiver();const t=this.localTrackMap.get(V.LocalAudioTrack);if((t==null?void 0:t.track)instanceof ve){if(t.track.trackList.length>0){const e=t.track;t.track.trackList.forEach(i=>{e.removeAudioTrack(i)})}t.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=wt.Disconnected}getStats(){var t;return(t=this.connection)===null||t===void 0?void 0:t.getStats()}getRemoteVideoIsReady(t){var e;return((e=this.connection)===null||e===void 0?void 0:e.getRemoteVideoIsReady(t))||!1}getLocalAudioVolume(){const t=this.localTrackMap.get(V.LocalAudioTrack);if(t)return t.track.getVolumeLevel()}getLocalVideoSize(){const t=this.localTrackMap.get(V.LocalVideoTrack);if(t)return{width:t.track.videoWidth||0,height:t.track.videoHeight||0}}getEncoderConfig(t){const e=this.localTrackMap.get(t);return e&&e.track instanceof Yt||e&&e.track instanceof ae?e.track._encoderConfig:void 0}getLocalMedia(t){return this.localTrackMap.get(t)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(t,e){if(!t)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(t);return!!i&&(!e||i.has(e))}hasRemoteMediaWithLock(t,e){return C(this,null,function*(){if(!t)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(t);return!!i&&(!e||i.has(e))})}getRemoteMedia(t){var e;const i=Array.from(Ji(e=this.remoteUserMap).call(e)).find(n=>n.uid===t);return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let t=Array.from(this.remoteUserMap.entries()).map(i=>{let[n]=i;return{uid:n.uid,level:n.audioTrack?100*n.audioTrack._source.getAccurateVolumeLevel():0}});const e=this.localTrackMap.get(V.LocalAudioTrack);return e&&t.push({level:100*e.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),t=jo(t).call(t,(i,n)=>i.level-n.level),t}disconnectForReconnect(){return C(this,null,function*(){this.connection&&(_.debug("[".concat(this.store.clientId,"] P2PChannel.disconnectForReconnect closing P2PConnection")),this.state=wt.Reconnecting,y("KEEP_LAST_FRAME")&&this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(t=>{let[e]=t;var i;e._videoTrack&&e._videoTrack._player&&((i=e._videoTrack._player.getVideoElement())===null||i===void 0||i.pause(),e._videoTrack._player.isKeepLastFrame=!0,e._videoTrack._originMediaStreamTrack.stop())}),this.resetConnection(this.connection),this.connection=void 0,this.shouldForwardP2PCreation&&(this.connection=Ju(this.store),this.emit($.PeerConnectionStateChange,this.connection.peerConnectionState),this.bindConnectionEvents(this.connection)),this.localTrackMap.size!==0&&(Array.from(this.localTrackMap.entries()).forEach(t=>{var e;let[i,{track:n}]=t;switch(i){case V.LocalVideoTrack:G(e=n._hints).call(e,Vt.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case V.LocalAudioTrack:n instanceof ve?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case V.LocalVideoLowTrack:}}),this.emit($.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(t=>{let[e,i]=t;Array.from(Ji(i).call(i)).forEach(n=>{this.setPendingRemoteMedia(e,n)}),this.emit($.MediaReconnectStart,e.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.localDataChannels.length!==0&&(this.localDataChannels.forEach(t=>{this.pendingLocalDataChannels.push(t)}),this.localDataChannels.length=0),this.remoteDataChannelMap.size!==0&&(Array.from(this.remoteDataChannelMap.entries()).forEach(t=>{let[e,i]=t;Array.from(Ji(i).call(i)).forEach(n=>{this.setPendingRemoteDataChannel(e,n)})}),this.remoteDataChannelMap.clear()),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),_.debug("[".concat(this.store.clientId,"] P2PChannel disconnected, waiting to reconnect.")))})}hasPendingRemoteDataChannel(t,e){for(const i of this.pendingRemoteDataChannels){const{user:n,id:r}=i;if((t instanceof Co?t.uid:t)===n.uid&&r===e)return!0}return!1}setPendingRemoteDataChannel(t,e){this.hasPendingRemoteDataChannel(t,e)||this.pendingRemoteDataChannels.push({user:t,id:e})}hasPendingRemoteMedia(t,e){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((t instanceof Co?t.uid:t)===n.uid&&e===r)return!0}return!1}setPendingRemoteMedia(t,e){this.hasPendingRemoteMedia(t,e)||this.pendingRemoteTracks.push({user:t,kind:e})}restartICE(t){var e=this;return cn(function*(){if(!e.connection||e.state!==wt.Connected)return;const i=yield Rt(e.mutex.lock("From P2PChannel.restartICE"));let n;try{n=yield Rt(e.connection.restartICE(t));const o=yield Rt(n.next());if(o.done)return;const s=o.value,a=yield s;switch(zm(e.connection)&&e.reportPCStats(Date.now(),!1,e._pcStatsUploadType),t){case Xe.UDP_TCP_RELAY:e._pcStatsUploadType=Hr.UDP_TCP_RESTART;break;case Xe.TCP_RELAY:e._pcStatsUploadType=Hr.TCP_RESTART;break;case Xe.RELAY:e._pcStatsUploadType=Hr.RELAY_RESTART;break;default:e._pcStatsUploadType=Hr.OLD_RESTART}e._isTryConnecting=!0,n.next(a)}catch(o){var r;(r=n)===null||r===void 0||r.throw(o)}finally{i()}})()}getUplinkNetworkQuality(){if(!this.connection)return 0;const t=this.connection.getStats(),e=this.localTrackMap.get(V.LocalVideoTrack),i=this.localTrackMap.get(V.LocalAudioTrack),n=t.videoSend.find(p=>p.ssrc===(e==null?void 0:e.ssrcs[0].ssrcId)),r=t.audioSend.find(p=>p.ssrc===(i==null?void 0:i.ssrcs[0].ssrcId));if(!n||!r)return 1;const o=zi(this,$.NeedSignalRTT),s=n?n.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*t.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=e==null?void 0:e.track;if(h&&h._encoderConfig&&h._hints.indexOf(Vt.SCREEN_TRACK)===-1){const p=h._encoderConfig.bitrateMax,g=t.bitrate.actualEncoded;if(p&&g){const m=(1e3*p-g)/(1e3*p);return Xb[m<.15?0:m<.3?1:m<.45?2:m<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.connection)return 0;const t=this.connection.getStats();let e=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=t.audioRecv.find(g=>g.ssrc===r),a=t.videoRecv.find(g=>g.ssrc===o);if(!s&&!a)return void(e+=1);const c=zi(this,$.NeedSignalRTT),d=t.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=t.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400),e+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5}),this.remoteUserMap.size>0?Math.round(e/this.remoteUserMap.size):e}muteLocalTrack(t){return C(this,null,function*(){return new K((e,i)=>{this.handleMuteLocalTrack(t,e,i)})})}replaceTrack(t,e){return C(this,null,function*(){var i;if(_.debug("[".concat(this.store.clientId,"] P2PChannel replaceTrack from [").concat(t.getTrackId(),"] to [").concat(e.getTrackId(),"]")),!this.connection||this.state!==wt.Connected)return;const n=Array.from(this.localTrackMap.entries()).find(o=>{let[,{track:s}]=o;return t===s});if(!n)return;const r=n[0];if(t!==e&&(this.unbindLocalTrackEvents([{track:t,type:r}]),this.bindLocalTrackEvents([{track:e,type:r}]),n[1].track=e),yield(i=this.connection)===null||i===void 0?void 0:i.replaceTrack(e,n[1].id),this.isPlanB){const o=n[1];o.id=e._mediaStreamTrack.id,this.localTrackMap.set(r,o)}if(r===V.LocalVideoTrack&&!y("DISABLE_DUAL_STREAM_USE_ENCODING")&&Ct().supportDualStreamEncoding){const o=this.localTrackMap.get(V.LocalVideoLowTrack);if(o){const s=t._mediaStreamTrack.clone();o.track._originMediaStreamTrack.stop(),o.track._mediaStreamTrack=s,o.track._originMediaStreamTrack=s,yield new K((a,c)=>{this.handleReplaceTrack(o.track,a,c,!0)})}}})}filterTobePublishedTracks(t,e,i){const n=[],r=this.getAllTracks();t=oa(t=t.filter(c=>r.indexOf(c)===-1));let o,s=!1;const a=this.localTrackMap.get(V.LocalAudioTrack);for(const c of t){if(c instanceof Yt&&(this.localTrackMap.has(V.LocalVideoTrack)||s?new k(v.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:c,type:V.LocalVideoTrack}),s=!0),e)){const d=this.getLowVideoTrack(c,i);n.push({track:d,type:V.LocalVideoLowTrack})}if(c instanceof ae)if(a){const d=a.track;if(d instanceof ve)Ym([c]),d.addAudioTrack(c),this.bindLocalAudioTrackEvents(c,!0);else{const l=qm([d,c]);_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will replace audioTrack [").concat(l.getTrackId(),"]")),this.replaceTrack(d,l)}}else o instanceof ve?(Ym([c]),o.addAudioTrack(c)):o||!c._useAudioElement&&Ct().webAudioMediaStreamDest&&!c._bypassWebAudio?o=qm(o?[c,o]:[c]):o=c}return o&&(_.debug("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection will send audioTrack [").concat(o.getTrackId(),"]")),n.push({track:o,type:V.LocalAudioTrack})),n}filterTobeUnpublishedTracks(t){const e=[],i=this.getAllTracks();t=oa(t=t.filter(n=>i.indexOf(n)!==-1));for(const n of t){if(n instanceof ae){const r=this.localTrackMap.get(V.LocalAudioTrack);if(!r)continue;r.track instanceof ve?(r.track.removeAudioTrack(n),this.unbindLocalAudioTrackEvents(n),r.track.trackList.length===0&&(e.push([V.LocalAudioTrack,r]),r.track.close())):e.push([V.LocalAudioTrack,r])}if(n instanceof Yt){const r=this.localTrackMap.get(V.LocalVideoTrack);if(!r)continue;e.push([V.LocalVideoTrack,r]);const o=this.localTrackMap.get(V.LocalVideoLowTrack);o&&e.push([V.LocalVideoLowTrack,o])}}return e}filterTobePublishedDataChannels(t){return t=(t=oa(t)).filter(e=>this.localDataChannels.findIndex(i=>i.id===e.id)===-1)}filterTobeUnpublishedDataChannels(t){return t=(t=(t=oa(t)).filter(e=>this.localDataChannels.indexOf(e)!==-1)).filter(e=>e._originDataChannel)}bindLocalTrackEvents(t){t.forEach(e=>{let{track:i,type:n}=e;switch(n){case V.LocalVideoTrack:i.addListener(J.GET_STATS,this.handleGetLocalVideoStats),i.addListener(J.GET_RTC_STATS,this.handleGetRTCStats),i.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.addListener(J.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),i.addListener(J.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),i.addListener(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),i.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case V.LocalAudioTrack:this.bindLocalAudioTrackEvents(i);case V.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(t,e){t instanceof ve?t.trackList.forEach(i=>{i.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.addListener(J.GET_STATS,this.handleGetLocalAudioStats),i.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(t.addListener(J.GET_STATS,this.handleGetLocalAudioStats),t.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),e||(t.addListener(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.addListener(J.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack)))}unbindLocalTrackEvents(t){t||(t=Array.from(this.localTrackMap.entries()).map(e=>{let[i,{track:n}]=e;return{track:n,type:i}})),t.forEach(e=>{let{track:i,type:n}=e;switch(n){case V.LocalVideoTrack:i.off(J.GET_STATS,this.handleGetLocalVideoStats),i.off(J.GET_RTC_STATS,this.handleGetRTCStats),i.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.off(J.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),i.off(J.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),i.off(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),i.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case V.LocalAudioTrack:this.unbindLocalAudioTrackEvents(i);case V.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(t){t instanceof ve?t.trackList.forEach(e=>{e.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(J.GET_STATS,this.handleGetLocalAudioStats),e.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(t.off(J.GET_STATS,this.handleGetLocalAudioStats),t.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(J.NEED_REPLACE_MIXING_TRACK,this.handleReplaceMixingTrack),t.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(t,e){e instanceof ga&&e.addListener(J.GET_STATS,i=>{i(this.handleGetRemoteVideoStats(t))}),e instanceof Sa&&e.addListener(J.GET_STATS,i=>{i(this.handleGetRemoteAudioStats(t))})}unbindRemoteTrackEvents(t){t&&t.removeAllListeners(J.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(t=>{let[e,i]=t;i.has(q.AUDIO)&&this.unbindRemoteTrackEvents(e._audioTrack),i.has(q.VIDEO)&&this.unbindRemoteTrackEvents(e._videoTrack)})}createGatewayPublishMessage(t,e){return t.map((i,n)=>{var r;let o,s,{track:a,type:c}=i;switch(c){case V.LocalAudioTrack:o=Ot.Audio,s={dtx:a instanceof xc&&a._config.DTX,hq:!1,lq:!1,stereo:!1,speech:!1};break;case V.LocalVideoTrack:o=G(r=a._hints).call(r,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High,s=yr(yr({},uw(a)),{},{codec:this.store.codec,svc_mode:Vu()});break;case V.LocalVideoLowTrack:o=Ot.Low,s=yr(yr({},uw(a)),{},{codec:this.store.codec,svc_mode:Vu()})}return{stream_type:o,attributes:s,ssrcs:e[n]}})}createGatewayUnpublishMessage(t){return t.map(e=>{var i;let n,[r,{track:o,ssrcs:s,id:a}]=e;switch(r){case V.LocalVideoTrack:n=G(i=o._hints).call(i,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High;break;case V.LocalAudioTrack:n=Ot.Audio;break;case V.LocalVideoLowTrack:n=Ot.Low}return{stream_type:n,ssrcs:s,mid:a}})}assignLocalTracks(t,e){t.forEach((i,n)=>{let{track:r,type:o}=i;this.localTrackMap.set(o,{track:r,id:e[n].id,ssrcs:e[n].localSSRC})})}withdrawLocalTracks(t){t.forEach(e=>{let[i]=e;this.localTrackMap.delete(i)})}bindConnectionEvents(t){t.onConnectionStateChange=e=>C(this,null,function*(){if(_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onConnectionStateChange(").concat(e,")")),this.emit($.PeerConnectionStateChange,e),e==="connecting"&&t instanceof Cr&&!ne()&&y("FIRST_TCP_CANDIDATE")&&window.setTimeout(()=>{e==="connecting"&&t.extendCandidate()},y("FIRST_TCP_CANDIDATE_INTERVAL")),e!=="connected"||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),e==="connected"&&(this._restartTimer&&(window.clearTimeout(this._restartTimer),this._restartTimer=void 0),t instanceof Cr&&c0(t,!0),this._isTryConnecting&&this.reportPCStats(Date.now(),!0,this._pcStatsUploadType),this._isTryConnecting=!1,this._isStartRestartIce=!1,this._pcStatsUploadType=Hr.DISCONNECTED_OR_FAILED,zi(this,$.QueryClientConnectionState)==="CONNECTED"&&this._isWaitPcToRePub)){const i=this.pendingLocalTracks.map(r=>r.getTrackId()),n=this.pendingLocalDataChannels.map(r=>"dc_".concat(r.id));Z.reportApiInvoke(this.store.sessionId,{name:_e.REPUB_AFTER_PC_CONNECTED,options:i.concat(n),tag:oe.TRACER}).onSuccess(),this.republish()}if(y("NEW_ICE_RESTART")&&t instanceof Cr&&!ne()&&!this._forceTurn){if(G(ow).call(ow,e)){if(this._isStartRestartIce)return;this._isStartRestartIce=!0;const i=r=>{zm(t)&&(_.debug("[".concat(this.store.clientId,"] [P2PChannel] try to restartICE, type is ").concat(r)),zi(this,$.QueryClientConnectionState)==="CONNECTED"&&this.emit($.RequestRestartICE,r))},n=()=>{zm(t)&&(this.reportPCStats(Date.now(),!1,this._pcStatsUploadType),_.debug("[".concat(this.store.clientId,"] P2PConnection disconnected timeout, force reconnect")),setTimeout(()=>this.emit($.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())};return void(this._restartTimer=window.setTimeout(()=>{d0(t,i,n)},800))}}else{if(e==="disconnected"&&t.iceConnectionState==="disconnected")return setTimeout(()=>{t.iceConnectionState==="disconnected"&&y("ICE_RESTART")&&zi(this,$.QueryClientConnectionState)==="CONNECTED"&&this.emit($.RequestRestartICE)},800),void setTimeout(()=>{t.peerConnectionState==="disconnected"&&(_.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($.P2PLost),0),this.iceFailedCount+=1,this.requestReconnect())},4e3);e==="failed"&&(_.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($.P2PLost),0),this.iceFailedCount+=1,yield this.requestReconnect())}}),t.onICEConnectionStateChange=e=>{e!=="connected"||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),Z.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:oe.TRACER}).onSuccess(),this.emit($.IceConnectionStateChange,e)},t.onICETransportStateChange=e=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},t.onDTLSTransportStateChange=e=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},t.onDTLSTransportError=e=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},t.onFirstAudioDecoded=e=>{var i;const n=Array.from(Ji(i=this.remoteUserMap).call(i)).find(o=>o._audioSSRC===e);var r;n&&(this.store.subscribe(n.uid,"audio",void 0,void 0,void 0,Date.now()),(r=n.audioTrack)===null||r===void 0||r.emit(pa.FIRST_FRAME_DECODED),Z.firstRemoteFrame(this.store.sessionId,Oe.FIRST_AUDIO_DECODE,Jt.FIRST_AUDIO_DECODE,{peer:n._uintid,subscribeElapse:Je.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},t.onFirstAudioReceived=e=>{var i;const n=Array.from(Ji(i=this.remoteUserMap).call(i)).find(r=>r._audioSSRC===e);n&&Z.firstRemoteFrame(this.store.sessionId,Oe.FIRST_AUDIO_RECEIVED,Jt.FIRST_AUDIO_RECEIVED,{peer:n._uintid,subscribeElapse:Je.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},t.onFirstVideoDecoded=(e,i,n)=>{this.reportVideoFirstFrameDecoded(e,i,n)},t.onFirstVideoReceived=e=>{var i;const n=Array.from(Ji(i=this.remoteUserMap).call(i)).find(r=>r._videoSSRC===e);n&&Z.firstRemoteFrame(this.store.sessionId,Oe.FIRST_VIDEO_RECEIVED,Jt.FIRST_VIDEO_RECEIVED,{peer:n._uintid,subscribeElapse:Je.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},t.onSelectedLocalCandidateChanged=(e,i)=>{const n=e.candidateType==="relay",r=i.candidateType==="relay";i.candidateType!=="unknown"&&n===r||this.emit($.ConnectionTypeChange,n),_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(To(i))," -> ").concat(JSON.stringify(To(e)),")"))},t.onSelectedRemoteCandidateChanged=(e,i)=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(To(i))," -> ").concat(JSON.stringify(To(e)),")"))},t.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},t.getLocalVideoStats=()=>{const e=this.statsCollector.getLocalVideoTrackStats(),i=this.statsCollector.getRTCStats();return yr(yr({},e),i)},t.onICECandidateError=e=>{this._iceError=e}}resetConnection(t){t instanceof Cr&&function(e){Pa.delete(e.id),c0(e)}(t),t.close(),this.emit($.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}(t),this._isWaitPcToRePub=!1}filterTobeMutedTracks(t){const e=[];if(this.getAllTracks().indexOf(t)===-1)return e;const i=this.localTrackMap.get(V.LocalAudioTrack);if(t instanceof ae&&(i==null?void 0:i.track)instanceof ve)return i.track.isActive||e.push([V.LocalAudioTrack,i]),e;const n=Array.from(this.localTrackMap.entries()).find(r=>{let[,{track:o}]=r;return t===o});if(n&&(e.push(n),n[0]===V.LocalVideoTrack)){const r=this.localTrackMap.get(V.LocalVideoLowTrack);r&&e.push([V.LocalVideoLowTrack,r])}return e}filterTobeUnmutedTracks(t){const e=[],i=this.localTrackMap.get(V.LocalAudioTrack);if(t instanceof ae&&(i==null?void 0:i.track)instanceof ve)return i.track.isActive&&e.push([V.LocalAudioTrack,i]),e;const n=Array.from(this.localTrackMap.entries()).find(r=>{let[,{track:o}]=r;return t===o});if(n)if(n[0]===V.LocalVideoTrack){e.push(n);const r=this.localTrackMap.get(V.LocalVideoLowTrack);r&&e.push([V.LocalVideoLowTrack,r])}else e.push(n);return e}createMuteMessage(t){return t.map(e=>{var i;let n,[r,{track:o,ssrcs:s,id:a}]=e;switch(r){case V.LocalAudioTrack:n=Ot.Audio;break;case V.LocalVideoTrack:n=G(i=o._hints).call(i,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High;break;case V.LocalVideoLowTrack:n=Ot.Low}return{stream_type:n,ssrcs:s,mid:a}})}createUnmuteMessage(t){return t.map(e=>{var i;let n,[r,{track:o,ssrcs:s,id:a}]=e;switch(r){case V.LocalAudioTrack:n=Ot.Audio;break;case V.LocalVideoTrack:n=G(i=o._hints).call(i,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High;break;case V.LocalVideoLowTrack:n=Ot.Low}return{stream_type:n,ssrcs:s,mid:a}})}filterTobeUnSubscribedTracks(t,e){const i=[],n=this.remoteUserMap.get(t);if(!n)return i;if(e){const r=n.get(e);if(!r)return i;i.push([t,{kind:e,id:r}])}else Array.from(n.entries()).forEach(r=>{let[o,s]=r;i.push([t,{kind:o,id:s}])});return i}filterTobeUnSubscribedDataChannels(t,e){const i=[];return e.forEach(n=>{var r;(r=this.remoteDataChannelMap.get(t))!==null&&r!==void 0&&r.has(n.id)&&i.push(n)}),i}createUnsubscribeMessage(t){const e=[];return t.forEach(i=>{let[n,{kind:r,id:o}]=i;switch(r){case q.VIDEO:return void(n._videoSSRC&&e.push({stream_type:q.VIDEO,ssrcId:n._videoSSRC}));case q.AUDIO:return void(n._audioSSRC&&e.push({stream_type:q.AUDIO,ssrcId:n._audioSSRC}))}}),e}createUnsubscribeAllMessage(t){const e=new Map;return t.forEach(i=>{let[n,{kind:r}]=i;if(e.has(n)){let o=e.get(n);r===q.VIDEO?o|=Ne.Video:o|=Ne.Audio,e.set(n,o)}else r===q.VIDEO?e.set(n,Ne.Video):e.set(n,Ne.Audio)}),{users:Array.from(e.entries()).map(i=>{let[n,r]=i;return{stream_id:n.uid,stream_type:r}})}}withdrawRemoteTracks(t){t.forEach(e=>{let[i,{kind:n}]=e;const r=this.remoteUserMap.get(i);r&&(r.delete(n),Array.from(r.entries()).length===0&&this.remoteUserMap.delete(i))})}updateBitrateLimit(t){return C(this,null,function*(){const e=this.localTrackMap.get(V.LocalVideoTrack),i=this.localTrackMap.get(V.LocalVideoLowTrack);e&&(yield e.track.setBitrateLimit(t.uplink),yield new K((n,r)=>{this.handleUpdateVideoEncoder(e.track,n,r,!0)})),i&&t.low_stream_uplink&&(yield i.track.setBitrateLimit({max_bitrate:t.low_stream_uplink.bitrate,min_bitrate:t.low_stream_uplink.bitrate||0}),yield new K((n,r)=>{this.handleUpdateVideoEncoder(i.track,n,r,!0)}))})}isP2PDisconnected(){return this.connection?this.connection.peerConnectionState!=="connected":!0}mapPubResToRemoteConfig(t,e,i){return t.map((n,r)=>{var o;let{stream_type:s}=n;const a=(o=e.find(c=>{let{stream_type:d}=c;return s===d}))===null||o===void 0?void 0:o.attributes;if(a&&y("DISABLE_SCREEN_SHARE_REMB")){const c=i[r]._hints;(G(c).call(c,Vt.SCREEN_TRACK)||G(c).call(c,Vt.SCREEN_LOW_TRACK))&&(a.remb=!1,_.debug("disable remb for screen share, hints:",c))}return a})}tryToUnmuteAudio(t){return C(this,null,function*(){for(let i=0;i<t.length;i++)if(t[i]instanceof ae){var e;const n=this.filterTobeUnmutedTracks(t[i]);if(n.length===0)continue;yield(e=this.connection)===null||e===void 0?void 0:e.unmuteLocal(n.map(o=>{let[,{id:s}]=o;return s}));const r=this.createUnmuteMessage(n);return void(yield Bt(this,$.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=t=>{var e;return!((e=this.connection)===null||e===void 0||!e.getRemoteVideoIsReady(t))},this.statsUploader.requestUpload=(t,e)=>this.emit($.RequestUpload,t,e),this.statsUploader.requestUploadStats=t=>this.emit($.RequestUploadStats,t),this.statsUploader.requestAllTracks=()=>this.getAllTracks(),this.statsUploader.requestTransportStats=()=>{var t;return{connectState:((t=this.connection)===null||t===void 0?void 0:t.peerConnectionState)||"closed"}}}unbindStatsUploaderEvents(){this.statsUploader.requestStats=void 0,this.statsUploader.requestLocalMedia=void 0,this.statsUploader.requestRemoteMedia=void 0,this.statsUploader.requestVideoIsReady=void 0}requestReconnect(){return C(this,null,function*(){this.dtlsFailedCount+=1,yield Ue(FE(this.dtlsFailedCount,ge)),this.emit($.RequestReconnect)})}reconnectP2P(){return C(this,null,function*(){const t=Array.from(this.localTrackMap.entries()),e=this.createGatewayUnpublishMessage(t);Array.from(this.remoteUserMap.entries()),e.length>0&&(yield We(this,$.RequestUnpublishForReconnectPC,e)),this.disconnectForReconnect(),this.emit($.RequestReconnectPC)})}canPublishLowStream(){return this.localTrackMap.has(V.LocalVideoTrack)||this.pendingLocalTracks.some(t=>t instanceof Yt)}throwIfTrackTypeNotMatch(t){if(t.filter(e=>e instanceof Yt).length>1)throw new k(v.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t.filter(e=>e instanceof ae).length>1&&(t.some(e=>e instanceof ae&&e._bypassWebAudio)||!Ct().webAudioMediaStreamDest))throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const e of t){if(e instanceof Yt&&this.pendingLocalTracks.some(i=>i instanceof Yt))throw new k(v.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e instanceof ae&&this.pendingLocalTracks.some(i=>i instanceof ae)&&(!Ct().webAudioMediaStreamDest||e._bypassWebAudio||this.pendingLocalTracks.some(i=>i instanceof ae&&i._bypassWebAudio)))throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(t,e){var i;const n=!y("DISABLE_DUAL_STREAM_USE_ENCODING")&&Ct().supportDualStreamEncoding,r=yr(yr({},{width:160,height:120,framerate:15,bitrate:50}),e);let o;o=n?t._mediaStreamTrack.clone():Xm(t,r);const s=Gt(8,"track-low-"),a=new Yt(o,yr(yr({},n&&{scaleResolutionDownBy:Dm(r,t)}),{},{frameRate:r.framerate,bitrateMax:r.bitrate,bitrateMin:r.bitrate}),void 0,void 0,s);return a.on(ts.TRANSCEIVER_UPDATED,c=>{t._updateRtpTransceiver(c,ua.LOW_STREAM)}),a._hints.push(Vt.LOW_STREAM),G(i=t._hints).call(i,Vt.SCREEN_TRACK)&&a._hints.push(Vt.SCREEN_LOW_TRACK),t.on("sei-to-send",c=>{a.emit("sei-to-send",c)}),t.addListener(J.NEED_CLOSE,()=>{a.close()}),a}globalLock(){return C(this,null,function*(){return this.mutex.lock("From P2PChannel.globalLock")})}reportPCStats(n,r,o){return C(this,arguments,function*(t,e,i){let s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:null;if(this.connection&&this.connection instanceof Cr){var a,c,d,l;const u=this.store.keyMetrics.descriptionStart||0,{iceConnectionState:h,dtlsTransportState:p,peerConnectionState:g}=this.connection,{local:m,remote:f}=yield this.connection.getSelectedCandidatePair();Z.pcStats(this.store.sessionId,{startTime:u,eventElapse:t-u||0,iceconnectionsate:h,dtlsstate:p,connectionstate:g,intSucc:e?1:2,error:this._iceError||s||"",selectedLocalCandidateProtocol:(a=m==null?void 0:m.protocol)!==null&&a!==void 0?a:"",selectedLocalCandidateType:(c=m.candidateType)!==null&&c!==void 0?c:"",selectedLocalCandidateAddress:"".concat(m.address,":").concat(m.port),selectedRemoteCandidateProtocol:(d=f.protocol)!==null&&d!==void 0?d:"",selectedRemoteCandidateType:(l=f.candidateType)!==null&&l!==void 0?l:"",selectedRemoteCandidateAddress:"".concat(f.address,":").concat(f.port),restartCnt:i,preallocation:this.connection.isPreallocation}),this._iceError=null}})}reportVideoFirstFrameDecoded(t,e,i,n){var r;const o=Array.from(Ji(r=this.remoteUserMap).call(r)).find(s=>s._videoSSRC===t);if(o){n||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const s=this.store.keyMetrics,a=s.subscribe.find(c=>c.userId===o.uid&&c.type==="video");Z.firstRemoteVideoDecode(this.store.sessionId,Oe.FIRST_VIDEO_DECODE,Jt.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:e,videoheight:i,subscribeElapse:Je.measureFromSubscribeStart(this.store.clientId,t),subscribeRequestid:t,p2pid:this.store.p2pId,apEnd:s.requestAPEnd||0,apStart:s.requestAPStart||0,joinGwEnd:s.joinGatewayEnd||0,joinGwStart:s.joinGatewayStart||0,pcEnd:s.peerConnectionEnd||0,pcStart:s.peerConnectionStart||0,subscriberEnd:(a==null?void 0:a.subscribeEnd)||0,subscriberStart:(a==null?void 0:a.subscribeStart)||0,videoAddNotify:(a==null?void 0:a.streamAdded)||0,state:n?1:0,firstFrame:(a==null?void 0:a.firstFrame)||0})}}remoteMediaSsrcChanged(t,e,i){return C(this,null,function*(){if(!this.connection)return!1;const n=this.remoteUserMap.get(t);if(!n)return!1;const r=n.get(e);if(!r)return!1;const o=yield this.connection.getRemoteSSRC(r);return o!==void 0&&o!==i})}unbindRtpTransceiver(){this.localTrackMap.size!==0&&Array.from(this.localTrackMap.entries()).forEach(t=>{let[e,{track:i}]=t;e===V.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,ua.LOW_STREAM):i._updateRtpTransceiver(void 0)})}},Q(pt.prototype,"startP2PConnection",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"startP2PConnection"),pt.prototype),Q(pt.prototype,"connect",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"connect"),pt.prototype),Q(pt.prototype,"updateRemoteRTPCapabilities",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"updateRemoteRTPCapabilities"),pt.prototype),Q(pt.prototype,"publishDataChannel",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"publishDataChannel"),pt.prototype),Q(pt.prototype,"unpublish",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"unpublish"),pt.prototype),Q(pt.prototype,"unpublishDataChannel",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"unpublishDataChannel"),pt.prototype),Q(pt.prototype,"unpublishLowStream",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"unpublishLowStream"),pt.prototype),Q(pt.prototype,"subscribeDataChannel",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"subscribeDataChannel"),pt.prototype),Q(pt.prototype,"subscribe",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"subscribe"),pt.prototype),Q(pt.prototype,"massSubscribe",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"massSubscribe"),pt.prototype),Q(pt.prototype,"unsubscribe",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"unsubscribe"),pt.prototype),Q(pt.prototype,"unsubscribeDataChannel",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"unsubscribeDataChannel"),pt.prototype),Q(pt.prototype,"massUnsubscribe",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"massUnsubscribe"),pt.prototype),Q(pt.prototype,"muteRemote",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"muteRemote"),pt.prototype),Q(pt.prototype,"unmuteRemote",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"unmuteRemote"),pt.prototype),Q(pt.prototype,"hasRemoteMediaWithLock",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"hasRemoteMediaWithLock"),pt.prototype),Q(pt.prototype,"disconnectForReconnect",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"disconnectForReconnect"),pt.prototype),Q(pt.prototype,"updateBitrateLimit",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"updateBitrateLimit"),pt.prototype),Q(pt.prototype,"remoteMediaSsrcChanged",[oi],Object.getOwnPropertyDescriptor(pt.prototype,"remoteMediaSsrcChanged"),pt.prototype),pt);function oi(t,e,i){const n=t[e];if(typeof n!="function")throw new Error("Cannot use mutex on object property.");return i.value=function(){return C(this,arguments,function*(){const r=this.mutex,o=yield r.lock("From P2PChannel.".concat(e));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return yield n.apply(this,a)}finally{o()}})},i}function h0(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function p0(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?h0(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):h0(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}const kW=Date.now(),MW=20,Qm=new Map,eh=new Map;function _0(t){return C(this,null,function*(){const e=Qm.get(t),i=Array.isArray(e)&&e[e.length-1],n=eh.get(t);if(!i)return void(n.isSyncing=!1);const r={uid:i.uid,payload:i.payload};n.firstRecvTs===0&&(n.firstRecvTs=i.recvTs,n.firstSendTs=i.sendTs);const o=i.sendTs-n.firstSendTs,s=o-(Date.now()-n.firstRecvTs);s>0&&(n.firstRecvTs=Date.now()-o);let a=i.mediaDelay+s;a<=0?(e.pop(),E0(i.context,r),a=0):a=Math.min(a,MW),setTimeout(()=>e.length&&_0(t),a)})}function E0(t,e){t.safeEmit(_t.STREAM_MESSAGE,e.uid,e.payload),t.onStreamMessage&&t.onStreamMessage(e)}function UW(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=arguments.length>2?arguments[2]:void 0;if(!t.syncWithAudio)return E0(i,{uid:t.uid,payload:t.payload});const n="".concat(i.id,"-").concat(t.uid),r=Qm.get(n)||[],o=r.findIndex(d=>t.sendTs>=d.sendTs),s=p0(p0({},t),{},{context:i,mediaDelay:e,recvTs:Date.now()});o===-1?r.push(s):r.splice(o,0,s),Qm.set(n,r);let a=!1;var c;eh.has(n)?a=!((c=eh.get(n))===null||c===void 0||!c.isSyncing):eh.set(n,{isSyncing:a,firstRecvTs:0,firstSendTs:0}),a||_0(n)}const xW=vt().name;function m0(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function f0(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?m0(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):m0(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}const La="websdk_ng_cache_parameter",VW=y("MAX_PRELOAD_ASYNC_LENGTH"),FW=1e4,ls=new Map,us=[];let Zm=null,$m=0,tf=0;const ih=new Map,BW=function(t,e){const i=[];let n=0;const r=()=>C(this,null,function*(){const o=i.shift();o&&(yield o()),i.length>0&&n<e?r():n--});return function(){return C(this,arguments,function*(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];return new K((c,d)=>C(this,null,function*(){i.push(()=>C(this,null,function*(){try{const l=yield t(...s);c(l)}catch(l){d(l)}})),n<e&&(n++,r())}))})}}(g0,VW),ef=Ti.CancelToken.source();function g0(t,e,i,n,r,o){return C(this,null,function*(){try{if(!y("ENABLE_PRELOAD"))return;if(!Ct().supportWebCrypto)return void _o(()=>{_.warn("Your browser does not support preloading, this feature be run in a secure environment")},"preload_webcrypto_not_supported");if(!i&&i!==null)throw new k(v.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Me(i,"token",1,2047),Me(t,"appid",1,2047),Lu(e),n&&ku(n);const s=Zo();_.debug("preload channel ".concat(e,", uid is ").concat(n));const a={appId:t,cname:e,token:i||t,uid:typeof n!="string"?n:null,sid:s,proxyServer:r};let c,d;typeof n=="string"?(a.stringUid=n,[d,c]=yield K.all([vW(n,{sid:s,appId:t},ef.token),Gw(f0(f0({},a),{},{token:i||t,uid:0}),ef.token)]),a.uid=d.uid,c.gatewayInfo.uid=a.uid,c.gatewayInfo.res.uid=a.uid):(o&&(a.stringUid=o),c=yield Gw(a,ef.token));const l={sid:s,appId:t,cname:e,token:i||t,uid:a.stringUid||n,intUid:a.uid||c.gatewayInfo.uid,stringUid:a.stringUid,ts:Date.now(),sua:d,ap:c};yield function(u){return C(this,null,function*(){let h;try{u.uid&&T0({appId:u.appId,cname:u.cname,token:u.token,uid:u.uid,stringUid:u.stringUid});const p=y0(u),g=yield function(f,T){return C(this,null,function*(){try{const R=yield window.crypto.subtle.importKey("raw",hI(T),"AES-GCM",!1,["encrypt"]),A=yield window.crypto.subtle.encrypt({name:"AES-GCM",iv:new Uint8Array(1)},R,Qo(window.btoa(JSON.stringify(f))));return Eo(new Uint8Array(A))}catch(R){return}})}(u,u.token||u.appId);if(!g)return;h=C0(La);const m=h?JSON.parse(h):[];m.push({[p]:g}),m.length>y("AP_CACHE_NUM")&&m.shift(),nh(La,JSON.stringify(m))}catch(p){_.warn("Error caching server parameters:",p.message),nh(La,"")}})}(l),$m++}catch(s){throw tf++,function(a){Zm||(Zm=window.setTimeout(()=>{let d="";ih.forEach((l,u)=>{d+="".concat(u,": ").concat(l," ;")}),Z.reportApiInvoke(null,{name:_e.PRELOAD,options:{success:$m,failed:tf,err:d}}).onError(a),$m=0,tf=0,ih.clear(),Zm=null},FW));const c=ih.get(a.code)||0;ih.set(a.code,c+1)}(s),s}})}function S0(t){return C(this,null,function*(){try{if(y("AP_REQUEST_DETAIL")||y("ENABLE_ROLE_SELECT_EDGE"))return;const e=T0(t);if(!e||t.cloudProxyServer!=="disabled")return;const i=yield function(n,r){return C(this,null,function*(){try{const o=yield window.crypto.subtle.importKey("raw",hI(r),"AES-GCM",!1,["decrypt"]),s=yield window.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(1)},o,Qo(n));return JSON.parse(window.atob(Eo(new Uint8Array(s))))}catch(o){return}})}(e,t.token||t.appId);if(!i||!function(n,r){return n.cname===r.cname&&n.appId===r.appId&&n.token===r.token?r.stringUid?n.stringUid===r.stringUid:typeof r.uid=="number"?n.uid===r.uid:n.uid==r.uid:!1}(i,t))return;if(i&&Date.now()-i.ts<y("AP_CACHE_LIFETIME"))return i}catch(e){_.warn("Error get preloadInfo",e.message)}})}function T0(t){let e;try{if(e=C0(La),!e)return;const i=JSON.parse(e),n=y0(t),r=function(s,a){for(let c=s.length-1;c>=0;c--)if(a(s[c]))return c;return-1}(i,s=>n in s);if(r===-1)return;const o=i.splice(r,1)[0];return nh(La,JSON.stringify(i)),o[n]}catch(i){_.warn("Error delete preload info: ".concat(e),i.message),nh(La,"")}}function nf(t){if(t){let e=ls.get(t);e&&(window.clearTimeout(e),e=null,ls.delete(t)),G(us).call(us,t)||t.cloudProxyServer!=="disabled"||us.push(t)}if(ls.size<y("AP_CACHE_NUM")&&us.length>0){const e=us.shift();ls.set(e,window.setTimeout(()=>C(this,null,function*(){const{appId:i,cname:n,token:r,stringUid:o,uid:s,proxyServer:a}=e;try{yield BW(i,n,r,s,a,o),ls.has(e)&&nf(e)}catch(c){_.warn("update preload failed",c.message),R0(e)}}),y("AP_UPDATE_INTERVAL")))}}function R0(t){const e=us.indexOf(t);e!==-1&&us.splice(e,1);let i=ls.get(t);i&&(window.clearTimeout(i),i=null,ls.delete(t),nf())}function v0(t,e){const i=t.sua,n=t.ap;e&&i&&Z.reqUserAccount(t.sid,{lts:i.requestTime,elapse:i.elapse,success:!0,serverAddr:i.url,stringUid:e,uid:t.intUid,errorCode:null,extend:i.req}),Z.reportResourceTiming(t.ap.url,t.sid),Z.joinWebProxyAP(t.sid,{lts:n.requestTime,elapse:n.elapse,sucess:1,apServerAddr:n.url,turnServerAddrList:n.proxyInfo.addresses.map(r=>r.ip).join(","),eventType:"disabled",unilbsServerIds:[me.CHOOSE_SERVER,me.CLOUD_PROXY_FALLBACK].toString()}),Z.joinChooseServer(t.sid,{lts:n.requestTime,elapse:n.elapse,succ:!0,csAddr:n.url,opid:n.opid,serverList:n.gatewayInfo.gatewayAddrs.map(r=>r.address),ec:null,cid:n.gatewayInfo.cid.toString(),uid:n.gatewayInfo.uid.toString(),csIp:n.gatewayInfo.csIp,unilbsServerIds:[me.CHOOSE_SERVER].toString(),isHttp3:n.isHttp3})}function C0(t){return window.atob(window.localStorage.getItem(t)||"")}function nh(t,e){window.localStorage.setItem(t,window.btoa(e))}function y0(t){let e="".concat(t.appId,"_").concat(t.cname);return typeof t.uid=="string"&&(e+="_s_".concat(t.uid)),typeof t.uid=="number"&&(e+="_".concat(t.uid)),t.token&&(e+="_".concat(t.token)),SI(e)}function jW(t){let e=function(){const i=HW.pop();return i?(i.offset=i.limit=0,i):{bytes:new Uint8Array(64),offset:0,limit:0}}();return function(i,n){let r=i.appId;r!==void 0&&(fe(n,10),Io(n,r));let o=i.cid;o!==void 0&&(fe(n,16),fe(n,o));let s=i.cname;s!==void 0&&(fe(n,26),Io(n,s));let a=i.deviceId;a!==void 0&&(fe(n,34),Io(n,a));let c=i.elapse;c!==void 0&&(fe(n,40),Ao(n,c));let d=i.fileSize;d!==void 0&&(fe(n,48),Ao(n,ka(d)));let l=i.height;l!==void 0&&(fe(n,56),Ao(n,ka(l)));let u=i.jpg;u!==void 0&&(fe(n,66),fe(n,u.length),A0(n,u));let h=i.networkType;h!==void 0&&(fe(n,72),Ao(n,ka(h)));let p=i.osType;p!==void 0&&(fe(n,80),Ao(n,ka(p)));let g=i.requestId;g!==void 0&&(fe(n,90),Io(n,g));let m=i.sdkVersion;m!==void 0&&(fe(n,98),Io(n,m));let f=i.sequence;f!==void 0&&(fe(n,104),Ao(n,ka(f)));let T=i.sid;T!==void 0&&(fe(n,114),Io(n,T));let R=i.timestamp;R!==void 0&&(fe(n,120),Ao(n,R));let A=i.uid;A!==void 0&&(fe(n,128),fe(n,A));let N=i.vid;N!==void 0&&(fe(n,136),fe(n,N));let O=i.width;O!==void 0&&(fe(n,144),Ao(n,ka(O)));let w=i.service;w!==void 0&&(fe(n,152),fe(n,w));let L=i.callbackData;L!==void 0&&(fe(n,162),fe(n,L.length),A0(n,L));let M=i.ticket;M!==void 0&&(fe(n,170),Io(n,M));let j=i.vendorConfigs;j!==void 0&&(fe(n,178),Io(n,j))}(t,e),function(i){let n=i.bytes,r=i.limit;return n.length===r?n:n.subarray(0,r)}(e)}function GW(t){return function(i){let n={};t:for(;!KW(i);){let r=$c(i);switch(r>>>3){case 0:break t;case 1:n.code=$c(i);break;case 2:n.msg=b0(i,$c(i));break;case 3:n.requestId=b0(i,$c(i));break;case 4:n.timestamp=YW(i,!1);break;default:WW(i,7&r)}}return n}({bytes:e=t,offset:0,limit:e.length});var e}function WW(t,e){switch(e){case 0:for(;128&Un(t););break;case 2:rf(t,$c(t));break;case 5:rf(t,4);break;case 1:rf(t,8);break;default:throw new Error("Unimplemented type: "+e)}}function ka(t){return{low:t|=0,high:t>>31,unsigned:t>=0}}let HW=[];function rf(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function KW(t){return t.offset>=t.limit}function rh(t,e){let i=t.bytes,n=t.offset,r=t.limit,o=n+e;if(o>i.length){let s=new Uint8Array(2*o);s.set(i),t.bytes=s}return t.offset=o,o>r&&(t.limit=o),n}function I0(t,e){let i=t.offset;if(i+e>t.limit)throw new Error("Read past limit");return t.offset+=e,i}function A0(t,e){let i=rh(t,e.length);t.bytes.set(e,i)}function b0(t,e){let i=I0(t,e),n=String.fromCharCode,r=t.bytes,o="<22>",s="";for(let a=0;a<e;a++){let c,d,l,u,h=r[a+i];128&h?(224&h)==192?a+1>=e?s+=o:(c=r[a+i+1],(192&c)!=128?s+=o:(u=(31&h)<<6|63&c,u<128?s+=o:(s+=n(u),a++))):(240&h)==224?a+2>=e?s+=o:(c=r[a+i+1],d=r[a+i+2],(49344&(c|d<<8))!=32896?s+=o:(u=(15&h)<<12|(63&c)<<6|63&d,u<2048||u>=55296&&u<=57343?s+=o:(s+=n(u),a+=2))):(248&h)==240?a+3>=e?s+=o:(c=r[a+i+1],d=r[a+i+2],l=r[a+i+3],(12632256&(c|d<<8|l<<16))!=8421504?s+=o:(u=(7&h)<<18|(63&c)<<12|(63&d)<<6|63&l,u<65536||u>1114111?s+=o:(u-=65536,s+=n(55296+(u>>10),56320+(1023&u)),a+=3))):s+=o:s+=n(h)}return s}function Io(t,e){let i=e.length,n=0;for(let s=0;s<i;s++){let a=e.charCodeAt(s);a>=55296&&a<=56319&&s+1<i&&(a=(a<<10)+e.charCodeAt(++s)-56613888),n+=a<128?1:a<2048?2:a<65536?3:4}fe(t,n);let r=rh(t,n),o=t.bytes;for(let s=0;s<i;s++){let a=e.charCodeAt(s);a>=55296&&a<=56319&&s+1<i&&(a=(a<<10)+e.charCodeAt(++s)-56613888),a<128?o[r++]=a:(a<2048?o[r++]=a>>6&31|192:(a<65536?o[r++]=a>>12&15|224:(o[r++]=a>>18&7|240,o[r++]=a>>12&63|128),o[r++]=a>>6&63|128),o[r++]=63&a|128)}}function Un(t){return t.bytes[I0(t,1)]}function w0(t,e){let i=rh(t,1);t.bytes[i]=e}function $c(t){let e,i=0,n=0;do e=Un(t),i<32&&(n|=(127&e)<<i),i+=7;while(128&e);return n}function fe(t,e){for(e>>>=0;e>=128;)w0(t,127&e|128),e>>>=7;w0(t,e)}function YW(t,e){let i,n=0,r=0,o=0;return i=Un(t),n=127&i,128&i&&(i=Un(t),n|=(127&i)<<7,128&i&&(i=Un(t),n|=(127&i)<<14,128&i&&(i=Un(t),n|=(127&i)<<21,128&i&&(i=Un(t),r=127&i,128&i&&(i=Un(t),r|=(127&i)<<7,128&i&&(i=Un(t),r|=(127&i)<<14,128&i&&(i=Un(t),r|=(127&i)<<21,128&i&&(i=Un(t),o=127&i,128&i&&(i=Un(t),o|=(127&i)<<7))))))))),{low:n|r<<28,high:r>>>4|o<<24,unsigned:e}}function Ao(t,e){let i=e.low>>>0,n=(e.low>>>28|e.high<<4)>>>0,r=e.high>>>24,o=r===0?n===0?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=rh(t,o),a=t.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=o!==9?128|r:127&r;case 8:a[s+7]=o!==8?n>>>21|128:n>>>21&127;case 7:a[s+6]=o!==7?n>>>14|128:n>>>14&127;case 6:a[s+5]=o!==6?n>>>7|128:n>>>7&127;case 5:a[s+4]=o!==5?128|n:127&n;case 4:a[s+3]=o!==4?i>>>21|128:i>>>21&127;case 3:a[s+2]=o!==3?i>>>14|128:i>>>14&127;case 2:a[s+1]=o!==2?i>>>7|128:i>>>7&127;case 1:a[s]=o!==1?128|i:127&i}}const O0={},N0={},oh=4294967296,qW=oh*oh,D0=qW/2;L0(0,!0);const P0=L0(0),zW=td(0,-2147483648,!1),XW=td(-1,2147483647,!1);function L0(t,e){let i,n,r;return e?(r=0<=(t>>>=0)&&t<256)&&(n=N0[t],n)?n:(i=td(t,0,!0),r&&(N0[t]=i),i):(r=-128<=(t|=0)&&t<128)&&(n=O0[t],n)?n:(i=td(t,t<0?-1:0,!1),r&&(O0[t]=i),i)}function td(t,e,i){return{low:0|t,high:0|e,unsigned:!!i}}function k0(t,e){if(isNaN(t))return P0;{if(t<=-D0)return zW;if(t+1>=D0)return XW}return t<0?P0:td(t%oh|0,t/oh|0,e)}function M0(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}class of extends $t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const i=this._connectionState;this._connectionState=e,this.emit(tr.CONNECTION_STATE_CHANGE,e,i)}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 i;super(),S(this,"name","AgoraRTCImageModeration"),S(this,"_connectionState",hn.CONNECTING),S(this,"_sequence",0),S(this,"_moderationStartTime",void 0),S(this,"_workerConnection",void 0),S(this,"_workerMessageLengthLimit",void 0),S(this,"_qualityRatio",void 0),S(this,"_connectInfo",void 0),S(this,"_cancelTokenSource",Ti.CancelToken.source()),S(this,"_retryConfig",void 0),S(this,"_moderationInterval",void 0),S(this,"_moderationTimer",null),S(this,"_moderationMode",1),S(this,"_quality",1),S(this,"_qualityTimer",null),S(this,"_ticket",void 0),S(this,"_moderationIntervalMinimum",void 0),S(this,"_uploadFailedNum",0),S(this,"_uploadNum",0),S(this,"_uploadTimer",null),S(this,"_extraInfo",void 0),S(this,"_vendor",""),S(this,"_encoder",new TextEncoder),S(this,"_moderationId",void 0),S(this,"inspectImage",()=>{if(this.connectionState!==hn.CONNECTED)throw new P(v.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===hn.CONNECTED?this.requestToInspectImage():_.debug("[".concat(this._moderationId,"] Moderation State is not connected , "),this.connectionState)},this._moderationInterval<this._moderationIntervalMinimum?this._moderationIntervalMinimum:this._moderationInterval),this.requestToInspectImage()}),this._moderationId=Gt(5,"image-moderation-"),this._workerMessageLengthLimit=y("IMAGE_MODERATION_WORKER_MESSAGE_LENGTH_LIMIT"),this._moderationIntervalMinimum=y("IMAGE_MODERATION_INTERVAL_MINIMUM"),this._moderationInterval=(i=e.interval)!==null&&i!==void 0?i:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),this._qualityRatio=y("IMAGE_MODERATION_QUALITY_RATIO"),this._moderationStartTime=Number(Date.now()),this._workerConnection=new Gc("worker-"+this._moderationId,ge),this.on(tr.STATE_CHANGE,(n,r)=>{_.debug("[".concat(this._moderationId,"] Moderation operation :").concat(Ca[n]," ").concat(r||""))}),this.handleWorkerEvents()}init(e,i){return C(this,null,function*(){this.emit(tr.STATE_CHANGE,Ca.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=i,new K((r,o)=>{this.on(tr.CONNECTION_STATE_CHANGE,(s,a)=>{s===hn.CONNECTED&&r()}),this.requestAP(e,n,i).then(s=>{this.connectWorker(s)}).catch(s=>{o(s)})})})}updateConfig(e){var i;this._moderationInterval=(i=e.interval)!==null&&i!==void 0?i:1e3,e.extraInfo&&(this._extraInfo=this._encoder.encode(e.extraInfo)),e.vendor&&(this._vendor=e.vendor),_.debug("[".concat(this._moderationId,"] updateConfig: ").concat(JSON.stringify(e))),this.connectionState===hn.CONNECTED&&this.inspectImage()}requestAP(e,i,n){return C(this,null,function*(){const r=y("WEBCS_DOMAIN").map(c=>"https://".concat(c,"/api/v1")),o=yield function(c,d,l,u){let{appId:h,areaCode:p,cname:g,sid:m,token:f,uid:T}=d;Oa++;const R="moderation_plugin",A={service_name:R,json_body:JSON.stringify({appId:h,areaCode:p,cname:g,command:"allocateEdge",requestId:Oa,seq:Oa,sid:m,appToken:f,ts:Date.now(),uid:T+""})};let N,O,w=c[0];return Jn(()=>C(this,null,function*(){N=Date.now();const L=yield er(w,{data:A,cancelToken:l,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(O=Date.now()-N,L.code!==0){const H=new P(v.UNEXPECTED_RESPONSE,"moderation plugin ap error, code"+L.code,{retry:!0,responseTime:O});throw _.error(H.toString()),H}const M=JSON.parse(L.json_body);if(M.code!==200){const H=new P(v.UNEXPECTED_RESPONSE,"moderation plugin ap error, code: ".concat(M.code,", reason: ").concat(M.reason),{code:M.code,responseTime:O});throw _.error(H.toString()),H}if(!M.servers||!Array.isArray(M.servers)||M.servers.length===0){const H=new P(v.UNEXPECTED_RESPONSE,"moderation plugin ap empty server",{code:M.code,responseTime:O});throw _.error(H.toString()),H}if(!M.servers.some(H=>!!H.wss)){const H=new P(v.UNEXPECTED_RESPONSE,"moderation plugin ap empty port",{code:M.code,responseTime:O});throw _.error(H.toString()),H}const j=y("IMAGE_MODERATION_WORKER_HOST");return{addressList:M.servers.map(H=>{let{address:ht,wss:lt}=H;if(ht&&lt)return"wss://".concat(ht.replace(/\./g,"-"),".").concat(j,":").concat(lt,"/moderation")}).filter(H=>!!H),workerToken:M.workerToken,vid:M.vid,ticket:M.appTicket,responseTime:O}}),(L,M)=>(Z.apworkerEvent(m,{success:!0,sc:200,serviceName:R,responseDetail:JSON.stringify(L.addressList),firstSuccess:M===0,responseTime:O,serverIp:c[M%c.length]}),!1),(L,M)=>(Z.apworkerEvent(m,{success:!1,sc:L.data&&L.data.code||200,serviceName:R,responseTime:O,serverIp:c[M%c.length]}),!!(L.code!==v.OPERATION_ABORTED&&L.code!==v.UNEXPECTED_RESPONSE||L.data&&L.data.retry)&&(w=c[(M+1)%c.length],!0)),u)}(r,e,i,n);this.emit(tr.STATE_CHANGE,Ca.AP_CONNECTED);const{addressList:s,ticket:a}=o;return this._ticket=a,s})}connectWorker(e){return C(this,null,function*(){this.emit(tr.STATE_CHANGE,Ca.CONNECT_WORKER),yield this._workerConnection.init(e,1e4)})}handleWorkerEvents(){this._workerConnection.on(dt.CONNECTED,()=>C(this,null,function*(){this.emit(tr.STATE_CHANGE,Ca.WORKER_CONNECTED,this._workerConnection.url),this.connectionState=hn.CONNECTED})),this._workerConnection.on(dt.CLOSED,()=>{this.connectionState=hn.CLOSED}),this._workerConnection.on(dt.FAILED,()=>{this.connectionState=hn.CLOSED}),this._workerConnection.on(dt.RECONNECTING,()=>{this.connectionState=this.connectionState===hn.CONNECTED?hn.RECONNECTING:hn.CONNECTING}),this._workerConnection.on(dt.ON_MESSAGE,e=>C(this,null,function*(){if(e.data instanceof ArrayBuffer){const i=GW(new Uint8Array(e.data));y("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&_.debug("[".concat(this._moderationId,"] Response message for worker of image moderation "),JSON.stringify(i)),this._uploadNum++,i.code===void 0||i.code===0||(this._uploadFailedNum++,_.error("[".concat(this._moderationId,"] Error response from worke, code is ").concat(i.code,", msg is ").concat(i.msg)),this._uploadTimer||(this._uploadTimer=window.setTimeout(()=>{Z.reportApiInvoke(this._connectInfo.sid||null,{name:_e.IMAGE_MODERATION_UPLOAD,options:[this._uploadFailedNum,this._uploadNum,i.code],tag:oe.TRACER}).onError(new P(v.IMAGE_MODERATION_UPLOAD_FAILED,i.msg)),this._uploadTimer=null},y("IMAGE_MODERATION_UPLOAD_REPORT_INTERVAL"))))}else _.error("[".concat(this._moderationId,"] Unexpected message type from worker"))})),this._workerConnection.on(dt.WILL_RECONNECT,(e,i,n)=>{e==="recover"&&n(e),n("tryNext")}),this._workerConnection.on(dt.REQUEST_NEW_URLS,(e,i)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(i)})}static intToLong(e){return{low:e|=0,high:e>>31,unsigned:e>=0}}requestToInspectImage(){return C(this,null,function*(){const e=zi(this,tr.CLIENT_LOCAL_VIDEO_TRACK),i={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(y("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&_.debug("Only the track being played can be inspected"));this._sequence++;const n=yield this.generateRequestData(e,i);this._workerConnection.sendMessage(n,!0,!0)}else y("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")&&_.debug("Only the track being published can be inspected")})}generateRequestData(e,i){return C(this,null,function*(){let{appId:n,cname:r,cid:o,vid:s,sid:a,uid:c}=i;const d=Date.now(),l=yield e.getCurrentFrameImage("image/jpeg",this.quality),u=yield cA(l,n,r),h=this._sequence+"-"+o+"-"+c+"-"+d+"-"+Gt(12,""),p={appId:n,cid:o,cname:r,deviceId:"",elapse:of.intToLong(Number(d-this._moderationStartTime)),fileSize:l.buffer.byteLength,height:l.height,width:l.width,jpg:u,networkType:6,osType:7,requestId:h,sdkVersion:"4.23.4",sequence:this._sequence,sid:a,timestamp:k0(d),uid:c,vid:s,service:this._moderationMode,ticket:this._ticket,callbackData:this._extraInfo,vendorConfigs:this._vendor};this._extraInfo===void 0&&delete p.callbackData;const g=jW(p);if(g.byteLength<this._workerMessageLengthLimit){if(y("SHOW_IMAGE_MODERATION_WORKER_MESSAGE")){const m=function(f){for(var T=1;T<arguments.length;T++){var R=arguments[T]!=null?arguments[T]:{};T%2?M0(Object(R),!0).forEach(function(A){S(f,A,R[A])}):Object.getOwnPropertyDescriptors?Object.defineProperties(f,Object.getOwnPropertyDescriptors(R)):M0(Object(R)).forEach(function(A){Object.defineProperty(f,A,Object.getOwnPropertyDescriptor(R,A))})}return f}({},p);delete m.jpg,_.debug("[".concat(this._moderationId,"] Request message for worker of image moderation service: "),JSON.stringify(m))}return g}{const m=this.quality*this._qualityRatio;return this.quality=m,yield this.generateRequestData(e,{appId:n,cname:r,cid:o,vid:s,sid:a,uid:c})}})}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=Ti.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=hn.CLOSED,this.emit(tr.STATE_CHANGE,Ca.CLOSED)}}function U0(t){if(xt(t.interval,"interval",1e3,1/0),t&&t.extraInfo&&t.extraInfo.length>1024)throw new P(v.INVALID_PARAMS,"config.extraInfo length cannot exceed 1024 bytes");if(t&&t.vendor&&t.vendor.length>1024)throw new P(v.INVALID_PARAMS,"config.vendor length cannot exceed 1024 bytes")}const JW={name:"ImageModeration",create:function(t){let{config:e}=t;return U0(e),new of(e)}};var x0,V0,F0,B0,j0,G0,W0,H0,K0,Y0,q0,z0,X0,J0,Q0,Z0,$0,tO,eO,iO,nO,rO,oO,sO,aO,cO,dO,lO,uO,hO,pO,_O,EO,mO,fO,gO,SO,TO,RO,vO,CO,Y;function yO(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function xn(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?yO(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):yO(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}qe.setLogger(_);let QW=(x0=it(),V0=it({argsMap:(t,e)=>{if(!Array.isArray(e)){if(!(e instanceof Ea))return[e];e=[e]}return e.map(i=>i?Object(i).toString():"null")}}),F0=it({argsMap:(t,e)=>(e||(e=[]),Array.isArray(e)||e.trackMediaType!==_a.DATA?(Array.isArray(e)||(e=[e]),e.map(i=>i.getTrackId())):[e.getChannelId()])}),B0=it({argsMap:(t,e,i,n)=>[typeof e=="object"?e.uid:e,i,n]}),j0=it({argsMap:(t,e,i)=>[e,i]}),G0=it({argsMap:(t,e)=>e.map(i=>{let{user:n,mediaType:r}=i;return[n==null?void 0:n.uid,r]})}),W0=it({argsMap:(t,e,i,n)=>[typeof e=="object"?e.uid:e,i,n]}),H0=it({argsMap:(t,e)=>e.map(i=>{let{user:n,mediaType:r}=i;return{uid:n==null?void 0:n.uid,mediaType:r}})}),K0=it(),Y0=it(),q0=it(),z0=it(),X0=it(),J0=it(),Q0=it(),Z0=it(),$0=it(),tO=it(),eO=it(),iO=it(),nO=it(),rO=it(),oO=it(),sO=it({argsMap:(t,e)=>[e]}),aO=it(),cO=it(),dO=it(),lO=it(),uO=it(),hO=it(),pO=it(),_O=it(),EO=it({argsMap:(t,e)=>(Array.isArray(e)||(e=[e]),[JSON.stringify(e)])}),mO=it(),fO=it(),gO=it(),SO=it(),TO=it(),RO=it(),vO=it({reportResult:!0}),CO=it(),Y=class extends $t{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 t;return((t=this._config)===null||t===void 0?void 0:t.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(t,e){let i;if(super(),S(this,"store",void 0),S(this,"_uid",void 0),S(this,"_channelName",void 0),S(this,"_uintUid",void 0),S(this,"_users",[]),S(this,"_config",void 0),S(this,"_clientId",void 0),S(this,"_appId",void 0),S(this,"_sessionId",null),S(this,"_key",void 0),S(this,"_rtmConfig",{}),S(this,"_joinInfo",void 0),S(this,"_gateway",void 0),S(this,"_statsCollector",void 0),S(this,"_configDistribute",void 0),S(this,"_leaveMutex",void 0),S(this,"_publishMutex",void 0),S(this,"_renewTokenMutex",void 0),S(this,"_subscribeMutex",void 0),S(this,"_encryptionMode","none"),S(this,"_encryptionSecret",null),S(this,"_encryptionSalt",null),S(this,"_encryptDataStream",!1),S(this,"_encryptDataStreamKey",null),S(this,"_encryptDataStreamIv",null),S(this,"_proxyServer",void 0),S(this,"_turnServer",{servers:[],mode:"auto"}),S(this,"_cloudProxyServerMode","disabled"),S(this,"_isDualStreamEnabled",!1),S(this,"_defaultStreamFallbackType",void 0),S(this,"_lowStreamParameter",void 0),S(this,"_streamFallbackTypeCacheMap",new Map),S(this,"_remoteStreamTypeCacheMap",new Map),S(this,"_axiosCancelSource",Ti.CancelToken.source()),S(this,"_audioVolumeIndicationInterval",void 0),S(this,"_networkQualityInterval",void 0),S(this,"_userOfflineTimeout",void 0),S(this,"_streamRemovedTimeout",void 0),S(this,"_liveTranscodeStreamingClient",void 0),S(this,"_liveRawStreamingClient",void 0),S(this,"_channelMediaRelayClient",void 0),S(this,"_networkQualitySensitivity","normal"),S(this,"_p2pChannel",void 0),S(this,"_useLocalAccessPoint",!1),S(this,"_setLocalAPVersion",void 0),S(this,"_joinAndNotLeaveYet",!1),S(this,"_numberOfJoinCount",0),S(this,"_remoteDefaultVideoStreamType",void 0),S(this,"_inspect",void 0),S(this,"_moderation",void 0),S(this,"_license",void 0),S(this,"_pendingPublishedUsers",[]),S(this,"ntpAlignErrorCount",0),S(this,"remoteInboundOffset",0),S(this,"_peerConnectionState",void 0),S(this,"_handleLocalTrackEnable",(r,o,s)=>{this.publish(r,!1).then(o).catch(s)}),S(this,"_handleLocalTrackDisable",(r,o,s)=>{this.unpublish(r).then(o).catch(s)}),S(this,"_handleUserOnline",r=>{if(y("BLOCK_LOCAL_CLIENT")&&ss(r.uid,this.channelName))return void _.debug("[".concat(r.uid,"] will be ignored in local"));this.isStringUID&&typeof r.uid!="string"&&_.error("[".concat(this._clientId,"] StringUID is Mixed with UintUID"));const o=this._users.find(s=>s.uid===r.uid);if(o)o._trust_in_room_=!0,o._is_pre_created&&(o._is_pre_created=!1,this.safeEmit(_t.USER_JOINED,o));else{const s=new Co(r.uid,r.uint_id||r.uid);this._users.push(s),_.debug("[".concat(this._clientId,"] user online"),r.uid),this.safeEmit(_t.USER_JOINED,s)}}),S(this,"_handleUserOffline",r=>{if(y("BLOCK_LOCAL_CLIENT")&&ss(r.uid,this.channelName))return;const o=this._users.find(s=>s.uid===r.uid);o&&(this._handleRemoveStream(r),this._handleRemoveDataChannels(r),o._audio_pre_subscribed||o._video_pre_subscribed?o._is_pre_created=!0:cu(this._users,o),this._remoteStreamTypeCacheMap.delete(o.uid),this._streamFallbackTypeCacheMap.delete(o.uid),_.debug("[".concat(this._clientId,"] user offline"),r.uid,"reason:",r.reason),this.safeEmit(_t.USER_LEAVED,o,r.reason))}),S(this,"_handleAddAudioOrVideoStream",(r,o,s,a,c,d,l)=>{if(y("BLOCK_LOCAL_CLIENT")&&ss(o,this.channelName))return;const u=this._users.find(p=>p.uid===o);if(!u)return void _.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));_.debug("[".concat(this._clientId,"] stream added with uid ").concat(o,", type ").concat(r)),this.store.subscribe(u.uid,r,void 0,void 0,void 0,Date.now());const h=r==="audio"?u.hasAudio:u.hasVideo;u._uintid||(u._uintid=c||o),r==="audio"?u._trust_audio_stream_added_state_=!0:u._trust_video_stream_added_state_=!0,r==="audio"?(u._audio_added_=!0,s!==void 0&&(u._audioSSRC=s),a!==void 0&&(u._cname=a),d&&(u._audioOrtc=d)):(u._video_added_=!0,s!==void 0&&(u._videoSSRC=s),a!==void 0&&(u._cname=a),l!==void 0&&(u._rtxSsrcId=l),d&&(u._videoOrtc=d)),(r==="audio"?u.hasAudio:u.hasVideo)&&!h&&(_.info("[".concat(this._clientId,"] remote user ").concat(u.uid," published ").concat(r)),this.safeEmit(_t.USER_PUBLISHED,u,r)),r==="video"?Z.onGatewayStream(this._sessionId,Oe.ON_ADD_VIDEO_STREAM,Jt.ON_ADD_VIDEO_STREAM,{peer:c||o,ssrc:u._videoSSRC}):Z.onGatewayStream(this._sessionId,Oe.ON_ADD_AUDIO_STREAM,Jt.ON_ADD_AUDIO_STREAM,{peer:c||o,ssrc:u._audioSSRC}),this._p2pChannel.remoteMediaSsrcChanged(u,r,s).then(p=>{if(p&&(_.debug("[".concat(this._clientId,"] resubscribe ").concat(r," for user ").concat(u.uid," after rejoin because SSRC id changed.")),this._p2pChannel instanceof Zc))return this._p2pChannel.unsubscribe(u,r,!0).then(()=>this._subscribe(u,r,!0).catch(g=>{_.error("[".concat(this._clientId,"] resubscribe error"),g.toString())}))}),this._p2pChannel.hasPendingRemoteMedia(u,r)&&(_.debug("[".concat(this._clientId,"] resubscribe ").concat(r," for user ").concat(u.uid," after reconnect.")),this._subscribe(u,r,!0).catch(p=>{_.error("[".concat(this._clientId,"] resubscribe error"),p.toString())}))}),S(this,"_handleRemoveStream",r=>{if(y("BLOCK_LOCAL_CLIENT")&&ss(r.uid,this.channelName))return;const o=this._users.find(a=>a.uid===r.uid);if(!o)return void _.warning("[".concat(this._clientId,"] can not find target user!(on_remove_stream)"));_.debug("[".concat(this._clientId,"] stream removed with uid ").concat(r.uid));let s=()=>{};o.hasAudio&&o.hasVideo?s=()=>{_.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished audio track")),this.safeEmit(_t.USER_UNPUBLISHED,o,"audio"),_.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished video track")),this.safeEmit(_t.USER_UNPUBLISHED,o,"video")}:o.hasVideo?s=()=>{_.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished video track")),this.safeEmit(_t.USER_UNPUBLISHED,o,"video")}:o.hasAudio&&(s=()=>{_.info("[".concat(this._clientId,"] remote user ").concat(o.uid," unpublished audio track")),this.safeEmit(_t.USER_UNPUBLISHED,o,"audio")}),o._video_pre_subscribed||o._audio_pre_subscribed||(o._trust_audio_stream_added_state_=!0,o._trust_video_stream_added_state_=!0,o._audio_added_=!1,o._video_added_=!1,this._p2pChannel instanceof Zc&&this._p2pChannel.unsubscribe(o).then(a=>{if(a)return this._gateway.unsubscribe(a,o.uid)}),o._audioSSRC=void 0,o._videoSSRC=void 0,o._audioOrtc=void 0,o._videoOrtc=void 0,o._rtxSsrcId=void 0),Z.onGatewayStream(this._sessionId,Oe.ON_REMOVE_STREAM,Jt.ON_REMOVE_STREAM,{peer:r.uint_id||r.uid}),s()}),S(this,"_handleSetStreamLocalEnable",(r,o,s)=>{if(y("BLOCK_LOCAL_CLIENT")&&ss(o,this.channelName))return;const a=this._users.find(l=>l.uid===o);if(!a)return void _.error("[".concat(this._clientId,"] can not find target user!(disable_local)"));_.debug("[".concat(this._clientId,"] local ").concat(r," ").concat(s?"enabled":"disabled"," with uid ").concat(o));const c=r==="audio"?a.hasAudio:a.hasVideo;if(r==="audio"){a._trust_audio_enabled_state_=!0;const l=a._audio_enabled_;if(a._audio_enabled_=s,a._audio_enabled_===l)return;{const u=a._audio_enabled_?"enable-local-audio":"disable-local-audio";_.debug("[".concat(this._clientId,"] user-info-updated, uid: ").concat(o,", msg: ").concat(u)),this.safeEmit(_t.USER_INFO_UPDATED,o,u)}}else{a._trust_video_enabled_state_=!0;const l=a._video_enabled_;if(a._video_enabled_=s,a._video_enabled_===l)return;{const u=a._video_enabled_?"enable-local-video":"disable-local-video";_.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(o,", msg: ").concat(u)),this.safeEmit(_t.USER_INFO_UPDATED,o,u)}}const d=r==="audio"?a.hasAudio:a.hasVideo;return c!==d?!c&&d?(_.info("[".concat(this._clientId,"] remote user ").concat(o," published ").concat(r)),void this.safeEmit(_t.USER_PUBLISHED,a,r)):(r==="video"&&a._videoTrack&&a._videoTrack._destroy(),r==="audio"&&a._audioTrack,this._p2pChannel.muteRemote(a,r),_.info("[".concat(this._clientId,"] remote user ").concat(o," unpublished ").concat(r)),void this.safeEmit(_t.USER_UNPUBLISHED,a,r)):void 0}),S(this,"_handleMuteStream",(r,o,s)=>{if(y("BLOCK_LOCAL_CLIENT")&&ss(r,this.channelName))return;_.debug("[".concat(this._clientId,"] receive mute message"),r,o,s);const a=this._users.find(l=>l.uid===r);if(!a)return void _.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r));const c=o==="audio"?a.hasAudio:a.hasVideo;if(o==="audio"){a._trust_audio_mute_state_=!0;const l=a._audio_muted_;if(a._audio_muted_=s,a._audio_muted_===l)return;{const u=a._audio_muted_?"mute-audio":"unmute-audio";_.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(r,", msg: ").concat(u)),this.safeEmit(_t.USER_INFO_UPDATED,r,u)}}else{a._trust_video_mute_state_=!0;const l=a._video_muted_;if(a._video_muted_=s,a._video_muted_===l)return;{const u=a._video_muted_?"mute-video":"unmute-video";_.debug("[".concat(this._clientId,"] user-info-update, uid: ").concat(r,", msg: ").concat(u)),this.safeEmit(_t.USER_INFO_UPDATED,r,u)}}const d=o==="audio"?a.hasAudio:a.hasVideo;if(c!==d){if(!c&&d)return(o==="audio"?a._audioSSRC:a._videoSSRC)?(_.info("[".concat(this._clientId,"] remote user ").concat(r," published ").concat(o)),void this.safeEmit(_t.USER_PUBLISHED,a,o)):void _.warning("[".concat(this._clientId,"] remote user ").concat(r," receive ").concat(o," unmute message before add stream message, ").concat(o," SSRC doesn't exist yet."));o==="video"&&a._videoTrack&&!a._video_pre_subscribed&&a._videoTrack._destroy(),o==="audio"&&a._audioTrack,this._p2pChannel.muteRemote(a,o),_.info("[".concat(this._clientId,"] remote user ").concat(r," unpublished ").concat(o)),this.safeEmit(_t.USER_UNPUBLISHED,a,o)}}),S(this,"_handleP2PLost",r=>C(this,null,function*(){_.debug("[".concat(this._clientId,"] receive p2p lost"),r),parseInt(r.p2pid,10)===this.store.p2pId?yield this._p2pChannel.requestReconnect():_.warning("[".concat(this._clientId,"] P2PLost stream not found"),r)})),S(this,"_handleTokenWillExpire",()=>{_.debug("[".concat(this._clientId,"] received message onTokenPrivilegeWillExpire")),this.safeEmit(_t.ON_TOKEN_PRIVILEGE_WILL_EXPIRE)}),S(this,"_handleBeforeUnload",r=>{r.type==="beforeunload"&&r.returnValue!==void 0&&r.returnValue!==""||(this.leave(),_.info("[".concat(this._clientId,"] auto leave onbeforeunload or pagehide")))}),S(this,"_handleUpdateNetworkQuality",()=>{if(this._networkQualitySensitivity==="normal")return;if(navigator&&navigator.onLine!==void 0&&!navigator.onLine)return void this.safeEmit(_t.NETWORK_QUALITY,{downlinkNetworkQuality:6,uplinkNetworkQuality:6});const r={downlinkNetworkQuality:0,uplinkNetworkQuality:0};r.uplinkNetworkQuality=this._p2pChannel.getUplinkNetworkQuality(),r.downlinkNetworkQuality=this._p2pChannel.getDownlinkNetworkQuality(),this.safeEmit(_t.NETWORK_QUALITY,r)}),S(this,"_handleP2PAddAudioOrVideoStream",(r,o,s,a)=>{const c=this._users.find(l=>l.uid===o);if(!c)return void _.error("[".concat(this._clientId,"] can not find target user!(on_add_stream)"));_.debug("[".concat(this._clientId,"] stream added with uid ").concat(o,", type ").concat(r)),this.store.subscribe(c.uid,r,void 0,void 0,void 0,Date.now());const d=r==="audio"?c.hasAudio:c.hasVideo;r==="audio"?c._trust_audio_stream_added_state_=!0:c._trust_video_stream_added_state_=!0,r==="audio"?(c._audio_added_=!0,s!==void 0&&(c._audioSSRC=s),a!==void 0&&(c._audioMid=a)):(c._video_added_=!0,s!==void 0&&(c._videoSSRC=s),a!==void 0&&(c._videoMid=a)),(r==="audio"?c.hasAudio:c.hasVideo)&&!d&&(_.info("[".concat(this._clientId,"] remote user ").concat(c.uid," published ").concat(r)),this.safeEmit(_t.USER_PUBLISHED,c,r)),this._p2pChannel.hasPendingRemoteMedia(c,r)&&(_.debug("[".concat(this._clientId,"] resubscribe ").concat(r," for user ").concat(c.uid," after reconnect.")),this._subscribe(c,r,!0).catch(l=>{_.error("[".concat(this._clientId,"] resubscribe error"),l.toString())}))}),this._config=t,this._clientId=e||Gt(5,"client-"),this.store=new class{constructor(r,o,s,a){st(this,"state",void 0),this.state={codec:r,audioCodec:o,mode:s,clientId:a,sessionId:null,p2pId:0,dcId:0,pubId:0,subId:0,keyMetrics:{publish:[],subscribe:[]},joinChannelServiceRecords:[],cloudProxyServerMode:"disabled",useP2P:!1,p2pTransport:$o.Default,hasStartJoinChannel:!1,isABTestSuccess:!1}}dispatch(r){this.state=function(o,s){switch(s.type){case ft.SET_SESSION_ID:return z(z({},o),{},{sessionId:s.sessionId});case ft.SET_P2P_ID:return z(z({},o),{},{p2pId:s.p2pId});case ft.SET_UID:return z(z({},o),{},{uid:s.uid});case ft.SET_INT_UID:return z(z({},o),{},{intUid:s.intUid});case ft.SET_PUB_ID:return z(z({},o),{},{pubId:s.pubId});case ft.KEY_METRIC_CLIENT_CREATED:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{clientCreated:s.metric})});case ft.KEY_METRIC_JOIN_START:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{joinStart:s.metric})});case ft.KEY_METRIC_JOIN_END:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{joinEnd:s.metric})});case ft.KEY_METRIC_REQUEST_AP_START:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{requestAPStart:s.metric})});case ft.KEY_METRIC_REQUEST_AP_END:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{requestAPEnd:s.metric})});case ft.KEY_METRIC_JOIN_GATEWAY_START:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{joinGatewayStart:s.metric})});case ft.KEY_METRIC_JOIN_GATEWAY_END:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{joinGatewayEnd:s.metric})});case ft.KEY_METRIC_PEER_CONNECTION_START:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{peerConnectionStart:s.metric})});case ft.KEY_METRIC_PEER_CONNECTION_END:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{peerConnectionEnd:s.metric})});case ft.KEY_METRIC_DESCRIPTION_START:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{descriptionStart:s.metric})});case ft.KEY_METRIC_SIGNAL_CHANNEL_OPEN:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{signalChannelOpen:s.metric})});case ft.KEY_METRIC_ICE_CONNECTION_END:return z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{iceConnectionEnd:s.metric})});case ft.KEY_METRIC_PUBLISH:{const a=o.keyMetrics.publish,c=a.findIndex(d=>d.trackId===s.metric.trackId);return c!==-1?(a[c]=z(z({},a[c]),s.metric),z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{publish:[...a]})})):z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{publish:[...o.keyMetrics.publish,s.metric]})})}case ft.KEY_METRIC_SUBSCRIBE:{const a=o.keyMetrics.subscribe,c=a.findIndex(d=>d.userId===s.metric.userId&&d.type===s.metric.type);return c!==-1?(a[c]=z(z({},a[c]),s.metric),z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{subscribe:[...a]})})):z(z({},o),{},{keyMetrics:z(z({},o.keyMetrics),{},{subscribe:[...o.keyMetrics.subscribe,s.metric]})})}case ft.SET_CLOUD_PROXY_SERVER_MODE:return o.cloudProxyServerMode=s.mode,o;case ft.RECORD_JOIN_CHANNEL_SERVICE:return typeof s.index!="number"?o.joinChannelServiceRecords=[...o.joinChannelServiceRecords,s.record]:(o.joinChannelServiceRecords[s.index]=z(z({},o.joinChannelServiceRecords[s.index]),s.record),o.joinChannelServiceRecords=[...o.joinChannelServiceRecords]),o;case ft.RESET_JOIN_CHANNEL_SERVICE_RECORDS:return o.joinChannelServiceRecords=[],o;case ft.RESET_KEY_METRICS:return o.keyMetrics={publish:[],subscribe:[]},o;case ft.SET_USE_P2P:return z(z({},o),{},{useP2P:s.val});case ft.SET_TRANSPORT_TYPE:return z(z({},o),{},{p2pTransport:s.val});default:return o}}(this.state,r)}set sessionId(r){this.dispatch({type:ft.SET_SESSION_ID,sessionId:r})}get sessionId(){return this.state.sessionId}set cid(r){this.state.cid=r}get cid(){return this.state.cid}set codec(r){this.state.codec=r}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(r){this.dispatch({type:ft.SET_P2P_ID,p2pId:r})}get p2pId(){return this.state.p2pId}set dcId(r){this.dispatch({type:ft.SET_DC_ID,dcId:r})}get dcId(){return this.state.dcId}set uid(r){this.dispatch({type:ft.SET_UID,uid:r})}get uid(){return this.state.uid}set intUid(r){this.dispatch({type:ft.SET_INT_UID,intUid:r})}get intUid(){return this.state.intUid}set pubId(r){this.dispatch({type:ft.SET_PUB_ID,pubId:r})}get pubId(){return this.state.pubId}set cloudProxyServerMode(r){this.dispatch({type:ft.SET_CLOUD_PROXY_SERVER_MODE,mode:r})}get cloudProxyServerMode(){return this.state.cloudProxyServerMode}set useP2P(r){this.dispatch({type:ft.SET_USE_P2P,val:r})}get useP2P(){return this.state.useP2P}set p2pTransport(r){this.dispatch({type:ft.SET_TRANSPORT_TYPE,val:r})}get p2pTransport(){return this.state.p2pTransport}set hasStartJoinChannel(r){this.state.hasStartJoinChannel=r}get hasStartJoinChannel(){return this.state.hasStartJoinChannel}set isABTestSuccess(r){this.state.isABTestSuccess=r}get isABTestSuccess(){return this.state.isABTestSuccess}clientCreated(){this.dispatch({type:ft.KEY_METRIC_CLIENT_CREATED,metric:Date.now()})}joinStart(){this.dispatch({type:ft.KEY_METRIC_JOIN_START,metric:Date.now()})}joinEnd(){this.dispatch({type:ft.KEY_METRIC_JOIN_END,metric:Date.now()})}requestAPStart(){this.dispatch({type:ft.KEY_METRIC_REQUEST_AP_START,metric:Date.now()})}requestAPEnd(){this.dispatch({type:ft.KEY_METRIC_REQUEST_AP_END,metric:Date.now()})}joinGatewayStart(){this.dispatch({type:ft.KEY_METRIC_JOIN_GATEWAY_START,metric:Date.now()})}joinGatewayEnd(){this.dispatch({type:ft.KEY_METRIC_JOIN_GATEWAY_END,metric:Date.now()})}peerConnectionStart(){this.dispatch({type:ft.KEY_METRIC_PEER_CONNECTION_START,metric:Date.now()})}peerConnectionEnd(){this.dispatch({type:ft.KEY_METRIC_PEER_CONNECTION_END,metric:Date.now()})}descriptionStart(){this.dispatch({type:ft.KEY_METRIC_DESCRIPTION_START,metric:Date.now()})}signalChannelOpen(){this.dispatch({type:ft.KEY_METRIC_SIGNAL_CHANNEL_OPEN,metric:Date.now()})}iceConnectionEnd(){this.dispatch({type:ft.KEY_METRIC_ICE_CONNECTION_END,metric:Date.now()})}publish(r,o,s,a){this.dispatch({type:ft.KEY_METRIC_PUBLISH,metric:z(z({trackId:r,type:o},s&&{publishStart:s}),a&&{publishEnd:a})})}subscribe(r,o,s,a,c,d,l){this.dispatch({type:ft.KEY_METRIC_SUBSCRIBE,metric:z(z(z(z(z({userId:r,type:o},s&&{subscribeStart:s}),a&&{subscribeEnd:a}),c&&{firstFrame:c}),d&&{streamAdded:d}),l&&{firstDecoded:l})})}massSubscribe(r,o,s,a){r.forEach(c=>{this.dispatch({type:ft.KEY_METRIC_SUBSCRIBE,metric:z(z(z({userId:c.userId,type:c.type},o&&{subscribeStart:o}),s&&{subscribeEnd:s}),a&&{firstFrame:a})})})}get keyMetrics(){return this.state.keyMetrics}recordJoinChannelService(r,o){r.service==="gateway"&&Array.isArray(r.urls)&&(r.urls=r.urls.map(s=>s.replace(/(\d+)-\d+-\d+-(\d+)/,"$1-*-*-$2")));try{return typeof o!="number"?(this.dispatch({type:ft.RECORD_JOIN_CHANNEL_SERVICE,record:z(z({},r),{},{sessionId:this.sessionId,cloudProxyMode:this.cloudProxyServerMode,uid:this.uid})}),this.state.joinChannelServiceRecords.length-1):(o<0||o>=this.state.joinChannelServiceRecords.length||this.dispatch({type:ft.RECORD_JOIN_CHANNEL_SERVICE,record:r,index:o}),o)}catch(s){return 0}}resetJoinChannelServiceRecords(){this.dispatch({type:ft.RESET_JOIN_CHANNEL_SERVICE_RECORDS})}resetKeyMetrics(){this.dispatch({type:ft.RESET_KEY_METRICS})}get joinChannelServiceRecords(){try{return this.state.joinChannelServiceRecords}catch(r){return[]}}}(t.codec,t.audioCodec,t.mode,this._clientId),this._leaveMutex=new qe("client-leave",this._clientId),this._publishMutex=new qe("client-publish",this._clientId),this._renewTokenMutex=new qe("client-renewtoken",this._clientId),this._subscribeMutex=new qe("client-subscribe",this._clientId),this.store.clientCreated(),t.proxyServer&&this.setProxyServer(t.proxyServer,!0),t.turnServer&&this.setTurnServer(t.turnServer,!0),_.info("[".concat(this._clientId,"] Initializing AgoraRTC client v").concat(dn," build: ").concat(XE,", mode: ").concat(this.mode,", codec: ").concat(this.codec)),t.clientRoleOptions)try{ME(t.clientRoleOptions),i=Object.assign({},t.clientRoleOptions)}catch(r){_.warning("[".concat(this._clientId,"] ").concat(r.toString()))}var n;this._statsCollector=new Xc(this.store),this._statsCollector.onStatsException=(r,o,s)=>{_.warn("[".concat(this._clientId,"] receive exception msg, code: ").concat(r,", msg: ").concat(o,", uid: ").concat(s)),this.safeEmit(_t.EXCEPTION,{code:r,msg:o,uid:s})},this._statsCollector.onUploadPublishDuration=(r,o,s,a)=>{const c=this._users.find(d=>d.uid===r);c&&Z.peerPublishStatus(this._sessionId,{subscribeElapse:a,audioPublishDuration:o,videoPublishDuration:s,peer:c._uintid})},this._statsCollector.onVideoCodecChanged=r=>{if(y("VIDEO_STANDARD_BITRATE_VERSION")&&(r==="av1"||r==="h265"||r==="h264")){const o=this.localTracks.find(s=>s instanceof Yt);o&&o._saveEncodeBitrateRatio!==1&&o.setSaveEncodeBitrateRatio(r==="h264"?y("BASELINE_MORE_H264_BITRATE_RATIO"):void 0)}},this.store.useP2P=t.mode==="p2p",this._gateway=new mW(this.store,{clientId:this._clientId,mode:this.mode,codec:this.codec,websocketRetryConfig:t.websocketRetryConfig||ge,httpRetryConfig:t.httpRetryConfig||ge,forceWaitGatewayResponse:t.forceWaitGatewayResponse===void 0||t.forceWaitGatewayResponse,statsCollector:this._statsCollector,role:t.role,clientRoleOptions:i}),this._configDistribute=new AW(this._clientId,this.store),this.store.useP2P?(this._p2pChannel=(n={store:this.store,statsCollector:this._statsCollector},Kr("P2PChannel").create(n)),this._handleP2PEvents()):this._p2pChannel=new Zc(this.store,this._statsCollector),this._handleP2PChannelEvents(),this._handleGatewayEvents(),this._handleGatewaySignalEvents()}joinMeta(o,s,a,c,d){return C(this,arguments,function*(t,e,i,n,r){let l=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5],u=arguments.length>6&&arguments[6]!==void 0&&arguments[6];kt("JOIN_GATEWAY_USE_443PORT_ONLY",l),kt("JOIN_GATEWAY_USE_DUAL_DOMAIN",u);const h=this._gateway.signal.websocket;return h instanceof Om&&(h.use443PortOnly=l,h.tryDoubleDomain=u),function(f,T,R){return C(this,arguments,function*(p,g,m){nu.get(p)||nu.set(p,[]),ru.get(p)||ru.set(p,g),_r.get(p)||_r.set(p,0);const A=nu.get(p),N=ru.get(p);if(!A||!N)throw new Error("concurrent: deferQueue or maxConcurrency is null");if(_r.get(p)===N){const j=Ic();A.push(j),yield j.promise}_r.set(p,_r.get(p)+1);for(var O=arguments.length,w=new Array(O>3?O-3:0),L=3;L<O;L++)w[L-3]=arguments[L];const M=yield m(...w);return _r.set(p,_r.get(p)-1),_r.get(p)===N-1&&A.length>0&&(A[0].resolve(),A.shift()),_r.get(p)===0&&(nu.set(p,[]),ru.set(p,0),_r.set(p,0)),M})}("client.join",y("JOIN_MAX_CONCURRENCY"),this.join.bind(this),t,e,i,n,r)})}join(t,e,i,n,r){return C(this,null,function*(){const o=++this._numberOfJoinCount;this.store.joinStart(),n&&(this.store.uid=n);const s=(uu||uu||(uu=(window.location.protocol.split(":")[0]||"").toUpperCase(),uu))==="HTTPS",a=vI()?window.isSecureContext:"Browser Not Support";(!vI()&&!s||!window.isSecureContext)&&_.warning("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"),Z.setAppId(t);try{if(!i&&i!==null)throw new P(v.INVALID_PARAMS,"Invalid token: ".concat(i,". If you don not use token, set it to null"));i&&Me(i,"token",1,2047),Me(t,"appid",1,2047),Lu(e),n&&ku(n),r&&Me(r,"optionalInfo",1,2047)}catch(m){throw Z.reportApiInvoke(Zo(),{name:_e.JOIN,options:[t,e,i,n],states:{isHttps:s,isSecureContext:a},tag:oe.TRACER}).onError(m),m}if(this._leaveMutex.isLocked&&(_.debug("[".concat(this._clientId,"] join: waiting leave operation")),(yield this._leaveMutex.lock())(),_.debug("[".concat(this._clientId,"] join: continue"))),this._joinAndNotLeaveYet=!0,this.connectionState!=="DISCONNECTED"){const m=new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] Client already in connecting/connected state"));throw Z.reportApiInvoke(Zo(),{name:_e.JOIN,options:[t,e,i,n],states:{isHttps:s,isSecureContext:a},tag:oe.TRACER}).onError(m),m}this._gateway.state="CONNECTING";const c=yield S0({appId:t,cname:e,uid:n,stringUid:typeof n=="string"?n:void 0,token:i||t,cloudProxyServer:this._cloudProxyServerMode});if(!this._joinAndNotLeaveYet)throw new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));const d=(c==null?void 0:c.sid)||Zo();_.info("[".concat(this._clientId,"] start join channel ").concat(e,", join number: ").concat(o)),this._sessionId||(this._sessionId=d,this.store.sessionId=this._sessionId);const l=Z.reportApiInvoke(d,{id:this._clientId,name:_e.JOIN,options:[t,e,i,n],states:{isHttps:s,isSecureContext:a},tag:oe.TRACER}),u=xn(xn(xn({},this._rtmConfig),{},{role:this.role,clientId:this._clientId,appId:t,sid:this._sessionId,cname:e,uid:typeof n!="string"?n:null,turnServer:this._turnServer,proxyServer:this._proxyServer,token:i||t,cloudProxyServer:this._cloudProxyServerMode,optionalInfo:r,license:this._license,useLocalAccessPoint:this._useLocalAccessPoint,preload:!!c},this._remoteDefaultVideoStreamType!==void 0&&{defaultVideoStream:this._remoteDefaultVideoStreamType}),{},{apRequestDetail:y("AP_REQUEST_DETAIL")||void 0});if(this._useLocalAccessPoint&&(u.setLocalAPVersion=this._setLocalAPVersion),typeof n=="string"&&(u.stringUid=n,this._uintUid?(u.uid=this._uintUid,this._uintUid=void 0):u.uid=0),this._encryptionMode!=="none"&&this._encryptionSecret){if(u.aesmode=this._encryptionMode,u.aespassword=yield(m=>C(this,null,function*(){const f=function(N){const O=window.atob(`MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCMnXAHkKIGAM+x4N22gCI+Wyu
STM9ztkT3uYslTT2PuKmZfPzhH6kVdO7PTjGCOZnAsyb3oTtWat0KcxQ4jxvqQV+
HvYl3iI1Yd4vl2c3qRMJPLtRDfNxa2Mcxgq7e9aEUibzdd0st+OJAy3tOj/Y0aVy
xQiYDz3vqa6bP29adwIDAQAB`),w=new Uint8Array(new ArrayBuffer(O.length));for(let L=0;L<O.length;L+=1)w[L]=O.charCodeAt(L);return w}(),T=yield window.crypto.subtle.importKey("spki",f,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"]),R=LE(m),A=yield window.crypto.subtle.encrypt({name:"RSA-OAEP"},T,R);return function(N){let O="";for(let w=0;w<N.length;w+=1)O+=String.fromCharCode(N[w]);return window.btoa(O)}(new Uint8Array(A))}))(this._encryptionSecret),!this._joinAndNotLeaveYet)throw new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));this._encryptionSalt&&(u.aessalt=this._encryptionSalt)}if(this._encryptDataStream&&(this._encryptionMode==="aes-128-gcm2"||this._encryptionMode==="aes-256-gcm2"))if(this._encryptionSalt&&this._encryptionSecret)if(window.crypto.subtle){const m=new TextEncoder,f=y("USE_PURE_ENCRYPTION_MASTER_KEY")?m.encode(u.appId+this._encryptionSecret+this._encryptionSecret):m.encode(u.appId+u.cname+this._encryptionSecret);this._encryptDataStreamIv=yield function(T,R,A){return C(this,null,function*(){const N=yield window.crypto.subtle.importKey("raw",R,"PBKDF2",!1,["deriveBits","deriveKey"]),O=T==="aes-128-gcm2"?128:256,w=yield window.crypto.subtle.deriveBits({name:"PBKDF2",iterations:PI,hash:"SHA-256",salt:A},N,O+KG);return new Uint8Array(w).subarray(O/8)})}(this._encryptionMode,f,Qo(this._encryptionSalt)),this._encryptDataStreamKey=yield function(T,R,A){return C(this,null,function*(){const N=yield window.crypto.subtle.importKey("raw",R,"PBKDF2",!1,["deriveBits","deriveKey"]),O=T==="aes-128-gcm2"?128:256;return yield window.crypto.subtle.deriveKey({name:"PBKDF2",iterations:PI,hash:"SHA-256",salt:A},N,{name:"AES-GCM",length:O},!0,["encrypt","decrypt"])})}(this._encryptionMode,f,Qo(this._encryptionSalt))}else a?_.warning("[".concat(this._clientId,"] encrypt datastream must be running in a secure context, fallback to plain data stream")):_.warning("[".concat(this._clientId,"] current browser do not support WebCrypto ,fallback to plain data stream")),this._encryptDataStream=!1;else this._encryptDataStream=!1,_.debug("[".concat(this._clientId,"] no salt / secret, cannot support encrypt data stream, fallback to plain data stream"));this._startSession(this._sessionId,{channel:e,appId:t,stringUid:u.stringUid});const h=this._sessionId;setTimeout(()=>{this.connectionState==="CONNECTING"&&h===this._sessionId&&Z.joinChannelTimeout(this._sessionId,5)},5e3);try{var p;let m;const f=u.cloudProxyServer;if(G(p=["proxy3","proxy4","proxy5"]).call(p,f)){const O=y("PROXY_SERVER_TYPE3");Array.isArray(O)?u.proxyServer=O[0]:u.proxyServer=O}if(Z.setProxyServer(u.proxyServer),_.setProxyServer(u.proxyServer),this.store.requestAPStart(),c){if(_.debug("[".concat(this._clientId,"] get serverInfo Success from Preload Cache ").concat(u.stringUid?", ".concat(u.stringUid," => ").concat(c.intUid):""," ")),u.stringUid&&!u.uid&&(u.uid=c.intUid),m={gatewayInfo:c.ap.gatewayInfo},y("JOIN_WITH_FALLBACK_MEDIA_PROXY")&&u.turnServer.mode==="auto")if(c.ap.proxyInfo.addresses.length===0)_.warning("no edge services in ap response of proxy fallback, will not set proxy in iceServers");else{const O=(yield pw(c.ap.proxyInfo,c.ap.gatewayInfo.uid)).map(w=>({turnServerURL:w.address,tcpport:w.tcpport||He.tcpport,udpport:w.udpport||He.udpport,username:w.username||He.username,password:w.password||He.password,forceturn:!1,security:!0}));u.turnServer={mode:"manual",servers:O}}v0(c,u.stringUid)}else{if(u.stringUid&&!u.uid){let O;[O,m]=yield K.all([jw(u.stringUid,u,this._axiosCancelSource.token,this._config.httpRetryConfig||ge,this.store),Bw(u,this._axiosCancelSource.token,this._config.httpRetryConfig||ge,!0,this.store)]),_.debug("[".concat(this._clientId,"] getUserAccount Success ").concat(u.stringUid," => ").concat(O)),u.uid=O,m.gatewayInfo.uid=O,m.gatewayInfo.res.uid=O}else m=yield Bw(u,this._axiosCancelSource.token,this._config.httpRetryConfig||ge,!0,this.store);if(!this._joinAndNotLeaveYet)throw new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"))}this.store.requestAPEnd(),setTimeout(()=>{this._configDistribute.startGetConfigDistribute(u,this._axiosCancelSource.token),this._configDistribute.on(Bc.UPDATE_BITRATE_LIMIT,O=>{this._p2pChannel.updateBitrateLimit(O)}),this._configDistribute.on(Bc.UPDATE_CLIENT_ROLE_OPTIONS,O=>{this._setClientRoleOptions(O)})},0),this._key=i||t;const T=m.gatewayInfo,R=u.uid?u.uid:T.uid;this._joinInfo=xn(xn({},u),{},{cid:T.cid,uid:R,vid:T.vid,apResponse:T.res,apGatewayAddress:T.apGatewayAddress,uni_lbs_ip:T.uni_lbs_ip,gatewayAddrs:T.gatewayAddrs}),this.store.intUid=R,this.store.cid=T.cid;const A=yield this._joinGateway();if(!this._joinAndNotLeaveYet)throw new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] Client already left"));l.onSuccess(A),this._appId=t,this._channelName=u.cname,this._uid=A,this.store.uid=A,setTimeout(()=>{this._networkQualityInterval&&window.clearInterval(this._networkQualityInterval),this._networkQualityInterval=window.setInterval(this._handleUpdateNetworkQuality,2e3),window.addEventListener(je()?"beforeunload":"pagehide",this._handleBeforeUnload),this._statsCollector.startUpdateStats()},0);const N=u.stringUid?"string uid: ".concat(u.stringUid,",uid: ").concat(u.uid):"uid: ".concat(this._uid);return _.info("[".concat(this._clientId,"] Joining channel success: channel: ").concat(e,",").concat(N)),setTimeout(()=>{_.startUpload()},5e3),this.store.joinEnd(),g=this,G(os).call(os,g)||os.push(g),this._cloudProxyServerMode==="disabled"&&Ct().supportWebCrypto&&y("ENABLE_PRELOAD")&&nf(this._joinInfo),A}catch(m){const f=Array.isArray(m)?m[0]:m;throw f&&f.code===v.OPERATION_ABORTED?_.warning("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),f):_.error("[".concat(this._clientId,"] join number: ").concat(o,", Joining channel failed, rollback"),f),f.code!==v.OPERATION_ABORTED&&this._numberOfJoinCount===o&&(this._gateway.state="DISCONNECTED",this._reset()),l.onError(f),f}var g})}_joinGateway(){if(!this._joinInfo||!this._key)throw new P(v.INVALID_OPERATION);return this._gateway.join(this._joinInfo,this._key,!(this._joinInfo.cloudProxyServer!=="disabled"||this._joinInfo.proxyServer||!y("JOIN_WITH_FALLBACK_SIGNAL_PROXY")))}leave(){return C(this,null,function*(){_.info("[".concat(this._clientId,"] Leaving channel")),window.removeEventListener(je()?"beforeunload":"pagehide",this._handleBeforeUnload),this._reset(),function(e){const i=os.indexOf(e);i!==-1&&os.splice(i,1)}(this),this._statsCollector.stopUpdateStats();const t=yield this._leaveMutex.lock();if(this.connectionState==="DISCONNECTED")return _.info("[".concat(this._clientId,"] Leaving channel repeated, success")),void t();yield this._gateway.leave(this.connectionState!=="CONNECTED",bt.LEAVE),_.info("[".concat(this._clientId,"] Leaving channel success")),this._joinAndNotLeaveYet=!1,this.store.resetJoinChannelServiceRecords(),t()})}publish(e){return C(this,arguments,function*(t){let i=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Array.isArray(t)){if(!(t instanceof Ea))return this._publishDataChannel(t);t=[t]}if(t.length===0)throw new P(v.INVALID_PARAMS,"param list is empty");const n=t;if(this._gateway.role==="audience")throw new P(v.INVALID_OPERATION,"audience can not publish stream");for(const o of n){if(!(o instanceof Ea))throw new P(v.INVALID_PARAMS,"parameter is not local track");if(!o._enabled&&i)throw new P(v.TRACK_IS_DISABLED,"can not publish a disabled track: ".concat(o.getTrackId()))}_.info("[".concat(this._clientId,"] Publishing tracks, id ").concat(n.map(o=>"".concat(o.getTrackId()," "))));const r=yield this._publishMutex.lock();yield this._configDistribute.awaitConfigDistributeComplete(),i&&n.forEach(o=>{const s=this._configDistribute.getBitrateLimit();o instanceof Yt&&s&&o.setBitrateLimit(s.uplink)});try{yield this._publishHighStream(n),_.info("[".concat(this._clientId,"] Publish success, id ").concat(n.map(o=>"".concat(o.getTrackId()," "))))}catch(o){throw _.error("[".concat(this._clientId,"] publish error"),o.toString()),o}finally{r()}})}_publishDataChannel(t){return C(this,null,function*(){xt(t.id,"id",0,65535,!0),Fr(t.ordered,"ordered"),Me(t.metadata,"metadata",0,512),_.info("[".concat(this._clientId,"] Publishing datachannels, id ").concat(t.id));const e=yield this._publishMutex.lock();try{if(this._p2pChannel.getAllDataChannels().findIndex(r=>r.id===t.id)!==-1)throw new P(v.INVALID_PARAMS,"Invalid id: ".concat(t.id,". If you want to republish the datachannel, unpublish first"));if(!this._joinInfo||this._uid===void 0)throw new P(v.INVALID_OPERATION,"Can't publish datachannel, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not publish datachannel in ".concat(this.connectionState," state"));if(this._turnServer.mode==="auto"&&y("FORCE_TURN")&&!y("TURN_ENABLE_TCP")&&!y("TURN_ENABLE_UDP"))throw new P(v.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");const i=function(r){return Dw(r,!1)}(t),n=yield this._p2pChannel.publishDataChannel([i]);if(n.length>0){if(typeof i._originDataChannelId!="number")throw _.error("[".concat(this._clientId,"] can not publish with mediaType datachannel, cannot get RTCDatachannel id")),new P(v.CREATE_DATACHANNEL_ERROR);try{yield K.all(n.map(r=>this._uid&&this._gateway.publishDataChannel(this._uid,r,!0))),yield i._waitTillOpen()}catch(r){if(r.code!==v.DISCONNECT_P2P)throw r}}return _.info("[".concat(this._clientId,"] Publish dataChannels success, id ").concat(i.id)),i}catch(i){throw _.error("[".concat(this._clientId,"] publish datachannels error"),i.toString()),i}finally{e()}})}unpublish(t){return C(this,null,function*(){if(!this._joinInfo||this._uid===void 0)throw new P(v.INVALID_OPERATION,"Can't unpublish stream, haven't joined yet!");let e=[];if(t)if(Array.isArray(t))e=t;else{if(!(t instanceof Ea))return this._unpublishDataChannel([t]);e=[t]}else this.store.useP2P||(yield this._unpublishDataChannel()),e=this._p2pChannel.getAllTracks(!0);_.info("[".concat(this._clientId,"] Unpublish tracks, tracks ").concat(e.map(n=>"".concat(n.getTrackId()," "))," "));const i=yield this._publishMutex.lock();try{if(this.store.useP2P){const n=yield this._p2pChannel.unpublish(e);n&&(yield this._gateway.sendExtensionMessage(he.UNPUBLISH,{unpubMsg:n},!0))}else{const n=yield this._p2pChannel.unpublish(e);n&&(yield this._gateway.unpublish(n,this._uid)),_.info("[".concat(this._clientId,"] Unpublish success,tracks ").concat(e.map(r=>"".concat(r.getTrackId()))))}}catch(n){throw _.error("[".concat(this._clientId,"] unpublish error"),n.toString()),n}finally{i&&i()}})}_unpublishDataChannel(t){return C(this,null,function*(){t!==void 0&&t.length!==0||(t=this._p2pChannel.getAllDataChannels()),_.info("[".concat(this._clientId,"] Unpublish datachannels, datachannels ").concat(t.map(i=>"".concat(i.id," "))," "));const e=yield this._publishMutex.lock();try{const i=yield this._p2pChannel.unpublishDataChannel(t);i&&(yield this._gateway.unpublishDataChannel(i)),_.info("[".concat(this._clientId,"] Unpublish dataChannel success,dataChannel ").concat(t.map(n=>"".concat(n.id))))}catch(i){throw _.error("[".concat(this._clientId,"] unpublish dataChannel error"),i.toString()),i}finally{e&&e()}})}subscribe(t,e,i){return C(this,null,function*(){if(!(t instanceof Co)){const n=this.remoteUsers.find(r=>r.uid===t);if(!n)throw new P(v.INVALID_REMOTE_USER,"user is not in the channel");t=n}return e==="datachannel"?this._subscribeDataChannel(t,i):this._subscribe(t,e)})}presubscribe(t,e){return C(this,null,function*(){if(Ae(e,"mediaType",["audio","video"]),this.store.useP2P)throw new P(v.INVALID_OPERATION,"can't presub at p2p mode");if(!this._joinInfo)throw new P(v.INVALID_OPERATION,"can't presub when not join");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can't presub in ".concat(this.connectionState," state"));const i=e===q.AUDIO,n=e===q.VIDEO,r=yield this._subscribeMutex.lock();try{const{ssrcId:o,ortc:s,rtxSsrcId:a,cname:c,uint_id:d}=yield this._gateway.presubscribe(t,e,!0);if(o==null)throw new P(v.UNEXPECTED_RESPONSE,"no ssrc id");let l=this._users.find(h=>h.uid===t);l||(l=new Co(t,d||t),l._is_pre_created=!0,this._users.push(l)),c&&(l._cname=c),l._uintid||(l._uintid=d||t),i&&(l._audioSSRC=o,l._audio_pre_subscribed=!0,s&&(l._audioOrtc=s)),n&&(l._videoSSRC=o,l._video_pre_subscribed=!0,s&&(l._videoOrtc=s),a!=null&&(l._rtxSsrcId=a)),_.info("[".concat(this._clientId,"] presub succeed ssrc: ").concat(o)),yield this._p2pChannel.subscribe(l,e,o,a,s);const u=i?l._audioTrack:l._videoTrack;if(!u)throw new P(v.UNEXPECTED_ERROR,"can not find remote track in user");return i&&(l._trust_audio_stream_added_state_=!0,l._audio_added_=!0),n&&(l._trust_video_stream_added_state_=!0,l._video_added_=!0),u}catch(o){throw _.error("[".concat(this._clientId,"] presub user ").concat(t," error"),o),o}finally{r()}})}_subscribeDataChannel(t,e){return C(this,null,function*(){var i;if(xt(e,"channelId",0,65535,!0),!this._joinInfo)throw new P(v.INVALID_OPERATION,"Can't subscribe datachannel, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"Can't subscribe datachannel in ".concat(this.connectionState," state"));if(!this._users.find(a=>a===t))throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid,", this user is not in the channel")),new P(v.INVALID_REMOTE_USER,"user is not in the channel");if(!t.hasAudio&&!t.hasVideo&&t._dataChannels.length===0)throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid,", user is not published")),new P(v.INVALID_REMOTE_USER,"user is not published");const r=(i=t._dataChannels)===null||i===void 0?void 0:i.find(a=>a.id===e);if(!r)throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid," with mediaType datachannel, remote datachannel is not published")),new P(v.REMOTE_USER_IS_NOT_PUBLISHED);const o=yield this._subscribeMutex.lock();_.info("[".concat(this._clientId,"] subscribe user ").concat(t.uid,", mediaType: datachannel"));try{const a=yield this._p2pChannel.subscribeDataChannel(t,[r]);if(a&&G(a).call(a,r.id))try{var s;if(typeof r._originDataChannelId!="number")throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid," with mediaType datachannel, cannot get RTCDatachannel")),new P(v.CREATE_DATACHANNEL_ERROR);const c={id:r.id,datachannelId:r._originDataChannelId,ordered:r.ordered,maxRetransmits:r.maxRetransmits,metadata:(s=r.metadata)!==null&&s!==void 0?s:""};yield this._gateway.subscribeDataChannel(t.uid,c,!0),yield r._waitTillOpen()}catch(c){if((c==null?void 0:c.code)!==v.WS_ABORT)throw yield this._p2pChannel.unsubscribeDataChannel(t,[r]),c;yield this._p2pChannel.unsubscribeDataChannel(t,[r]),this._p2pChannel.setPendingRemoteDataChannel(t,r.id)}return _.info("[".concat(this._clientId,"] subscribe success user ").concat(t.uid,", mediaType: datachannel")),r}finally{o()}})}_p2pSubscribe(t,e,i){return C(this,null,function*(){if(Ae(e,"mediaType",["audio","video"]),!this._joinInfo)throw new P(v.INVALID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(o=>o===t)){const o=new P(v.INVALID_REMOTE_USER,"user is not in the channel");throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid,", this user is not in the channel")),o}if(!t.hasAudio&&!t.hasVideo){const o=new P(v.INVALID_REMOTE_USER,"user is not published");throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid,", user is not published")),o}if(!i&&(e==="audio"&&!t.hasAudio||e==="video"&&!t.hasVideo)){const o=new P(v.REMOTE_USER_IS_NOT_PUBLISHED);throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid," with mediaType ").concat(e,", remote track is not published")),o}const r=yield this._subscribeMutex.lock();_.info("[".concat(this._clientId,"] subscribe user ").concat(t.uid,", mediaType: ").concat(e));try{if(yield this._p2pChannel.hasRemoteMediaWithLock(t,e))yield this._p2pChannel.unmuteRemote(t,e);else try{const s=e==="audio"?t._audioSSRC:t._videoSSRC,a=e==="audio"?t._audioMid:t._videoMid;this.store.subscribe(t.uid,e,Date.now()),this.store.useP2P&&(yield this._p2pChannel.subscribe(t,e,s,a))}catch(s){throw s}_.info("[".concat(this._clientId,"] subscribe success user ").concat(t.uid,", mediaType: ").concat(e)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(t.uid,this._defaultStreamFallbackType).catch(s=>{_.warning("[".concat(this._clientId,"] auto set fallback failed"),s)});const o=e==="audio"?t._audioTrack:t._videoTrack;if(!o)throw new P(v.UNEXPECTED_ERROR,"can not find remote track in user object");return o}catch(o){throw _.error("[".concat(this._clientId,"] subscribe user ").concat(t.uid," error"),o),o}finally{r()}})}_subscribe(t,e,i){return C(this,null,function*(){if(this.store.useP2P)return this._p2pSubscribe(t,e);if(Ae(e,"mediaType",["audio","video"]),!this._joinInfo)throw new P(v.INVALID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));if(!this._users.find(d=>d===t)){const d=new P(v.INVALID_REMOTE_USER,"user is not in the channel");throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid,", this user is not in the channel")),d}if(!t.hasAudio&&!t.hasVideo){const d=new P(v.INVALID_REMOTE_USER,"user is not published");throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid,", user is not published")),d}if(!(i||(e!=="audio"||t.hasAudio&&t._audioSSRC!==void 0)&&(e!=="video"||t.hasVideo&&t._videoSSRC!==void 0))){const d=new P(v.REMOTE_USER_IS_NOT_PUBLISHED);throw _.error("[".concat(this._clientId,"] can not subscribe ").concat(t.uid," with mediaType ").concat(e,", remote track is not published")),d}let r=e==="audio"?t._audioSSRC:t._videoSSRC,o=e==="audio"?t._audioOrtc:t._videoOrtc,s=e==="video"?t._rtxSsrcId:void 0,a={stream_type:e==="audio"?q.AUDIO:q.VIDEO,ssrcId:r};const c=yield this._subscribeMutex.lock();_.info("[".concat(this._clientId,"] subscribe user ").concat(t.uid,", mediaType: ").concat(e));try{if(yield this._p2pChannel.hasRemoteMediaWithLock(t,e))yield this._p2pChannel.unmuteRemote(t,e);else try{const l=e==="audio"?t._audioSSRC:t._videoSSRC;l!==void 0&&l!==r&&(r=l,o=e==="audio"?t._audioOrtc:t._videoOrtc,s=e==="video"?t._rtxSsrcId:void 0,a={stream_type:e==="audio"?q.AUDIO:q.VIDEO,ssrcId:r}),Je.markSubscribeStart(this.store.clientId,r),this.store.subscribe(t.uid,e,Date.now()),yield this._p2pChannel.subscribe(t,e,r,s,o);try{this._p2pChannel.isPreSubScribe(r)||(yield this._gateway.subscribe(t.uid,a,!0))}catch(u){if((u==null?void 0:u.code)!==v.WS_ABORT)throw yield this._p2pChannel.unsubscribe(t,e),u;yield this._p2pChannel.unsubscribe(t,e,!0),this._p2pChannel.setPendingRemoteMedia(t,e)}this.store.subscribe(t.uid,e,void 0,Date.now()),this._p2pChannel.reportSubscribeEvent(!0,null,t,e)}catch(l){throw this._p2pChannel.reportSubscribeEvent(!1,l==null?void 0:l.code,t,e),l}_.info("[".concat(this._clientId,"] subscribe success user ").concat(t.uid,", mediaType: ").concat(e)),this._defaultStreamFallbackType&&this.setStreamFallbackOption(t.uid,this._defaultStreamFallbackType).catch(l=>{_.warning("[".concat(this._clientId,"] auto set fallback failed"),l)});const d=e==="audio"?t._audioTrack:t._videoTrack;if(!d)throw new P(v.UNEXPECTED_ERROR,"can not find remote track in user object");return d}catch(d){throw _.error("[".concat(this._clientId,"] subscribe user ").concat(t.uid," error"),d),d}finally{c()}})}massSubscribe(t){return C(this,null,function*(){if(Br(t,"subscribeList"),!this._joinInfo)throw new P(v.INVALID_OPERATION,"Can't subscribe stream, not joined");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"Can't subscribe stream in ".concat(this.connectionState," state"));const e=Date.now(),i=new Map,n=yield this._subscribeMutex.lock();_.info("[".concat(this._clientId,"]start massSubscribe user ").concat(t.map(a=>{let{user:c,mediaType:d}=a;return"user: ".concat(c==null?void 0:c.uid,", mediaType: ").concat(d)}).join("; ")));const r=(t=[...t]).map(a=>{let{user:c,mediaType:d}=a;return{user:c,mediaType:d}}),o=yield this._p2pChannel.globalLock();try{var s;for(let c=t.length-1;c>=0;c--){const d=t[c],{user:l,mediaType:u}=d;if(Ae(u,"mediaType",["audio","video"]),!l){const m=new P(v.INVALID_PARAMS,"user property does not exist in subscribeList item");throw _.error("[".concat(this._clientId,"] user property does not exist in subscribeList item")),m}if(!this._users.find(m=>m===l)){const m=new P(v.INVALID_REMOTE_USER,"user is not in the channel");_.error("[".concat(this._clientId,"] can not massSubscribe ").concat(l.uid,", this user is not in the channel")),r[c].error=m,t.splice(c,1);continue}if(u==="audio"&&(!l.hasAudio||l._audioSSRC===void 0)||u==="video"&&(!l.hasVideo||l._videoSSRC===void 0)){const m=new P(v.REMOTE_USER_IS_NOT_PUBLISHED);_.error("[".concat(this._clientId,"] can not subscribe ").concat(l.uid," with mediaType ").concat(u,", remote user is not published")),r[c].error=m,t.splice(c,1);continue}const p=Ne.Video|Ne.LwoVideo,g=i.get(l);if(g){if(u==="video"?g&p:g&Ne.Audio){t.splice(c,1),_.warning("[".concat(this._clientId,"] repeat massSubscribe user:").concat(l.uid,", mediaType:").concat(u," twice"));continue}i.set(l,g|(u==="video"?p:Ne.Audio))}else i.set(l,u==="video"?p:Ne.Audio)}for(let c=t.length-1;c>=0;c--){const d=t[c],{user:l,mediaType:u}=d,h=Ne.Video|Ne.LwoVideo;if(this._p2pChannel.hasRemoteMedia(l,u)){yield this._p2pChannel.unmuteRemoteNoLock(l,u);const p=i.get(l);i.set(l,u==="video"?p^h:p^Ne.Audio),t.splice(c,1)}}this.store.massSubscribe(t.map(c=>({userId:c.user.uid,type:c.mediaType})),e);let a=Tn(s=Array.from(i.entries())).call(s,(c,d)=>{let[l,u]=d;if(u===0)return c;const h={stream_id:l.uid,stream_type:u};return u&Ne.Audio&&(h.audio_ssrc=l._audioSSRC),u&Ne.Video&&(h.video_ssrc=l._videoSSRC),c.push(h),c},[]);try{t.length>0&&(yield this._p2pChannel.massSubscribeNoLock(t.map(d=>{let{user:l,mediaType:u}=d;return{user:l,mediaType:u,ssrcId:u===q.VIDEO?l._videoSSRC:l._audioSSRC,rtxSsrcId:u===q.VIDEO?l._rtxSsrcId:void 0}})));const c=new Map;if(a=a.filter(d=>d.video_ssrc&&!this._p2pChannel.isPreSubScribe(d.video_ssrc)||d.audio_ssrc&&!this._p2pChannel.isPreSubScribe(d.audio_ssrc)||!d.video_ssrc&&!d.audio_ssrc),a.length>0){const d=yield this._gateway.subscribeAll(a,!0);((d==null?void 0:d.users)||[]).forEach(l=>{let{stream_id:u,video_error_code:h,audio_error_code:p,error_code:g}=l;(h||p||g)&&c.set(u,{video_error_code:h,audio_error_code:p,error_code:g})})}if(Array.from(c.entries()).length>0){const d=[];Array.from(c.entries()).forEach(l=>{let[u,h]=l;const p=this.remoteUsers.find(g=>g.uid===u);if(p){let g;h.error_code||h.video_error_code&&h.audio_error_code?g=void 0:h.video_error_code?g=q.VIDEO:h.audio_error_code&&(g=q.AUDIO),d.push({user:p,mediaType:g})}}),d.length>0&&(yield this._p2pChannel.massUnsubscribeNoLock(d))}for(const d of r){const l=c.get(d.user.uid);if(l){const u=l.error_code||d.mediaType==="audio"&&l.audio_error_code||d.mediaType==="video"&&l.video_error_code;if(u){const h=jc(u);_.error("user:".concat(d.user.uid," mediaType:").concat(d.mediaType," has massSubscribe error ").concat(h.desc)),d.error=new P(v.SUBSCRIBE_FAILED,"code ".concat(u,": ").concat(h.desc))}}d.error||(d.mediaType==="video"?d.track=d.user.videoTrack:d.track=d.user.audioTrack)}return this.store.massSubscribe(r.filter(d=>!d.error).map(d=>({userId:d.user.uid,type:d.mediaType})),void 0,Date.now()),r.forEach(d=>{var l;Z.subscribe(this.store.sessionId,{succ:!!d.error,ec:((l=d.error)===null||l===void 0?void 0:l.code)||null,video:d.mediaType===q.VIDEO,audio:d.mediaType===q.AUDIO,peerid:d.user.uid,subscribeRequestid:d.mediaType===q.VIDEO?d.user._videoSSRC:d.user._audioSSRC,p2pid:this.store.p2pId,eventElapse:Math.floor(performance.now()-e),preSsrc:this._p2pChannel.isPreSubScribe(d.user._videoSSRC)},!0)}),_.info("[".concat(this._clientId,"] massSubscribe success ").concat(t.map(d=>{let{user:l,mediaType:u}=d;return"user: ".concat(l==null?void 0:l.uid,", mediaType: ").concat(u)}).join("; "))),r}catch(c){throw yield this._p2pChannel.massUnsubscribeNoLock(t),c}}finally{o(),n()}})}unsubscribe(t,e,i){return C(this,null,function*(){if(!(t instanceof Co)){const o=this.remoteUsers.find(s=>s.uid===t);if(!o)throw new P(v.INVALID_REMOTE_USER,"user is not in the channel");t=o}if(e||this.store.useP2P){if(e==="datachannel")return this._unsubscribeDataChannel(t,i)}else yield this._unsubscribeDataChannel(t,i);if(e&&Ae(e,"mediaType",["audio","video"]),!this._joinInfo)throw new P(v.INVALID_OPERATION,"Can't unsubscribe stream, haven't joined yet!");if(!this._users.find(o=>o===t)){const o=new P(v.INVALID_REMOTE_USER,"user is not in the channel");throw _.error("[".concat(this._clientId,"] can not unsubscribe ").concat(t.uid,", user is not in the channel")),o}_.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(t.uid,", mediaType: ").concat(e));const r=yield this._subscribeMutex.lock();try{if(this.store.useP2P)yield this._p2pChannel.unsubscribe(t,e);else{const o=yield this._p2pChannel.unsubscribe(t,e);o&&(yield this._gateway.unsubscribe(o,t.uid)),e&&e!=="audio"||(t._audio_pre_subscribed=!1),e&&e!=="video"||(t._video_pre_subscribed=!1),t._is_pre_created&&cu(this._users,t),_.info("[".concat(this._clientId,"] unsubscribe success uid: ").concat(t.uid,", mediaType: ").concat(e))}}catch(o){if(o.code===v.DISCONNECT_P2P)return void _.warning("disconnecting p2p, abort unsubscribe request.");throw _.error("[".concat(this._clientId,"] unsubscribe user ").concat(t.uid," error"),o.toString()),o}finally{r()}})}_unsubscribeDataChannel(t,e){return C(this,null,function*(){if(e&&xt(e,"id",0,65535,!0),!this._joinInfo)throw new P(v.INVALID_OPERATION,"Can't unsubscribe datachannel, haven't joined yet!");if(!this._users.find(r=>r===t)){const r=new P(v.INVALID_REMOTE_USER,"user is not in the channel");throw _.error("[".concat(this._clientId,"] can not unsubscribe ").concat(t.uid,", user is not in the channel")),r}let n;if(typeof e=="number"){const r=t._dataChannels.find(o=>o.id===e);r&&(n=[r])}else n=t._dataChannels;if(n===void 0){const r=new P(v.REMOTE_USER_IS_NOT_PUBLISHED);throw _.error("[".concat(this._clientId,"] can not unsubscribe ").concat(t.uid," with channelId ").concat(e,", remote datachannel is not published")),r}_.info("[".concat(this._clientId,"] unsubscribe uid: ").concat(t.uid,", mediaType: datachannel, ids: ").concat(n.map(r=>r.id)));try{const r=yield this._p2pChannel.unsubscribeDataChannel(t,n);r&&(yield this._gateway.unsubscribeDataChannel(r,t.uid)),_.info("[".concat(this._clientId,"] unsubscribe datachannel success uid: ").concat(t.uid,", mediaType: datachannel, ids: ").concat(r))}catch(r){if(r.code===v.DISCONNECT_P2P)return void _.warning("disconnecting p2p, abort unsubscribe request.");throw _.error("[".concat(this._clientId,"] unsubscribe user ").concat(t.uid," error"),r.toString()),r}})}massUnsubscribe(t){return C(this,null,function*(){if(Br(t,"unsubscribeList"),!this._joinInfo)throw new P(v.INVALID_OPERATION,"Can't unsubscribeAll stream, haven't joined yet!");_.info("[".concat(this._clientId,"] start massUnsubscribe ").concat(t.map(i=>{let{user:n,mediaType:r}=i;return"user: ".concat(n==null?void 0:n.uid,", mediaType: ").concat(r,";")}).join())),t=[...t];const e=new Map;for(let i=t.length-1;i>=0;i--){const{user:n,mediaType:r}=t[i];if(!n){const a=new P(v.INVALID_PARAMS,"user property does not exist in unsubscribeList item");throw _.error("[".concat(this._clientId,"] user property does not exist in unsubscribeList item")),a}if(Ae(r,"mediaType",["video","audio",void 0]),!this._users.find(a=>a===n)){_.warning("[".concat(this._clientId,"] can not unsubscribe ").concat(n.uid,", user is not in the channel")),t.splice(i,1);continue}const s=Ne.Video|Ne.LwoVideo;if(e.has(n)){const a=e.get(n);let c;switch(r){case"video":c=a&s;break;case"audio":c=a&Ne.Audio;break;default:c=a&(Ne.Audio|s)}if(c){_.warning("[".concat(this._clientId,"] repeat massUnsubscribe user:").concat(n.uid,",mediaType:").concat(r," twice.")),t.splice(i,1);continue}r?r==="audio"?e.set(n,a|Ne.Audio):r==="video"&&e.set(n,a|s):e.set(n,a|Ne.Audio|s)}else r?r==="audio"?e.set(n,Ne.Audio):r==="video"&&e.set(n,s):e.set(n,Ne.Audio|s)}try{const i=yield this._p2pChannel.massUnsubscribe(t);i&&(yield this._gateway.massUnsubscribe(i)),_.info("[".concat(this._clientId,"] massUnsubscribe success ").concat(t.map(n=>{let{user:r,mediaType:o}=n;return"user: ".concat(r==null?void 0:r.uid,", mediaType: ").concat(o,";")}).join()))}catch(i){if(i.code===v.DISCONNECT_P2P)return void _.warning("[".concat(this._clientId,"] disconnecting p2p, abort unsubscribe request."));throw _.error("[".concat(this._clientId,"] massUnsubscribe error"),i.toString()),i}})}setLowStreamParameter(t){return C(this,null,function*(){(function(i){if(!i)throw new k(v.INVALID_PARAMS);re(i.width)||DE(i.width,"streamParameter.width"),re(i.height)||DE(i.height,"streamParameter.height"),re(i.framerate)||DE(i.framerate,"streamParameter.framerate"),re(i.bitrate)||xt(i.bitrate,"streamParameter.bitrate")})(t),(!t.width&&t.height||t.width&&!t.height)&&_.warning("[".concat(this._clientId,"] The width and height parameters take effect only when both are set")),_.info("[".concat(this._clientId,"] set low stream parameter to"),JSON.stringify(t));const e=this._configDistribute.getLowStreamConfigDistribute();if(e&&e.bitrate&&t.bitrate&&e.bitrate<t.bitrate&&(t.bitrate=e.bitrate),this._lowStreamParameter=t,this._isDualStreamEnabled)return this._p2pChannel.updateVideoStreamParameter(t,V.LocalVideoLowTrack)})}enableDualStream(){return C(this,null,function*(){if(!Ct().supportDualStream)throw Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),new P(v.NOT_SUPPORTED,"Your browser is not support dual stream");if(this._isDualStreamEnabled)throw new P(v.INVALID_OPERATION,"Dual stream is already enabled");if(this._p2pChannel.canPublishLowStream())try{yield this._publishLowStream()}catch(t){throw Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!1}),t}this._isDualStreamEnabled=!0,Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!0,succ:!0}),_.info("[".concat(this._clientId,"] enable dual stream"))})}disableDualStream(){return C(this,null,function*(){if(this._isDualStreamEnabled){if(!this._joinInfo)throw new P(v.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this._p2pChannel.getLocalMedia(V.LocalVideoLowTrack))try{const t=yield this._p2pChannel.unpublishLowStream();t&&(yield this._gateway.unpublish(t,this._joinInfo.stringUid||this._joinInfo.uid))}catch(t){throw Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!1}),t}this._isDualStreamEnabled=!1,Z.streamSwitch(this._sessionId,{lts:Date.now(),isdual:!1,succ:!0}),_.info("[".concat(this._clientId,"] disable dual stream"))}})}setClientRole(t,e){return C(this,null,function*(){if(function(n){Ae(n,"role",["audience","host"])}(t),e&&ME(e),this.mode==="rtc"||this.mode==="p2p")throw _.warning("[".concat(this._clientId,"]").concat(this.mode," mode can not use setClientRole")),new P(v.INVALID_OPERATION,"".concat(this.mode," mode can not use setClientRole"));if(e&&e.level&&t==="host")throw new P(v.INVALID_OPERATION,"host mode can not set audience latency level");if(t==="audience"&&this._p2pChannel.hasLocalMedia())throw new P(v.INVALID_OPERATION,"can not set client role to audience when publishing stream");const i=this._config.role;this._joinInfo&&(this._joinInfo.role=t),t!==i&&y("ENABLE_ROLE_SELECT_EDGE")?(this._gateway.updateClientRole(t,e),this._config.role=t,this._gateway.reconnect("recover",Ge.REGIONAL_DISTRIBUTION)):(yield this._gateway.setClientRole(t,e),this._config.role=t),_.info("[".concat(this._clientId,"] set client role to ").concat(t,", level: ").concat(e&&e.level))})}_setClientRoleOptions(t){return C(this,null,function*(){if(this.mode==="rtc"||this.mode==="p2p"||this._config.role!=="audience"||this._p2pChannel.hasLocalMedia())return;let e=!1;try{t&&ME(t),yield this._gateway.setClientRole(this._config.role,t),e=!0}catch(i){}finally{_.info("[".concat(this._clientId,"] set client role options ").concat(e?"succeed":"failed",", options is ").concat(t))}})}getRemoteInboundOffset(){var t;const e=(t=this._p2pChannel.getStats())===null||t===void 0?void 0:t.audioSend[0];if(!e||!e.timestamp)return 0;const i=e.timestamp-Date.now();return Math.abs(i)>1e3+e.rttMs+100?this.ntpAlignErrorCount+=1:this.ntpAlignErrorCount=0,this.ntpAlignErrorCount>=3?i:0}getNtpWallTimeInMs(){return document.visibilityState==="visible"&&(this.remoteInboundOffset=this.getRemoteInboundOffset()),this.remoteInboundOffset+Date.now()+this._gateway.ntpOffset}setProxyServer(t,e){if(Me(t,"proxyServer"),!e){if(this.connectionState!=="DISCONNECTED")throw new P(v.INVALID_OPERATION,"Set proxy server before join channel");if(this._cloudProxyServerMode!=="disabled"||this._useLocalAccessPoint)throw new P(v.INVALID_OPERATION,"You have already set the proxy")}this._proxyServer=t,Z.setProxyServer(this._proxyServer),_.setProxyServer(this._proxyServer),_.info("[".concat(this._clientId,"] Set proxy server ").concat(e?"by initialize call":""," success."))}setTurnServer(t,e){if(Array.isArray(t)||(t=[t]),!e){if(this.connectionState!=="DISCONNECTED")throw new P(v.INVALID_OPERATION,"Set turn server before join channel");if(this._cloudProxyServerMode!=="disabled"||this._useLocalAccessPoint)throw new P(v.INVALID_OPERATION,"You have already set the proxy")}if(Nc(t))return this._turnServer={servers:t,mode:"original-manual"},void _.info("[".concat(this._clientId,"] Set original turnserver ").concat(e?"by initialize call":""," success: ").concat(t.map(i=>i.urls).join(","),"."));t.forEach(i=>lI(i)),this._turnServer={servers:t,mode:"manual"},_.info("[".concat(this._clientId,"] Set turnserver ").concat(e?"by initialize call":""," success."))}setLicense(t){if(this.connectionState!=="DISCONNECTED")throw new P(v.INVALID_OPERATION,"you should set license before join channel");if(Me(t,"license",32,32),!/^[A-Za-z\d]+$/.test(t))throw new P(v.INVALID_PARAMS,"license should only contains characters from A-Z a-z 0-9");this._license=t,_.info("[".concat(this._clientId,"] set license success"),t)}startProxyServer(t){if(this.connectionState!=="DISCONNECTED")throw new P(v.INVALID_OPERATION,"Start proxy server before join channel");if(this._proxyServer||this._turnServer.mode==="manual"||this._useLocalAccessPoint)throw new P(v.INVALID_OPERATION,"You have already set the proxy");const e=[3,4,5];let i;switch(t===void 0&&(t=3),t){case 1:case 2:throw new P(v.NOT_SUPPORTED,"proxy mode 1/2 has been deprecated and not supported.");case 3:i="proxy3";break;case 4:i="proxy4";break;case 5:i="proxy5";break;default:throw new P(v.INVALID_PARAMS,"proxy server mode must be ".concat(e.join("|")))}this._cloudProxyServerMode=i,this.store.cloudProxyServerMode=i,_.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode)}stopProxyServer(){if(this.connectionState!=="DISCONNECTED")throw new P(v.INVALID_OPERATION,"Stop proxy server after leave channel");Z.setProxyServer(),_.setProxyServer(),this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled",_.info("[".concat(this._clientId,"] set cloud proxy server mode to"),this._cloudProxyServerMode),this._proxyServer=void 0,this._turnServer={mode:"auto",servers:[]}}setLocalAccessPointsV2(t){if(!t.accessPoints)throw new P(v.INVALID_PARAMS,"accessPoints is required.");Br(t.accessPoints.serverList,"accessPoints.serverList"),Me(t.accessPoints.domain,"accessPoints.domain");const e=(h,p)=>{xt(h,p,0,65535,!0)};let i=443;if(t.accessPoints.port&&(e(t.accessPoints.port,"accessPoints.port"),i=t.accessPoints.port),this._proxyServer||this._cloudProxyServerMode!=="disabled")throw new P(v.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");y("CLOSE_AFB_FOR_LOCAL_AP")&&(kt("JOIN_WITH_FALLBACK_SIGNAL_PROXY",!1),kt("JOIN_WITH_FALLBACK_MEDIA_PROXY",!1));const n=/^((\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=t.accessPoints.domain,o=t.accessPoints.serverList.map(h=>n.test(h)?"".concat(h.replace(/\./g,"-"),".").concat(r):h),s=o.map(h=>"".concat(h,":").concat(i));this._useLocalAccessPoint=!0,this._setLocalAPVersion=2,kt("WEBCS_DOMAIN",s),kt("WEBCS_DOMAIN_BACKUP_LIST",s),kt("GATEWAY_DOMAINS",[r]),t.report&&t.report.hostname&&Array.isArray(t.report.hostname)&&t.report.hostname.length?(Br(t.report.hostname,"report.hostname"),kt("EVENT_REPORT_DOMAIN",t.report.hostname[0]),kt("EVENT_REPORT_BACKUP_DOMAIN",t.report.hostname[1]||t.report.hostname[0])):(kt("EVENT_REPORT_DOMAIN",o[0]),kt("EVENT_REPORT_BACKUP_DOMAIN",o[1]||o[0]));let a=6443;t.report&&t.report.port&&(e(t.report.port,"report.port"),a=t.report.port),kt("STATS_COLLECTOR_PORT",a),t.report?kt("ENABLE_EVENT_REPORT",!0):kt("ENABLE_EVENT_REPORT",!1);let c="";t.log&&t.log.hostname&&Array.isArray(t.log.hostname)&&t.log.hostname.length?(Br(t.log.hostname,"log.hostname"),c=t.log.hostname[0]):c=o[0];let d=6444;t.log&&t.log.port&&(e(t.log.port,"log.port"),d=t.log.port),kt("LOG_UPLOAD_SERVER","".concat(c,":").concat(d));let l=[];t.cds&&t.cds.hostname&&Array.isArray(t.cds.hostname)&&t.cds.hostname.length?(Br(t.cds.hostname,"cds.hostname"),l=t.cds.hostname):l=o;let u=443;t.cds&&t.cds.port&&(e(t.cds.port,"cds.port"),u=t.cds.port),kt("CDS_AP",l.map(h=>"".concat(h,":").concat(u))),t.cds?kt("ENABLE_CONFIG_DISTRIBUTE",!0):kt("ENABLE_CONFIG_DISTRIBUTE",!1),_.info("set local access point v2 success")}setLocalAccessPoints(t,e){if(Br(t,"serverList"),Me(e,"domain"),this._proxyServer||this._cloudProxyServerMode!=="disabled")throw new P(v.INVALID_OPERATION,"set local access point failed, You have already set the cloud proxy");const i=/^(\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])$/;t=t.map(n=>i.test(n)?"".concat(n.replace(/\./g,"-"),".").concat(e):n),this._useLocalAccessPoint=!0,this._setLocalAPVersion=1,kt("WEBCS_DOMAIN",t),kt("WEBCS_DOMAIN_BACKUP_LIST",t),kt("GATEWAY_DOMAINS",[e]),kt("EVENT_REPORT_DOMAIN",t[0]),kt("EVENT_REPORT_BACKUP_DOMAIN",t[1]||t[0]),kt("LOG_UPLOAD_SERVER","".concat(t[0],":6444")),_.info("[".concat(this._clientId,"] set local access point success"))}setRemoteDefaultVideoStreamType(t){return C(this,null,function*(){if(Ae(t,"streamType",[0,1,4,5,6,7,8,9]),this._remoteDefaultVideoStreamType=t,this._joinInfo)try{yield this._gateway.setDefaultRemoteVideoStreamType(t),this._joinInfo.defaultVideoStream=this._remoteDefaultVideoStreamType}catch(e){throw _.error("[".concat(this._clientId,"] set default remote video stream type error"),e.toString()),e}else _.debug("[".concat(this._clientId,"] haven't joined yet, cache remoteDefaultVideoStreamType ").concat(t))})}setRemoteVideoStreamType(t,e){return C(this,null,function*(){Ae(e,"streamType",[0,1,4,5,6,7,8,9]);try{yield this._gateway.setRemoteVideoStreamType(t,e),setTimeout(()=>{const i=this._users.find(n=>n.uid===t);i&&i.videoTrack&&i.videoTrack.updateMediaStreamTrackResolution()},2e3)}catch(i){throw _.error("[".concat(this._clientId,"] set remote video stream type error"),i.toString()),i}_.info("[".concat(this._clientId,"] set remote ").concat(t," video stream type to ").concat(e)),this._remoteStreamTypeCacheMap.set(t,e)})}setStreamFallbackOption(t,e){return C(this,null,function*(){Ae(e,"fallbackType",[0,1,2,3,4,5,6,7,8]);try{yield this._gateway.setStreamFallbackOption(t,e)}catch(i){throw _.error("[".concat(this._clientId,"] set stream fallback option"),i.toString()),i}_.info("[".concat(this._clientId,"] set remote ").concat(t," stream fallback type to ").concat(e)),this._streamFallbackTypeCacheMap.set(t,e)})}setEncryptionConfig(t,e,i,n){(function(o){Ae(o,"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"])})(t),Me(e,"secret");const r=["aes-128-gcm2","aes-256-gcm2"];if(G(r).call(r,t)){if(!i||!(i instanceof Uint8Array&&i.length===32))throw new P(v.INVALID_PARAMS,"salt must be an Uint8Array and exactly equal to 32 bytes")}else if(i)throw new P(v.INVALID_PARAMS,"current encrypt mode does not need salt");if(n){if(Fr(n,"encryptDataStream"),!G(r).call(r,t))throw new P(v.INVALID_PARAMS,"current encrypt mode does not support data stream");this._encryptDataStream=!0}new RegExp(`^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*,.<>?/:;'"|{}\\[\\]])(?=.{8,})`).test(e)||_.warning(`The secret is not strong:
The secret must contain at least 1 lowercase alphabetical character,
The secret must contain at least 1 uppercase alphabetical character,
The secret must contain at least 1 numeric character,
The secret must contain at least one special character,
The secret must be eight characters or longer.
`),this._encryptionMode=t,this._encryptionSecret=e,i&&(this._encryptionSalt=Eo(i))}renewToken(t){return C(this,null,function*(){if(Me(t,"token",1,2047),!this._key||!this._joinInfo)throw new P(v.INVALID_OPERATION,"renewToken should not be called before user join");const e=this._key;this._key=t,this._joinInfo&&(this._joinInfo.token=t);const i=yield this._renewTokenMutex.lock();try{if(y("USE_NEW_TOKEN")){_.debug("[".concat(this._clientId,"] start renew token with ticket from unilbs"));const n=yield IW(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ge);_.debug("[".concat(this._clientId,"] get ticket from unilbs success")),yield this._gateway.renewToken({token:t,ticket:n})}else _.debug("[".concat(this._clientId,"] start renew token without ticket")),yield this._gateway.renewToken({token:t});_.debug("[".concat(this._clientId,"] renewToken success"))}catch(n){throw this._key=e,this._joinInfo.token=e,_.error("[".concat(this._clientId,"] renewToken failed"),n.toString()),n}finally{i()}})}enableAudioVolumeIndicator(){this._audioVolumeIndicationInterval?_.warning("you have already enabled audio volume indicator!"):this._audioVolumeIndicationInterval=window.setInterval(()=>{const t=this._p2pChannel.getAudioLevels();this.safeEmit(_t.VOLUME_INDICATOR,t)},y("AUDIO_VOLUME_INDICATION_INTERVAL")||2e3)}getRTCStats(){const t=this._statsCollector.getRTCStats(),e=this._gateway.getInChannelInfo();return t.Duration=Math.round(e.duration/1e3),t}startLiveStreaming(t,e){return C(this,null,function*(){if(!e){if(this.codec!=="h264")throw new P(v.LIVE_STREAMING_INVALID_RAW_STREAM,"raw streaming is only support h264");if(!this._p2pChannel.hasLocalMedia())throw new P(v.LIVE_STREAMING_INVALID_RAW_STREAM,"can not find stream to raw streaming")}if(this._liveRawStreamingClient&&this._liveRawStreamingClient.hasUrl(t)||this._liveTranscodeStreamingClient&&this._liveTranscodeStreamingClient.hasUrl(t))throw new P(v.LIVE_STREAMING_TASK_CONFLICT);const i=e?Gr.TRANSCODE:Gr.RAW;return this._createLiveStreamingClient(i).startLiveStreamingTask(t,i)})}setLiveTranscoding(t){return this._createLiveStreamingClient(Gr.TRANSCODE).setTranscodingConfig(t)}stopLiveStreaming(t){return C(this,null,function*(){const e=[this._liveRawStreamingClient,this._liveTranscodeStreamingClient].filter(i=>i&&i.hasUrl(t));if(!e.length)throw new P(v.INVALID_PARAMS,"can not find live streaming url to stop");yield K.all(e.map(i=>i&&i.stopLiveStreamingTask(t)))})}startChannelMediaRelay(t){return C(this,null,function*(){zw(t),yield this._createChannelMediaRelayClient().startChannelMediaRelay(t)})}updateChannelMediaRelay(t){return C(this,null,function*(){zw(t),yield this._createChannelMediaRelayClient().updateChannelMediaRelay(t)})}stopChannelMediaRelay(){return C(this,null,function*(){yield this._createChannelMediaRelayClient().stopChannelMediaRelay(),this._statsCollector.onStatsChanged&&(this._statsCollector.onStatsChanged=void 0)})}sendAudioMetadata(t){this._p2pChannel instanceof Zc&&this._p2pChannel.addAudioMetadata(t)}sendStreamMessage(e){return C(this,arguments,function*(t){var i;let n=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!this._joinInfo)throw new P(v.INVALID_OPERATION,"can not send data stream, not joined");if((typeof t=="string"||t instanceof Uint8Array)&&(t={payload:t}),typeof t.payload=="string"){const o=new TextEncoder;t.payload=o.encode(t.payload)}let r=!1;if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&G(i=["aes-128-gcm2","aes-256-gcm2"]).call(i,this._encryptionMode)&&(r=!0,t.payload=yield function(o,s,a){return C(this,null,function*(){var c;const d=Tn(c=Array.from(a)).call(c,(f,T)=>f+T,0),l={serverTs:0,seq:YG++,length:a.length,checkSum:d},u=new Uint8Array(gI(d,2)),h=new ArrayBuffer(ca),p=new DataView(h);p.setUint32(0,l.serverTs),p.setUint16(4,l.seq),p.setUint16(6,l.length),p.setUint16(8,l.checkSum);const g=16-a.length%16;a=pI(a,new Uint8Array(g));const m=yield window.crypto.subtle.encrypt({name:"AES-GCM",iv:o,tagLength:DI,additionalData:u},s,a);return pI(new Uint8Array(h),new Uint8Array(m))})}(this._encryptDataStreamIv,this._encryptDataStreamKey,t.payload)),new Blob([t.payload]).size>1024)throw new P(v.INVALID_PARAMS,r?"encrypted stream message out of range.":"stream message out of range.");return this._gateway.signal.request(nt.DATA_STREAM,{payload:Eo(t.payload),syncWithAudio:t.syncWithAudio,sendTs:Date.now()-kW},!n)})}sendMetadata(t){if(!this._joinInfo)throw new P(v.INVALID_OPERATION,"can not send metadata, not joined");if(new Blob([t]).size>1024)throw new P(v.METADATA_OUT_OF_RANGE);return this._gateway.signal.request(nt.SEND_METADATA,{session_id:this._joinInfo.sid,metadata:Eo(t)})}sendCustomReportMessage(t){return C(this,null,function*(){if(Array.isArray(t)||(t=[t]),t.forEach(e3),!this._joinInfo)throw new P(v.INVALID_OPERATION,"can not send custom report, not joined");yield Z.sendCustomReportMessage(this._joinInfo.sid,t)})}getLocalAudioStats(){return this._statsCollector.getLocalAudioTrackStats()}getRemoteAudioStats(){return this._statsCollector.getRemoteAudioTrackStats()}getLocalVideoStats(){return this._statsCollector.getLocalVideoTrackStats()}getRemoteVideoStats(){return this._statsCollector.getRemoteVideoTrackStats()}getRemoteNetworkQuality(){return this._statsCollector.getRemoteNetworkQualityStats()}pickSVCLayer(t,e){return C(this,null,function*(){Ae(e.spatialLayer,"spatialLayer",[0,1,2,3]),Ae(e.temporalLayer,"temporalLayer",[0,1,2,3]);try{yield this._gateway.pickSVCLayer(t,e)}catch(i){throw _.error("[".concat(this._clientId,"] pick SVC layer failed"),i.toString()),i}})}setRTMConfig(t){return C(this,null,function*(){const{apRTM:e=!1,rtmFlag:i}=t;if(Fr(e,"apRTM"),xt(i,"rtmFlag",0),this._rtmConfig.apRTM=e,this._rtmConfig.rtmFlag=i,_.debug("[".concat(this._clientId,"] setRTMconfig ").concat(JSON.stringify(t)," in ").concat(this.connectionState," state")),(this.connectionState==="CONNECTED"||this.connectionState==="RECONNECTING")&&this._joinInfo)return this._joinInfo.apRTM=e,this._joinInfo.rtmFlag=i,this._gateway.setRTM2Flag(i)})}_reset(){if(_.debug("[".concat(this._clientId,"] reset client")),function(t){const e=Ra.indexOf(t);e!==-1&&Ra.splice(e,1)}(this._clientId),this.store.hasStartJoinChannel=!1,this.store.isABTestSuccess=!1,this._axiosCancelSource.cancel(),this._axiosCancelSource=Ti.CancelToken.source(),this._streamFallbackTypeCacheMap=new Map,this._remoteStreamTypeCacheMap=new Map,this._configDistribute.stopGetConfigDistribute(),this._joinInfo&&R0(this._joinInfo),this._joinInfo=void 0,this._proxyServer=void 0,this._defaultStreamFallbackType=void 0,this._sessionId&&Z.removeSid(this._sessionId),this._sessionId=null,this.store.sessionId=null,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(t=>{t._audioTrack&&t._audioTrack._destroy(),t._videoTrack&&t._videoTrack._destroy(),t._dataChannels&&(t._dataChannels.forEach(e=>e._close()),t._dataChannels.length=0)}),this._users=[],this._audioVolumeIndicationInterval&&(window.clearInterval(this._audioVolumeIndicationInterval),this._audioVolumeIndicationInterval=void 0),this._cloudProxyServerMode==="fallback"&&(this._cloudProxyServerMode="disabled",this.store.cloudProxyServerMode="disabled"),this._p2pChannel.reset(),this._publishMutex=new qe("client-publish",this._clientId),this._subscribeMutex=new qe("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(t){}if(this._moderation)try{this.setImageModeration(!1)}catch(t){}}_startSession(t,e){var i;const n=t||Zo();t?_.debug("[".concat(this._clientId,"] new Session ").concat(n)):_.debug("[".concat(this._clientId,"] renewSession ").concat(this._sessionId," => ").concat(n));const r=t?"":this._sessionId||"";this._sessionId=n,this.store.sessionId=n,Z.addSid(n);const o={lts:new Date().getTime(),mode:this.mode,buildFormat:1,stringUid:(e==null?void 0:e.stringUid)||((i=this._joinInfo)===null||i===void 0?void 0:i.stringUid),channelProfile:this.mode==="live"?1:0,channelMode:0,isABTestSuccess:Number(this._configDistribute.isSuccess),lsid:r,clientRole:this.role==="audience"?2:1};Z.sessionInit(this._sessionId,xn({cname:e.channel,appid:e.appId},o)),this._joinInfo&&(this._joinInfo.sid=n),this._gateway.joinInfo&&(this._gateway.joinInfo.sid=n)}_publishHighStream(t){return C(this,null,function*(){if(!this._joinInfo||this._uid===void 0)throw new P(v.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));if(this._turnServer.mode==="auto"&&y("FORCE_TURN")&&!y("TURN_ENABLE_TCP")&&!y("TURN_ENABLE_UDP"))throw new P(v.UNEXPECTED_ERROR,"force TURN With No TURN Configuration");_.debug("[".concat(this._clientId,"] publish high stream"));try{const i=yield this._p2pChannel.publish(t,this._isDualStreamEnabled,this._lowStreamParameter);if(this.store.useP2P){const n=(yield i.next()).value;if(n){try{yield this._gateway.sendExtensionMessage(he.PUBLISH,n,!0)}catch(r){throw i.throw(r),r}yield i.next()}this._p2pChannel.reportPublishEvent(!0,null)}else{const n=(yield i.next()).value;if(n){var e;let r;try{r=yield this._gateway.publish(this._uid,n,!0)}catch(o){if(o.code!==v.DISCONNECT_P2P)throw i.throw(o),o}yield i.next(((e=r)===null||e===void 0?void 0:e.ortc)||[])}this._p2pChannel.reportPublishEvent(!0,null);for(const r of t)r instanceof Yt&&r._encoderConfig&&this._gateway.setVideoProfile(r._encoderConfig).catch(o=>{_.debug("[".concat(this._clientId,"] stop setVideoProfile, because websocket is closed"))}),!r.muted&&r.enabled||(yield this._p2pChannel.muteLocalTrack(r))}}catch(i){if(this._p2pChannel.reportPublishEvent(!1,i==null?void 0:i.code,t),(i==null?void 0:i.code)===v.WS_ABORT)return;throw i}})}_publishLowStream(){return C(this,null,function*(){if(!this._joinInfo||this._uid===void 0)throw new P(v.INVALID_OPERATION,"Can't publish stream, haven't joined yet!");if(this.connectionState!=="CONNECTED"&&this.connectionState!=="RECONNECTING")throw new P(v.INVALID_OPERATION,"can not publish stream in ".concat(this.connectionState," state"));_.debug("[".concat(this._clientId,"] publish low stream"));const t=this._configDistribute.getLowStreamConfigDistribute();t&&t.bitrate&&(this._lowStreamParameter||(this._lowStreamParameter={width:160,height:120,framerate:15,bitrate:50}),this._lowStreamParameter&&this._lowStreamParameter.bitrate&&t.bitrate<this._lowStreamParameter.bitrate&&(this._lowStreamParameter.bitrate=t.bitrate));try{const i=yield this._p2pChannel.publishLowStream(this._lowStreamParameter),n=(yield i.next()).value;if(n){var e;let r;try{r=yield this._gateway.publish(this._uid,n,!0)}catch(o){if(o.code!==v.DISCONNECT_P2P)throw i.throw(o),o}i.next(((e=r)===null||e===void 0?void 0:e.ortc)||[]),this._p2pChannel.reportPublishEvent(!0,null,void 0,!0)}}catch(i){if(this._p2pChannel.reportPublishEvent(!1,i==null?void 0:i.code,void 0,!0),(i==null?void 0:i.code)===v.WS_ABORT)return;throw i}})}_createLiveStreamingClient(t){const e=()=>{if(!this._joinInfo||!this._appId)return new P(v.INVALID_OPERATION,"can not create live streaming client, please join channel first").throw();const i=(n={joinInfo:this._joinInfo,appId:this._appId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig},Kr("LiveStreaming").create(n));var n;return i.onLiveStreamError=(r,o)=>{Z.reportApiInvoke(this._sessionId,{name:_e.ON_LIVE_STREAM_ERROR,options:[r,o],tag:oe.TRACER}).onSuccess(),this.safeEmit(_t.LIVE_STREAMING_ERROR,r,o)},i.onLiveStreamWarning=(r,o)=>{Z.reportApiInvoke(this._sessionId,{name:_e.ON_LIVE_STREAM_WARNING,options:[r,o],tag:oe.TRACER}).onSuccess(),this.safeEmit(_t.LIVE_STREAMING_WARNING,r,o)},i.on(Am.REQUEST_WORKER_MANAGER_LIST,(r,o,s)=>{if(!this._joinInfo)return s(new P(v.INVALID_OPERATION,"can not find join info to get worker manager"));(function(a,c,d,l){return C(this,null,function*(){const u=y("UAP_AP").slice(0,y("AJAX_REQUEST_CONCURRENT")).map(h=>c.proxyServer?"https://".concat(c.proxyServer,"/ap/?url=").concat(h+"/api/v1?action=uap"):"https://".concat(h,"/api/v1?action=uap"));return yield SW(u,a,c,d,l)})})(r,this._joinInfo,this._axiosCancelSource.token,ge).then(o).catch(s)}),i};return t===Gr.RAW?(this._liveRawStreamingClient=this._liveRawStreamingClient||e(),this._liveRawStreamingClient):(this._liveTranscodeStreamingClient=this._liveTranscodeStreamingClient||e(),this._liveTranscodeStreamingClient)}_createChannelMediaRelayClient(){if(!this._joinInfo)return new P(v.INVALID_OPERATION,"can not create channel media relay client, please join channel first").throw();if(!this._channelMediaRelayClient){const{sendResolutionWidth:e,sendResolutionHeight:i}=this.getLocalVideoStats(),n=(t={joinInfo:this._joinInfo,clientId:this._clientId,websocketRetryConfig:this._config.websocketRetryConfig,httpRetryConfig:this._config.httpRetryConfig,resolution:{width:e,height:i}},Kr("ChannelMediaRelay").create(t));n.on("state",r=>{r===Di.RELAY_STATE_FAILURE&&n&&n.dispose(),this.safeEmit(_t.CHANNEL_MEDIA_RELAY_STATE,r)}),n.on("event",r=>{this.safeEmit(_t.CHANNEL_MEDIA_RELAY_EVENT,r)}),this._channelMediaRelayClient=n,this._statsCollector.onStatsChanged=(r,o)=>{var s;r==="resolution"&&((s=this._channelMediaRelayClient)===null||s===void 0||s.setVideoProfile(o))}}var t;return this._channelMediaRelayClient}_handleUpdateDataChannel(t,e){const{added:i,deleted:n}=t,r=[];if(e){const o=[];this._users.forEach(s=>{s._dataChannels.forEach(a=>{i.every(c=>c.uid!==s._uintid||c.stream_id!==a.id)&&o.push({uid:s._uintid,stream_id:a.id,ordered:a.ordered,max_retrans_times:a.maxRetransmits,metadata:a.metadata})})}),o.length>0&&this._handleUpdateDataChannel({added:[],deleted:o})}Array.isArray(i)&&i.length>0&&i.forEach(o=>{const{uid:s,stream_id:a,ordered:c,max_retrans_times:d,metadata:l}=o,u=this._users.find(h=>h._uintid===s);if(!u)return void _.error("[".concat(this._clientId,"] can not find target user!(on_add_data_channel)"));if(_.debug("[".concat(this._clientId,"] data_channel added with uid ").concat(s)),G(r).call(r,u)||r.push(u),u._uintid||(u._uintid=s),u._dataChannels.findIndex(h=>h.id===o.stream_id)===-1){const h={id:a,ordered:!!c,maxRetransmits:d,metadata:l},p=function(g){return Dw(g,!0)}(h);u._dataChannels.push(p),_.info("[".concat(this._clientId,"] remote user ").concat(u.uid," published datachannel")),e||this.safeEmit(_t.USER_PUBLISHED,u,"datachannel",h)}this._p2pChannel.hasPendingRemoteDataChannel(u,o.stream_id)&&(_.debug("[".concat(this._clientId,"] resubscribe datachannel for user ").concat(u.uid," after reconnect.")),this._subscribeDataChannel(u,o.stream_id).catch(h=>{_.error("[".concat(this._clientId,"] resubscribe datachannel error"),h.toString())}))}),e&&(this.safeEmit(_t.PUBLISHED_USER_LIST,this._pendingPublishedUsers),this._pendingPublishedUsers=[]),Array.isArray(n)&&n.length>0&&n.forEach(o=>{const{uid:s,stream_id:a}=o,c=this._users.find(l=>l._uintid===s);if(!c)return void _.error("[".concat(this._clientId,"] can not find target user!(on_delete_data_channel)"));const d=c._dataChannels.find(l=>l.id===o.stream_id);d&&(_.debug("[".concat(this._clientId,"] data_stream delete with uid ").concat(s)),this._p2pChannel.unsubscribeDataChannel(c,[d]).then(l=>{if(c._dataChannels=c._dataChannels.filter(u=>u!==d),l)return this._gateway.unsubscribeDataChannel(l,c.uid)}),_.info("[".concat(this._clientId,"] remote user ").concat(s," unpublished datachannel ,id:").concat(d.id)),this.safeEmit(_t.USER_UNPUBLISHED,c,"datachannel",d._config))})}_handleRemoveDataChannels(t){const e=this._users.find(i=>i.uid===t.uid);if(e){if(e._dataChannels!==void 0&&e._dataChannels.length>0){_.debug("[".concat(this._clientId,"] datachannel removed with uid ").concat(t.uid));const i=()=>{_.info("[".concat(this._clientId,"] remote user ").concat(e.uid," unpublished datachannel")),e._dataChannels.forEach(n=>{this.safeEmit(_t.USER_UNPUBLISHED,e,"datachannel",n._config)})};this._p2pChannel.unsubscribeDataChannel(e,e._dataChannels).then(n=>{if(n)return this._gateway.unsubscribeDataChannel(n,e.uid)}),i()}}else _.warning("[".concat(this._clientId,"] can not find target user!(on_remove_datachannel)"))}_handleGatewayEvents(){this._gateway.on(De.UPDATE_GATEWAY_CONFIG,()=>{(function(){let t;try{t=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void _.error("Error loading sdk config",e.message)}if(t)try{const e=JSON.parse(window.atob(t)),i=Date.now();Object.keys(e).forEach(n=>{const{value:r,type:o,expires:s}=e[n];s&&s<=i||o||Sm()||!Object.prototype.hasOwnProperty.call(_u,n)||(Qn[n]=r,Xt[n]=r,_.debug("Update gateway parameters from config distribute",n,r))})}catch(e){_.error("Error update config from local cache",e.message)}})()}),this._gateway.on(De.DISCONNECT_P2P,()=>C(this,null,function*(){yield this._p2pChannel.disconnectForReconnect()})),this._gateway.on(De.CONNECTION_STATE_CHANGE,(t,e,i)=>{var n;if(i===bt.FALLBACK)return;const r=()=>{this.safeEmit(_t.CONNECTION_STATE_CHANGE,t,e,i)};if(Z.reportApiInvoke(this._sessionId||((n=this._gateway.joinInfo)===null||n===void 0?void 0:n.sid)||null,{name:_e.CONNECTION_STATE_CHANGE,options:[t,e,i],tag:oe.TRACER}).onSuccess(JSON.stringify({cur:t,prev:e,reason:i})),_.info("[".concat(this._clientId,"] signal connection state change: ").concat(e," -> ").concat(t)),t==="DISCONNECTED")return this._reset(),void r();if(t==="RECONNECTING")this._users.forEach(s=>{s._trust_in_room_=!1,s._trust_audio_enabled_state_=!1,s._trust_video_enabled_state_=!1,s._trust_audio_mute_state_=!1,s._trust_video_mute_state_=!1,s._trust_audio_stream_added_state_=!1,s._trust_video_stream_added_state_=!1,s._is_pre_created||(s._audio_pre_subscribed||(s._audioSSRC=void 0,s._audioOrtc=void 0),s._video_pre_subscribed||(s._videoSSRC=void 0,s._videoOrtc=void 0,s._rtxSsrcId=void 0),s._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(t==="CONNECTED"){var o;this._streamFallbackTypeCacheMap.forEach((s,a)=>{this._gateway.setStreamFallbackOption(a,s).catch(c=>{_.warning("[".concat(this._clientId,"] auto set stream fallback option failed"),c)})}),this._remoteStreamTypeCacheMap.forEach((s,a)=>{this._gateway.setRemoteVideoStreamType(a,s).catch(c=>{_.warning("[".concat(this._clientId,"] auto set remote stream type failed"),c)})}),this._remoteDefaultVideoStreamType!==void 0&&((o=this._joinInfo)===null||o===void 0?void 0:o.defaultVideoStream)===void 0&&this.setRemoteDefaultVideoStreamType(this._remoteDefaultVideoStreamType).then(()=>{_.debug("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway connected"))}).catch(s=>{_.error("[".concat(this._clientId,"] setRemoteDefaultVideoStreamType after gateway failed, ").concat(s))}),this.store.useP2P||(this._p2pChannel.republish(),this._userOfflineTimeout=window.setTimeout(()=>{this.connectionState==="CONNECTED"&&(this._userOfflineTimeout=void 0,this._users.filter(s=>!s._trust_in_room_).forEach(s=>{_.debug("[".concat(this._clientId,"] user offline timeout, emit user offline ").concat(s.uid)),this._handleUserOffline({uid:s.uid})}))},3e3),this._streamRemovedTimeout=window.setTimeout(()=>{this.connectionState==="CONNECTED"&&(this._streamRemovedTimeout=void 0,this._users.forEach(s=>{s._trust_audio_mute_state_||(_.debug("[".concat(this._clientId,"] auto dispatch audio unmute event ").concat(s.uid)),this._handleMuteStream(s.uid,q.AUDIO,!1)),s._trust_video_mute_state_||(_.debug("[".concat(this._clientId,"] auto dispatch video unmute event ").concat(s.uid)),this._handleMuteStream(s.uid,q.VIDEO,!1)),s._trust_audio_enabled_state_||(_.debug("[".concat(this._clientId,"] auto dispatch enable local audio ").concat(s.uid)),this._handleSetStreamLocalEnable("audio",s.uid,!0)),s._trust_video_enabled_state_||(_.debug("[".concat(this._clientId,"] auto dispatch enable local video ").concat(s.uid)),this._handleSetStreamLocalEnable("video",s.uid,!0)),s._trust_video_stream_added_state_||(_.debug("[".concat(this._clientId,"] auto dispatch reset video stream added ").concat(s.uid)),this._handleResetAddStream(s,"video")),s._trust_audio_stream_added_state_||(_.debug("[".concat(this._clientId,"] auto dispatch reset audio stream added ").concat(s.uid)),this._handleResetAddStream(s,"audio")),s._video_added_||s._audio_added_||(_.debug("[".concat(this._clientId,"] auto dispatch stream remove ").concat(s.uid)),this._handleRemoveStream({uid:s.uid,uint_id:s._uintid}))}))},1e3))}r()}),this._gateway.on(De.REQUEST_NEW_GATEWAY_LIST,(t,e)=>C(this,null,function*(){if(!this._joinInfo)return e(new P(v.UNEXPECTED_ERROR,"can not recover, no join info"));try{let i;const n=yield S0(xn(xn({},this._joinInfo),{},{uid:this._joinInfo.uid,stringUid:void 0}));n?(i=n.ap,v0(n),this._joinInfo.preload=!0):(i=yield Wm(this._joinInfo,this._axiosCancelSource.token,this._config.httpRetryConfig||ge,this.store),this._joinInfo.preload=!1),this._joinInfo&&(this._joinInfo.apResponse=i.gatewayInfo.res,this._joinInfo.gatewayAddrs=i.gatewayInfo.gatewayAddrs,this._joinInfo.uni_lbs_ip=i.gatewayInfo.uni_lbs_ip);const r=[];i.gatewayInfo.gatewayAddrs.forEach(o=>{let{address:s}=o;const[a,c]=s.split(":");this._joinInfo&&this._joinInfo.proxyServer?r.push({proxy:this._joinInfo.proxyServer,host:a,port:c}):r.push({host:a,port:c})}),t(r)}catch(i){e(i)}})),this._gateway.on(De.NETWORK_QUALITY,t=>{this._networkQualitySensitivity==="normal"&&this.safeEmit(_t.NETWORK_QUALITY,t)}),this._gateway.on(De.STREAM_TYPE_CHANGE,(t,e)=>{this.safeEmit(_t.STREAM_TYPE_CHANGED,t,e),Z.reportApiInvoke(this._sessionId,{name:_e.STREAM_TYPE_CHANGE,options:[t,e],tag:oe.TRACER}).onSuccess(JSON.stringify({uid:t,streamType:e}))}),this._gateway.on(De.IS_P2P_DISCONNECTED,t=>{this._p2pChannel.isP2PDisconnected()?t(!0):this._p2pChannel.hasLocalMedia()||this._p2pChannel.hasRemoteMedia()?t(!1):t(!0)}),this._gateway.on(De.REQUEST_P2P_CONNECTION_PARAMS,(t,e,i)=>C(this,null,function*(){try{let n=yield this._p2pChannel.getEstablishParams();y("ENABLE_PREALLOC_PC")&&n||(n=yield this._p2pChannel.startP2PConnection(t)),e(n)}catch(n){i(n)}})),this._gateway.on(De.JOIN_RESPONSE,(t,e)=>{if(this.store.useP2P)return;let i;t.attributes?i=t.attributes.userAttributes.preSubSsrcs:_.debug("no attributes in joinResponse");const n=Sw(t.ortc,e,i);this._p2pChannel.connect(n)}),this._gateway.on(De.PRE_CONNECT_PC,t=>C(this,null,function*(){const{candidates:e,fingerprint:i}=t;if(this._joinInfo&&e.length>0&&!this._p2pChannel.isPlanB){var n;yield this._p2pChannel.startP2PConnection({turnServer:this._joinInfo.turnServer});const{cert:r,cid:o}=this._joinInfo.apResponse;yield this._p2pChannel.connect({iceParameters:{iceUfrag:"".concat(o,"_").concat(r),icePwd:"".concat(o,"_").concat(r)},dtlsParameters:{fingerprints:[{hashFunction:"sha-256",fingerprint:(n=y("FINGERPRINT"))!==null&&n!==void 0?n:i}]},candidates:e,rtpCapabilities:{send:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},recv:{audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]}},setup:"active",cname:"o/i14u9pJrxRKAsu",preallocation:!0})}}))}_handleGatewaySignalEvents(){this._gateway.signal.on(mt.ON_USER_ONLINE,this._handleUserOnline),this._gateway.signal.on(mt.ON_USER_OFFLINE,this._handleUserOffline),this._gateway.signal.on(mt.ON_ADD_AUDIO_STREAM,t=>this._handleAddAudioOrVideoStream("audio",t.uid,t.ssrcId,t.cname,t.uint_id,t.ortc)),this._gateway.signal.on(mt.ON_ADD_VIDEO_STREAM,t=>this._handleAddAudioOrVideoStream("video",t.uid,t.ssrcId,t.cname,t.uint_id,t.ortc,t.rtxSsrcId)),this._gateway.signal.on(mt.ON_REMOTE_DATASTREAM_UPDATE,t=>{this._handleUpdateDataChannel(t)}),this._gateway.signal.on(mt.ON_REMOTE_FULL_DATASTREAM_INFO,t=>{this._handleUpdateDataChannel({added:t.datastreams||[],deleted:[]},!0)}),this._gateway.signal.on(mt.ON_REMOVE_STREAM,this._handleRemoveStream),this._gateway.signal.on(mt.ON_P2P_LOST,this._handleP2PLost),this._gateway.signal.on(mt.MUTE_AUDIO,t=>this._handleMuteStream(t.uid,q.AUDIO,!0)),this._gateway.signal.on(mt.UNMUTE_AUDIO,t=>this._handleMuteStream(t.uid,q.AUDIO,!1)),this._gateway.signal.on(mt.MUTE_VIDEO,t=>this._handleMuteStream(t.uid,q.VIDEO,!0)),this._gateway.signal.on(mt.UNMUTE_VIDEO,t=>this._handleMuteStream(t.uid,q.VIDEO,!1)),this._gateway.signal.on(mt.RECEIVE_METADATA,t=>{const e=Qo(t.metadata);this.safeEmit(_t.RECEIVE_METADATA,t.uid,e)}),this._gateway.signal.on(mt.ON_DATA_STREAM,t=>C(this,null,function*(){var e;if(!t)return;let i=Qo(t.payload);if(this._encryptDataStream&&this._encryptDataStreamIv&&this._encryptDataStreamKey&&window.crypto.subtle&&G(e=["aes-128-gcm2","aes-256-gcm2"]).call(e,this._encryptionMode)){if(t.payload.length<ca)throw new P(v.UNEXPECTED_RESPONSE,"payload length ".concat(t.payload.length," is less than header length ").concat(ca));i=yield function(o,s,a){return C(this,null,function*(){const c=a.subarray(0,ca),d=c.slice(8,ca),l=(d[0]<<8)+d[1],u=(c[6]<<8)+c[7],h=yield window.crypto.subtle.decrypt({name:"AES-GCM",iv:o,tagLength:DI,additionalData:new Uint8Array(gI(l,2))},s,a.subarray(ca));return new Uint8Array(h).subarray(0,u)})}(this._encryptDataStreamIv,this._encryptDataStreamKey,i)}let n=0;if(t.ordered||t.syncWithAudio){const r=this._p2pChannel.getStats(),o=this.remoteUsers.find(a=>a.uid===t.uid),s=r==null?void 0:r.audioRecv.find(a=>a.ssrc===(o==null?void 0:o._audioSSRC));n=s==null?void 0:s.jitterBufferMs}(n==null||Number.isNaN(n))&&(n=0),UW(xn(xn({},t),{},{payload:i}),n,{id:this._clientId,onStreamMessage:typeof this.onStreamMessage=="function"?this.onStreamMessage.bind(this):void 0,safeEmit:this.safeEmit.bind(this)})})),this._gateway.signal.on(mt.ON_CRYPT_ERROR,()=>{_o(()=>{_.warning("[".concat(this._clientId,"] on crypt error")),this.safeEmit(_t.CRYPT_ERROR)},this._sessionId)}),this._gateway.signal.on(mt.ON_TOKEN_PRIVILEGE_WILL_EXPIRE,this._handleTokenWillExpire),this._gateway.signal.on(mt.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{_.warning("[".concat(this._clientId,"] received message onTokenPrivilegeDidExpire, please get new token and join again")),this._gateway.leave(!0,bt.TOKEN_EXPIRE),this.safeEmit(_t.ON_TOKEN_PRIVILEGE_DID_EXPIRE),this._reset()}),this._gateway.signal.on(mt.ON_STREAM_FALLBACK_UPDATE,t=>{_.debug("[".concat(this._clientId,"] stream fallback peerId: ").concat(t.stream_id,", attr: ").concat(t.stream_type)),this.safeEmit(_t.STREAM_FALLBACK,t.stream_id,t.stream_type===1?"fallback":"recover")}),this._gateway.signal.on(mt.ON_PUBLISH_STREAM,t=>{this.uid===this._uid&&(this._p2pChannel.reportPublishEvent(!0,null,void 0,!1,JSON.stringify({proxy:t.proxy})),_.info("[".concat(this._clientId,"] on publish stream, ").concat(JSON.stringify(t))))}),this._gateway.signal.on(mt.ENABLE_LOCAL_VIDEO,t=>{this._handleSetStreamLocalEnable("video",t.uid,!0)}),this._gateway.signal.on(mt.DISABLE_LOCAL_VIDEO,t=>{this._handleSetStreamLocalEnable("video",t.uid,!1)}),this._gateway.signal.on(ot.REQUEST_TIMEOUT,(t,e)=>{if(this._joinInfo)switch(t){case nt.PUBLISH:{if(!e)return;const r=e.ortc;if(r){var i,n;const o=r.some(c=>{let{stream_type:d}=c;return d===Ot.Audio}),s=r.some(c=>{let{stream_type:d}=c;return d!==Ot.Audio}),a=r.some(c=>{let{stream_type:d}=c;return d===Ot.Screen||d===Ot.ScreenLow});e.state==="offer"&&Z.publish(this._joinInfo.sid,{eventElapse:Je.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:!1,ec:v.TIMEOUT,audio:o,video:s,p2pid:e.p2p_id,publishRequestid:this.store.pubId,screenshare:a,audioName:o?(i=r.find(c=>{let{stream_type:d}=c;return d===Ot.Audio}))===null||i===void 0||(i=i.ssrcs[0])===null||i===void 0?void 0:i.ssrcId.toString():void 0,videoName:s?(n=r.find(c=>{let{stream_type:d}=c;return d!==Ot.Audio}))===null||n===void 0||(n=n.ssrcs[0])===null||n===void 0?void 0:n.ssrcId.toString():void 0})}break}case nt.SUBSCRIBE:e&&Z.subscribe(this._joinInfo.sid,{succ:!1,ec:v.TIMEOUT,audio:e.stream_type===q.AUDIO,video:e.stream_type===q.VIDEO,peerid:e.stream_id,subscribeRequestid:e.ssrcId,p2pid:this.store.p2pId,eventElapse:Je.measureFromSubscribeStart(this.store.clientId,e.ssrcId),preSsrc:this._p2pChannel.isPreSubScribe(e.ssrcId)})}}),this._gateway.signal.on(mt.ON_P2P_OK,t=>{this.uid,this._uid}),this._gateway.signal.on(mt.ON_PUBLISHED_USER_LIST,t=>{if(t==null||!t.users)return;y("BLOCK_LOCAL_CLIENT")&&(t.users=t.users.filter(n=>!ss(n.string_id||n.stream_id,this.channelName)));const e=[],i=[];for(const n of t.users){let r=this._users.find(l=>l._uintid===n.stream_id);r?r._trust_in_room_=!0:(r=new Co(n.string_id||n.stream_id,n.stream_id),this._users.push(r),this.getListeners(_t.PUBLISHED_USER_LIST).length===0&&(_.debug("[".concat(this._clientId,"] user online"),n.stream_id),this.safeEmit(_t.USER_JOINED,r)));const o=Ne.Audio&n.stream_type,s=(Ne.Video|Ne.LwoVideo)&n.stream_type,a=(65280&n.stream_type)!=0,c=o&&r.hasAudio,d=s&&r.hasVideo;s&&(r._trust_video_stream_added_state_=!0,r._video_added_=!0,r._videoSSRC=n.video_ssrc,r._rtxSsrcId=n.video_rtx),o&&(r._trust_audio_stream_added_state_=!0,r._audio_added_=!0,r._audioSSRC=n.audio_ssrc),o&&!c&&this.getListeners(_t.PUBLISHED_USER_LIST).length===0&&(_.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published audio")),this.safeEmit(_t.USER_PUBLISHED,r,"audio")),s&&!d&&this.getListeners(_t.PUBLISHED_USER_LIST).length===0&&(_.info("[".concat(this._clientId,"] remote user ").concat(r.uid," published video")),this.safeEmit(_t.USER_PUBLISHED,r,"video")),(o&&!c||s&&!d||a)&&e.push(r),s&&this._p2pChannel.hasPendingRemoteMedia(r,"video")&&i.push({user:r,mediaType:"video"}),o&&this._p2pChannel.hasPendingRemoteMedia(r,"audio")&&i.push({user:r,mediaType:"audio"})}i.length>0&&(_.debug("[".concat(this._clientId,"] RE massSubscribe after reconnect ").concat(i.map(n=>"user: ".concat(n.user.uid,", mediaType: ").concat(n.mediaType)).join("; ")," ")),this.massSubscribe(i).catch(n=>{_.error("[".concat(this._clientId,"] mass resubscribe error"),n.toString())})),this.getListeners(_t.PUBLISHED_USER_LIST).length>0?y("ENABLE_DATASTREAM_2")?this._pendingPublishedUsers=e:(_.info("[".concat(this._clientId,"] client emit user-list event, users: ").concat(e.map(n=>n.uid).join(", "))),this.safeEmit(_t.PUBLISHED_USER_LIST,e)):_.info("[".concat(this._clientId,"] client not emit user-list event case there is no user-list listener, users: ").concat(e.map(n=>n.uid).join(", ")))}),this._gateway.signal.on(mt.ON_RTP_CAPABILITY_CHANGE,t=>{const{video_codec:e}=t;this._p2pChannel instanceof Zc&&this._p2pChannel.updateRemoteRTPCapabilities(e.map(i=>i.toLowerCase()).filter(i=>{var n;return G(n=Object.keys(Eu)).call(n,i)}))})}_handleP2PEvents(){this._gateway.signal.on(mt.ON_USER_OFFLINE,()=>{this._p2pChannel.disconnectForReconnect()}),this._gateway.signal.on(he.PUBLISH,(t,e,i)=>{const{uid:n}=t;t.forEach(r=>{const{kind:o,ssrcs:s,mid:a,isMuted:c}=r;this._handleP2PAddAudioOrVideoStream(o,n,s[0].ssrcId,a);const d=this._users.find(l=>l.uid===n);return d&&this.store.useP2P?this._p2pChannel.mockSubscribe(d,o,s[0].ssrcId,a).then(()=>{e()}).catch(i):e(),this._handleMuteStream(n,o,!!c)})}),this._gateway.signal.on(he.CALL,(t,e,i)=>C(this,null,function*(){if(this.store.useP2P)try{var n;e(yield this._p2pChannel.startP2P({turnServer:(n=this._joinInfo)===null||n===void 0?void 0:n.turnServer},t))}catch(r){i(r)}})),this._gateway.signal.on(ot.P2P_CONNECTION,t=>C(this,null,function*(){this.store.useP2P&&(yield this._p2pChannel).p2pConnect(t)})),this._gateway.signal.on(he.UNPUBLISH,(t,e,i)=>C(this,null,function*(){if(this.store.useP2P){const{unpubMsg:n,uid:r}=t,o=this._users.find(s=>s.uid===r);if(!o)return _.warning("[".concat(this._clientId,"] can not find remote user, ignore mute event, uid: ").concat(r)),void e();try{n.forEach(s=>C(this,null,function*(){let{stream_type:a}=s;const c=a===Ot.Audio?q.AUDIO:q.VIDEO;yield this._p2pChannel.unsubscribe(o,c),this._handleMuteStream(r,c,!0)})),e()}catch(s){i(s)}}})),this._gateway.signal.on(he.CONTROL,(t,e)=>C(this,null,function*(){const{action:i}=t;switch(i){case go.MUTE_LOCAL_VIDEO:this._handleMuteStream(e,q.VIDEO,!0);break;case go.MUTE_LOCAL_AUDIO:this._handleMuteStream(e,q.AUDIO,!0);break;case go.UNMUTE_LOCAL_VIDEO:this._handleP2PAddAudioOrVideoStream("video",e),this._handleMuteStream(e,q.VIDEO,!1);break;case go.UNMUTE_LOCAL_AUDIO:this._handleP2PAddAudioOrVideoStream("audio",e),this._handleMuteStream(e,q.AUDIO,!1)}})),this._gateway.signal.on(he.RESTART_ICE,(t,e,i)=>C(this,null,function*(){if(this.store.useP2P)try{const{direction:n,iceParameter:r}=t;n!==pi.SEND_ONLY||r?e(yield this._p2pChannel.restartICE(n,r)):(this._p2pChannel.handleDisconnect(n),e())}catch(n){i(n)}})),this._gateway.signal.on(he.CANDIDATE,t=>{if(this.store.useP2P){const{candidate:e,direction:i}=t;this._p2pChannel.addRemoteCandidate(e,i)}}),this._p2pChannel.on($.RequestP2PRestartICE,(t,e,i)=>C(this,null,function*(){try{const{direction:n}=t;e(yield this._gateway.sendExtensionMessage(he.RESTART_ICE,t,n===pi.SEND_ONLY))}catch(n){i(n)}})),this._p2pChannel.on($.LocalCandidate,t=>{this._gateway.sendExtensionMessage(he.CANDIDATE,JSON.stringify(t),!0)}),this._p2pChannel.on($.RequestP2PMuteLocal,(t,e,i)=>C(this,null,function*(){try{yield this._gateway.sendExtensionMessage(he.CONTROL,t,!0),e()}catch(n){i(n)}})),this._p2pChannel.on($.RequestP2PUnmuteRemote,(t,e,i)=>C(this,null,function*(){if(this._joinInfo)try{yield this._gateway.unmuteRemote(t,this._joinInfo.stringUid||this._joinInfo.uid),e()}catch(n){n.code===v.DISCONNECT_P2P?e():i(n)}else e()})),this._p2pChannel.on($.RequestP2PMuteRemote,(t,e,i)=>C(this,null,function*(){if(this._joinInfo)try{yield this._gateway.muteRemote(t,this._joinInfo.stringUid||this._joinInfo.uid),e()}catch(n){n.code===v.DISCONNECT_P2P?e():i(n)}else e()})),this._p2pChannel.on($.StateChange,(t,e)=>{e===wt.Connected&&this._p2pChannel.republish()})}_handleP2PChannelEvents(){this._p2pChannel.on($.PeerConnectionStateChange,t=>{const e=this._peerConnectionState;t!==e&&(this.safeEmit(_t.PEERCONNECTION_STATE_CHANGE,t,e),this._peerConnectionState=t)}),this._p2pChannel.on($.RequestMuteLocal,(t,e,i)=>C(this,null,function*(){if(this._joinInfo)try{yield this._gateway.muteLocal(t,this._joinInfo.stringUid||this._joinInfo.uid),e()}catch(n){n.code===v.DISCONNECT_P2P?e():i(n)}else e()})),this._p2pChannel.on($.RequestUnmuteLocal,(t,e,i)=>C(this,null,function*(){if(this._joinInfo)try{yield this._gateway.unmuteLocal(t,this._joinInfo.stringUid||this._joinInfo.uid),e()}catch(n){n.code===v.DISCONNECT_P2P?e():i(n)}else e()})),this._p2pChannel.on($.RequestRePublish,(t,e,i)=>{this.publish(t,!1).then(e).catch(i)}),this._p2pChannel.on($.RequestRePublishDataChannel,(t,e,i)=>{K.all(t.map(n=>C(this,null,function*(){const r=yield this._p2pChannel.publishDataChannel([n]);try{r.forEach(o=>{this._uid&&this._gateway.publishDataChannel(this._uid,o,!0)})}catch(o){if(o.code!==v.DISCONNECT_P2P)throw o}}))).then(e).catch(i)}),this._p2pChannel.on($.RequestReSubscribe,(t,e,i)=>C(this,null,function*(){try{for(const{user:n,kind:r}of t)r===q.VIDEO?yield this.subscribe(n,"video"):yield this.subscribe(n,"audio");e()}catch(n){i(n)}})),this._p2pChannel.on($.RequestUpload,(t,e)=>{this._gateway.upload(t,e)}),this._p2pChannel.on($.RequestUploadStats,t=>{this._gateway.uploadWRTCStats(t)}),this._p2pChannel.on($.MediaReconnectStart,t=>{this.safeEmit(_t.MEDIA_RECONNECT_START,t)}),this._p2pChannel.on($.MediaReconnectEnd,t=>{this.safeEmit(_t.MEDIA_RECONNECT_END,t)}),this._p2pChannel.on($.NeedSignalRTT,t=>{t(this._gateway.getSignalRTT())}),this._p2pChannel.on($.RequestRestartICE,t=>C(this,null,function*(){if(this.store.useP2P)return;const e=yield this._p2pChannel.restartICE(t),i=yield e.next();if(i.done)return;const n=i.value;let r;try{r=yield this._gateway.restartICE({iceParameters:n})}catch(s){return void e.throw(s)}const{iceParameters:o}=function(s){const a=s.iceParameters;return{iceParameters:{iceUfrag:a.iceUfrag,icePwd:a.icePwd}}}(r);yield e.next({remoteIceParameters:o})})),this._p2pChannel.on($.RequestReconnect,()=>C(this,null,function*(){this._gateway.reconnect()})),this._p2pChannel.on($.RequestReconnectPC,()=>C(this,null,function*(){var t;const{iceParameters:e,dtlsParameters:i,rtpCapabilities:n}=yield this._p2pChannel.startP2PConnection({turnServer:(t=this._joinInfo)===null||t===void 0?void 0:t.turnServer}),{gatewayEstablishParams:r,gatewayAddress:o}=yield this._gateway.reconnectPC({iceParameters:e,dtlsParameters:i,rtpCapabilities:n}),s=Sw(r,o);yield this._p2pChannel.connect(s),yield this._p2pChannel.republish(),yield this._p2pChannel.reSubscribe()})),this._p2pChannel.on($.RequestUnpublishForReconnectPC,(t,e,i)=>C(this,null,function*(){this._joinInfo&&this._uid!==void 0?(yield this._gateway.unpublish(t,this._uid),e()):i()})),this._p2pChannel.on($.P2PLost,()=>{this.safeEmit(_t.P2P_LOST,this.store.uid)}),this._p2pChannel.on($.UpdateVideoEncoder,t=>{t._encoderConfig&&this._gateway.setVideoProfile(t._encoderConfig)}),this._p2pChannel.on($.ConnectionTypeChange,t=>{this.safeEmit(_t.IS_USING_CLOUD_PROXY,t)}),this._p2pChannel.on($.RequestLowStreamParameter,t=>{t(this._lowStreamParameter||{width:160,height:120,framerate:15,bitrate:50})}),this._p2pChannel.on($.QueryClientConnectionState,t=>{t(this.connectionState)}),this._p2pChannel.on($.AudioMetadata,t=>{this.safeEmit(_t.AUDIO_METADATA,t)})}getKeyMetrics(){return this.store.keyMetrics}enableContentInspect(t){return C(this,null,function*(){if(!this._joinInfo||this.connectionState!=="CONNECTED")throw new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] can not create content inspect, please join channel first"));if(this._inspect)throw new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] Inspect content service already in connecting/connected state"));try{const i=(e={config:t},Kr("ContentInspect").create(e));this._inspect=i,this.handleVideoInspectEvents(i);const{appId:n,cname:r,sid:o,token:s,uid:a,cid:c,vid:d}=this._joinInfo;yield i.init({appId:n,areaCode:"",cname:r,sid:o,token:s,uid:a,cid:c,vid:d?Number(d):0},ge)}catch(i){throw Array.isArray(i)?i[0]:i}var e})}handleVideoInspectEvents(t){t.on(Pe.CONNECTION_STATE_CHANGE,(e,i)=>{if(this.safeEmit(_t.CONTENT_INSPECT_CONNECTION_STATE_CHANGE,e,i),i===Pn.CONNECTED){if(this.connectionState!=="CONNECTED")return void this.safeEmit(_t.CONTENT_INSPECT_ERROR,new P(v.OPERATION_ABORTED,"Content inspect was cancelled because it left the channel"));t.inspectImage()}}),t.on(Pe.INSPECT_RESULT,(e,i)=>{var n;if((i==null?void 0:i.code)===v.INVALID_OPERATION&&this.connectionState==="DISCONNECTED")return _.debug("Stop inspect content because that has left channel"),this==null||(n=this._inspect)===null||n===void 0||n.close(),void(this._inspect=void 0);this.safeEmit(_t.CONTENT_INSPECT_RESULT,e,i)}),t.on(Pe.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(i=>i.trackMediaType==="video")[0])})}disableContentInspect(){return C(this,null,function*(){if(!this._inspect)throw new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] inspectVideoContent not started"));try{this._inspect.close(),this._inspect=void 0}catch(t){throw Array.isArray(t)?t[0]:t}})}setImageModeration(t,e){return C(this,null,function*(){if(Fr(t,"enabled"),t){if(!e)throw new P(v.INVALID_PARAMS,"config is required");if(U0(e),!this._joinInfo)throw new P(v.INVALID_OPERATION,"can not create image moderation, please join channel first");try{if(this._moderation)this._moderation.updateConfig(e);else{const n=(i={config:e},Kr("ImageModeration").create(i));this._moderation=n,this.handleImageModerationEvents(n);const{appId:r,cname:o,sid:s,token:a,uid:c,cid:d,vid:l}=this._joinInfo;yield n.init({appId:r,areaCode:"",cname:o,sid:s,token:a,uid:c,cid:d,vid:l?Number(l):0},ge)}}catch(n){throw Array.isArray(n)?n[0]:n}}else{var i;if(!this._moderation)throw new P(v.INVALID_OPERATION,"[".concat(this._clientId,"] image moderation not started"));try{this._moderation.close(),this._moderation.removeAllListeners(),this._moderation=void 0}catch(n){throw Array.isArray(n)?n[0]:n}}})}handleImageModerationEvents(t){t.on(tr.CONNECTION_STATE_CHANGE,(e,i)=>{if(this.safeEmit(_t.IMAGE_MODERATION_CONNECTION_STATE_CHANGE,e,i),e===hn.CONNECTED){if(this.connectionState!=="CONNECTED")throw this.setImageModeration(!1),new P(v.OPERATION_ABORTED,"Image moderation was cancelled because it left the channel");t.inspectImage()}}),t.on(tr.CLIENT_LOCAL_VIDEO_TRACK,e=>{e(this.localTracks.filter(i=>i.trackMediaType==="video")[0])})}setP2PTransport(t){if(function(e){Ae(e,"transport",["default","auto","relay","sd-rtn"])}(t),this.mode!=="p2p")throw new P(v.INVALID_OPERATION,"only p2p mode can set p2pTransport");this.store.p2pTransport=t,_.info("[".concat(this._clientId,"] set client p2pTransport to ").concat(t))}getJoinChannelServiceRecords(){return _.debug("getJoinChannelServiceRecords"),this.store.joinChannelServiceRecords}setPublishAudioFilterEnabled(t){return C(this,null,function*(){Fr(t,"enabled"),kt("ENABLE_PUBLISH_AUDIO_FILTER",t),this._joinInfo&&(yield this._gateway.setPublishAudioFilterEnabled(t))})}_handleResetAddStream(t,e){switch(e){case"audio":t._audio_added_=!1,t._trust_audio_stream_added_state_=!0;break;case"video":t._video_added_=!1,t._trust_video_stream_added_state_=!0}}},Q(Y.prototype,"leave",[x0],Object.getOwnPropertyDescriptor(Y.prototype,"leave"),Y.prototype),Q(Y.prototype,"publish",[V0],Object.getOwnPropertyDescriptor(Y.prototype,"publish"),Y.prototype),Q(Y.prototype,"unpublish",[F0],Object.getOwnPropertyDescriptor(Y.prototype,"unpublish"),Y.prototype),Q(Y.prototype,"subscribe",[B0],Object.getOwnPropertyDescriptor(Y.prototype,"subscribe"),Y.prototype),Q(Y.prototype,"presubscribe",[j0],Object.getOwnPropertyDescriptor(Y.prototype,"presubscribe"),Y.prototype),Q(Y.prototype,"massSubscribe",[G0],Object.getOwnPropertyDescriptor(Y.prototype,"massSubscribe"),Y.prototype),Q(Y.prototype,"unsubscribe",[W0],Object.getOwnPropertyDescriptor(Y.prototype,"unsubscribe"),Y.prototype),Q(Y.prototype,"massUnsubscribe",[H0],Object.getOwnPropertyDescriptor(Y.prototype,"massUnsubscribe"),Y.prototype),Q(Y.prototype,"setLowStreamParameter",[K0],Object.getOwnPropertyDescriptor(Y.prototype,"setLowStreamParameter"),Y.prototype),Q(Y.prototype,"enableDualStream",[Y0],Object.getOwnPropertyDescriptor(Y.prototype,"enableDualStream"),Y.prototype),Q(Y.prototype,"disableDualStream",[q0],Object.getOwnPropertyDescriptor(Y.prototype,"disableDualStream"),Y.prototype),Q(Y.prototype,"setClientRole",[z0],Object.getOwnPropertyDescriptor(Y.prototype,"setClientRole"),Y.prototype),Q(Y.prototype,"_setClientRoleOptions",[X0],Object.getOwnPropertyDescriptor(Y.prototype,"_setClientRoleOptions"),Y.prototype),Q(Y.prototype,"setProxyServer",[J0],Object.getOwnPropertyDescriptor(Y.prototype,"setProxyServer"),Y.prototype),Q(Y.prototype,"setTurnServer",[Q0],Object.getOwnPropertyDescriptor(Y.prototype,"setTurnServer"),Y.prototype),Q(Y.prototype,"setLicense",[Z0],Object.getOwnPropertyDescriptor(Y.prototype,"setLicense"),Y.prototype),Q(Y.prototype,"startProxyServer",[$0],Object.getOwnPropertyDescriptor(Y.prototype,"startProxyServer"),Y.prototype),Q(Y.prototype,"stopProxyServer",[tO],Object.getOwnPropertyDescriptor(Y.prototype,"stopProxyServer"),Y.prototype),Q(Y.prototype,"setLocalAccessPointsV2",[eO],Object.getOwnPropertyDescriptor(Y.prototype,"setLocalAccessPointsV2"),Y.prototype),Q(Y.prototype,"setLocalAccessPoints",[iO],Object.getOwnPropertyDescriptor(Y.prototype,"setLocalAccessPoints"),Y.prototype),Q(Y.prototype,"setRemoteDefaultVideoStreamType",[nO],Object.getOwnPropertyDescriptor(Y.prototype,"setRemoteDefaultVideoStreamType"),Y.prototype),Q(Y.prototype,"setRemoteVideoStreamType",[rO],Object.getOwnPropertyDescriptor(Y.prototype,"setRemoteVideoStreamType"),Y.prototype),Q(Y.prototype,"setStreamFallbackOption",[oO],Object.getOwnPropertyDescriptor(Y.prototype,"setStreamFallbackOption"),Y.prototype),Q(Y.prototype,"setEncryptionConfig",[sO],Object.getOwnPropertyDescriptor(Y.prototype,"setEncryptionConfig"),Y.prototype),Q(Y.prototype,"renewToken",[aO],Object.getOwnPropertyDescriptor(Y.prototype,"renewToken"),Y.prototype),Q(Y.prototype,"enableAudioVolumeIndicator",[cO],Object.getOwnPropertyDescriptor(Y.prototype,"enableAudioVolumeIndicator"),Y.prototype),Q(Y.prototype,"startLiveStreaming",[dO],Object.getOwnPropertyDescriptor(Y.prototype,"startLiveStreaming"),Y.prototype),Q(Y.prototype,"setLiveTranscoding",[lO],Object.getOwnPropertyDescriptor(Y.prototype,"setLiveTranscoding"),Y.prototype),Q(Y.prototype,"stopLiveStreaming",[uO],Object.getOwnPropertyDescriptor(Y.prototype,"stopLiveStreaming"),Y.prototype),Q(Y.prototype,"startChannelMediaRelay",[hO],Object.getOwnPropertyDescriptor(Y.prototype,"startChannelMediaRelay"),Y.prototype),Q(Y.prototype,"updateChannelMediaRelay",[pO],Object.getOwnPropertyDescriptor(Y.prototype,"updateChannelMediaRelay"),Y.prototype),Q(Y.prototype,"stopChannelMediaRelay",[_O],Object.getOwnPropertyDescriptor(Y.prototype,"stopChannelMediaRelay"),Y.prototype),Q(Y.prototype,"sendCustomReportMessage",[EO],Object.getOwnPropertyDescriptor(Y.prototype,"sendCustomReportMessage"),Y.prototype),Q(Y.prototype,"pickSVCLayer",[mO],Object.getOwnPropertyDescriptor(Y.prototype,"pickSVCLayer"),Y.prototype),Q(Y.prototype,"setRTMConfig",[fO],Object.getOwnPropertyDescriptor(Y.prototype,"setRTMConfig"),Y.prototype),Q(Y.prototype,"enableContentInspect",[gO],Object.getOwnPropertyDescriptor(Y.prototype,"enableContentInspect"),Y.prototype),Q(Y.prototype,"disableContentInspect",[SO],Object.getOwnPropertyDescriptor(Y.prototype,"disableContentInspect"),Y.prototype),Q(Y.prototype,"setImageModeration",[TO],Object.getOwnPropertyDescriptor(Y.prototype,"setImageModeration"),Y.prototype),Q(Y.prototype,"setP2PTransport",[RO],Object.getOwnPropertyDescriptor(Y.prototype,"setP2PTransport"),Y.prototype),Q(Y.prototype,"getJoinChannelServiceRecords",[vO],Object.getOwnPropertyDescriptor(Y.prototype,"getJoinChannelServiceRecords"),Y.prototype),Q(Y.prototype,"setPublishAudioFilterEnabled",[CO],Object.getOwnPropertyDescriptor(Y.prototype,"setPublishAudioFilterEnabled"),Y.prototype),Y);class ed{constructor(e,i){S(this,"id",0),S(this,"element",void 0),S(this,"peerPair",void 0),S(this,"context",void 0),S(this,"audioPlayerElement",void 0),S(this,"audioTrack",void 0),ed.count+=1,this.id=ed.count,this.element=e,this.context=i}initPeers(){this.peerPair=[new RTCPeerConnection,new RTCPeerConnection],this.peerPair[1].ontrack=e=>{const i=document.createElement("audio");i.srcObject=new MediaStream([e.track]),i.play(),this.audioPlayerElement=i}}switchSdp(){return C(this,null,function*(){if(!this.peerPair)return;const e=(n,r)=>C(this,null,function*(){const o=r==="offer"?yield n.createOffer():yield n.createAnswer();return yield n.setLocalDescription(o),n.iceGatheringState==="complete"?n.localDescription:new K(s=>{n.onicegatheringstatechange=()=>{n.iceGatheringState==="complete"&&s(n.localDescription)}})}),i=(n,r)=>C(this,null,function*(){return yield n.setRemoteDescription(r)});try{const n=yield e(this.peerPair[0],"offer");yield i(this.peerPair[1],n);const r=yield e(this.peerPair[1],"answer");yield i(this.peerPair[0],r)}catch(n){throw new P(v.LOCAL_AEC_ERROR,n.toString()).print()}})}getTracksFromMediaElement(e){return C(this,null,function*(){if(this.audioTrack)return this.audioTrack;let i;try{e instanceof HTMLVideoElement&&(e.captureStream?e.captureStream():e.mozCaptureStream()),i=this.context.createMediaStreamDestination(),this.context.createMediaElementSource(e).connect(i)}catch(r){throw new P(v.LOCAL_AEC_ERROR,r.toString()).print()}if(!i)throw new P(v.LOCAL_AEC_ERROR,"no dest node when local aec").print();const n=i.stream.getAudioTracks()[0];return this.audioTrack=n,n})}getElement(){return this.element}startEchoCancellation(){return C(this,null,function*(){this.context.resume(),this.peerPair&&this.close(),this.initPeers();const e=this.element,i=yield this.getTracksFromMediaElement(e);this.peerPair&&this.peerPair[0].addTrack(i),yield this.switchSdp()})}close(){_.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 IO,sh;S(ed,"count",0);const ZW=window.AudioContext||window.webkitAudioContext,$W=new(IO=it({report:Z}),Q((sh=class{constructor(){S(this,"units",[]),S(this,"context",void 0)}processExternalMediaAEC(t){if(!this._doesEnvironmentNeedAEC())return _.debug("the system does not need to process local aec"),-1;this.context||(this.context=new ZW);let e=this.units.find(i=>i&&i.getElement()===t);return e||(e=new ed(t,this.context),this.units.push(e)),e.startEchoCancellation(),_.debug("start processing local audio echo cancellation, id is",e.id),e.id}_doesEnvironmentNeedAEC(){return vt().name!==It.SAFARI}}).prototype,"processExternalMediaAEC",[IO],Object.getOwnPropertyDescriptor(sh.prototype,"processExternalMediaAEC"),sh.prototype),sh);function AO(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function bO(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?AO(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):AO(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}const sf=window||document;function wO(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!sf)return;const i=Se._cspEventHandlerPointer;if(i&&e)return void console.error(i,e);const n=r=>{if(!(r&&r.blockedURI&&(Se.onSecurityPolicyViolation||Se.getListeners(Tr.SECURITY_POLICY_VIOLATION).length>0)))return;const o=r.blockedURI;y("CSP_DETECTED_HOSTNAME_LIST").some(s=>G(o).call(o,s))&&(Se.onSecurityPolicyViolation&&typeof Se.onSecurityPolicyViolation=="function"&&Se.onSecurityPolicyViolation(r),Se.getListeners(Tr.SECURITY_POLICY_VIOLATION).length>0&&Se.safeEmit(Tr.SECURITY_POLICY_VIOLATION,r))};i&&sf.removeEventListener("securitypolicyviolation",i),(e||t&&typeof t=="function"||Se.getListeners(Tr.SECURITY_POLICY_VIOLATION).length>0)&&sf.addEventListener("securitypolicyviolation",n),Se._cspEventHandlerPointer=n}var t5=$e,e5=hy,OO=RegExp.prototype,i5=function(t){return t===OO||t5(OO,t)?e5(t):t.flags},si=Pt(i5);function Ma(t){let e=t.length;for(;--e>=0;)t[e]=0}const af=256,NO=286,id=30,nd=15,cf=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]),ah=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]),n5=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),DO=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qr=new Array(576);Ma(qr);const rd=new Array(60);Ma(rd);const od=new Array(512);Ma(od);const sd=new Array(256);Ma(sd);const df=new Array(29);Ma(df);const ch=new Array(id);function lf(t,e,i,n,r){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=t&&t.length}let PO,LO,kO;function uf(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}Ma(ch);const MO=t=>t<256?od[t]:od[256+(t>>>7)],ad=(t,e)=>{t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255},on=(t,e,i)=>{t.bi_valid>16-i?(t.bi_buf|=e<<t.bi_valid&65535,ad(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=i-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)},Ir=(t,e,i)=>{on(t,i[2*e],i[2*e+1])},UO=(t,e)=>{let i=0;do i|=1&t,t>>>=1,i<<=1;while(--e>0);return i>>>1},xO=(t,e,i)=>{const n=new Array(16);let r,o,s=0;for(r=1;r<=nd;r++)s=s+i[r-1]<<1,n[r]=s;for(o=0;o<=e;o++){let a=t[2*o+1];a!==0&&(t[2*o]=UO(n[a]++,a))}},VO=t=>{let e;for(e=0;e<NO;e++)t.dyn_ltree[2*e]=0;for(e=0;e<id;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.sym_next=t.matches=0},FO=t=>{t.bi_valid>8?ad(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0},BO=(t,e,i,n)=>{const r=2*e,o=2*i;return t[r]<t[o]||t[r]===t[o]&&n[e]<=n[i]},hf=(t,e,i)=>{const n=t.heap[i];let r=i<<1;for(;r<=t.heap_len&&(r<t.heap_len&&BO(e,t.heap[r+1],t.heap[r],t.depth)&&r++,!BO(e,n,t.heap[r],t.depth));)t.heap[i]=t.heap[r],i=r,r<<=1;t.heap[i]=n},jO=(t,e,i)=>{let n,r,o,s,a=0;if(t.sym_next!==0)do n=255&t.pending_buf[t.sym_buf+a++],n+=(255&t.pending_buf[t.sym_buf+a++])<<8,r=t.pending_buf[t.sym_buf+a++],n===0?Ir(t,r,e):(o=sd[r],Ir(t,o+af+1,e),s=cf[o],s!==0&&(r-=df[o],on(t,r,s)),n--,o=MO(n),Ir(t,o,i),s=ah[o],s!==0&&(n-=ch[o],on(t,n,s)));while(a<t.sym_next);Ir(t,256,e)},pf=(t,e)=>{const i=e.dyn_tree,n=e.stat_desc.static_tree,r=e.stat_desc.has_stree,o=e.stat_desc.elems;let s,a,c,d=-1;for(t.heap_len=0,t.heap_max=573,s=0;s<o;s++)i[2*s]!==0?(t.heap[++t.heap_len]=d=s,t.depth[s]=0):i[2*s+1]=0;for(;t.heap_len<2;)c=t.heap[++t.heap_len]=d<2?++d:0,i[2*c]=1,t.depth[c]=0,t.opt_len--,r&&(t.static_len-=n[2*c+1]);for(e.max_code=d,s=t.heap_len>>1;s>=1;s--)hf(t,i,s);c=o;do s=t.heap[1],t.heap[1]=t.heap[t.heap_len--],hf(t,i,1),a=t.heap[1],t.heap[--t.heap_max]=s,t.heap[--t.heap_max]=a,i[2*c]=i[2*s]+i[2*a],t.depth[c]=(t.depth[s]>=t.depth[a]?t.depth[s]:t.depth[a])+1,i[2*s+1]=i[2*a+1]=c,t.heap[1]=c++,hf(t,i,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],((l,u)=>{const h=u.dyn_tree,p=u.max_code,g=u.stat_desc.static_tree,m=u.stat_desc.has_stree,f=u.stat_desc.extra_bits,T=u.stat_desc.extra_base,R=u.stat_desc.max_length;let A,N,O,w,L,M,j=0;for(w=0;w<=nd;w++)l.bl_count[w]=0;for(h[2*l.heap[l.heap_max]+1]=0,A=l.heap_max+1;A<573;A++)N=l.heap[A],w=h[2*h[2*N+1]+1]+1,w>R&&(w=R,j++),h[2*N+1]=w,N>p||(l.bl_count[w]++,L=0,N>=T&&(L=f[N-T]),M=h[2*N],l.opt_len+=M*(w+L),m&&(l.static_len+=M*(g[2*N+1]+L)));if(j!==0){do{for(w=R-1;l.bl_count[w]===0;)w--;l.bl_count[w]--,l.bl_count[w+1]+=2,l.bl_count[R]--,j-=2}while(j>0);for(w=R;w!==0;w--)for(N=l.bl_count[w];N!==0;)O=l.heap[--A],O>p||(h[2*O+1]!==w&&(l.opt_len+=(w-h[2*O+1])*h[2*O],h[2*O+1]=w),N--)}})(t,e),xO(i,d,t.bl_count)},GO=(t,e,i)=>{let n,r,o=-1,s=e[1],a=0,c=7,d=4;for(s===0&&(c=138,d=3),e[2*(i+1)+1]=65535,n=0;n<=i;n++)r=s,s=e[2*(n+1)+1],++a<c&&r===s||(a<d?t.bl_tree[2*r]+=a:r!==0?(r!==o&&t.bl_tree[2*r]++,t.bl_tree[32]++):a<=10?t.bl_tree[34]++:t.bl_tree[36]++,a=0,o=r,s===0?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4))},WO=(t,e,i)=>{let n,r,o=-1,s=e[1],a=0,c=7,d=4;for(s===0&&(c=138,d=3),n=0;n<=i;n++)if(r=s,s=e[2*(n+1)+1],!(++a<c&&r===s)){if(a<d)do Ir(t,r,t.bl_tree);while(--a!=0);else r!==0?(r!==o&&(Ir(t,r,t.bl_tree),a--),Ir(t,16,t.bl_tree),on(t,a-3,2)):a<=10?(Ir(t,17,t.bl_tree),on(t,a-3,3)):(Ir(t,18,t.bl_tree),on(t,a-11,7));a=0,o=r,s===0?(c=138,d=3):r===s?(c=6,d=3):(c=7,d=4)}};let HO=!1;const KO=(t,e,i,n)=>{on(t,0+(n?1:0),3),FO(t),ad(t,i),ad(t,~i),i&&t.pending_buf.set(t.window.subarray(e,e+i),t.pending),t.pending+=i};var r5=t=>{HO||((()=>{let e,i,n,r,o;const s=new Array(16);for(n=0,r=0;r<28;r++)for(df[r]=n,e=0;e<1<<cf[r];e++)sd[n++]=r;for(sd[n-1]=r,o=0,r=0;r<16;r++)for(ch[r]=o,e=0;e<1<<ah[r];e++)od[o++]=r;for(o>>=7;r<id;r++)for(ch[r]=o<<7,e=0;e<1<<ah[r]-7;e++)od[256+o++]=r;for(i=0;i<=nd;i++)s[i]=0;for(e=0;e<=143;)qr[2*e+1]=8,e++,s[8]++;for(;e<=255;)qr[2*e+1]=9,e++,s[9]++;for(;e<=279;)qr[2*e+1]=7,e++,s[7]++;for(;e<=287;)qr[2*e+1]=8,e++,s[8]++;for(xO(qr,287,s),e=0;e<id;e++)rd[2*e+1]=5,rd[2*e]=UO(e,5);PO=new lf(qr,cf,257,NO,nd),LO=new lf(rd,ah,0,id,nd),kO=new lf(new Array(0),n5,0,19,7)})(),HO=!0),t.l_desc=new uf(t.dyn_ltree,PO),t.d_desc=new uf(t.dyn_dtree,LO),t.bl_desc=new uf(t.bl_tree,kO),t.bi_buf=0,t.bi_valid=0,VO(t)},o5=(t,e,i,n)=>{let r,o,s=0;t.level>0?(t.strm.data_type===2&&(t.strm.data_type=(a=>{let c,d=4093624447;for(c=0;c<=31;c++,d>>>=1)if(1&d&&a.dyn_ltree[2*c]!==0)return 0;if(a.dyn_ltree[18]!==0||a.dyn_ltree[20]!==0||a.dyn_ltree[26]!==0)return 1;for(c=32;c<af;c++)if(a.dyn_ltree[2*c]!==0)return 1;return 0})(t)),pf(t,t.l_desc),pf(t,t.d_desc),s=(a=>{let c;for(GO(a,a.dyn_ltree,a.l_desc.max_code),GO(a,a.dyn_dtree,a.d_desc.max_code),pf(a,a.bl_desc),c=18;c>=3&&a.bl_tree[2*DO[c]+1]===0;c--);return a.opt_len+=3*(c+1)+5+5+4,c})(t),r=t.opt_len+3+7>>>3,o=t.static_len+3+7>>>3,o<=r&&(r=o)):r=o=i+5,i+4<=r&&e!==-1?KO(t,e,i,n):t.strategy===4||o===r?(on(t,2+(n?1:0),3),jO(t,qr,rd)):(on(t,4+(n?1:0),3),((a,c,d,l)=>{let u;for(on(a,c-257,5),on(a,d-1,5),on(a,l-4,4),u=0;u<l;u++)on(a,a.bl_tree[2*DO[u]+1],3);WO(a,a.dyn_ltree,c-1),WO(a,a.dyn_dtree,d-1)})(t,t.l_desc.max_code+1,t.d_desc.max_code+1,s+1),jO(t,t.dyn_ltree,t.dyn_dtree)),VO(t),n&&FO(t)},s5=(t,e,i)=>(t.pending_buf[t.sym_buf+t.sym_next++]=e,t.pending_buf[t.sym_buf+t.sym_next++]=e>>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,e===0?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(sd[i]+af+1)]++,t.dyn_dtree[2*MO(e)]++),t.sym_next===t.sym_end),a5=t=>{on(t,2,3),Ir(t,256,qr),(e=>{e.bi_valid===16?(ad(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)})(t)},c5={_tr_init:r5,_tr_stored_block:KO,_tr_flush_block:o5,_tr_tally:s5,_tr_align:a5},cd=(t,e,i,n)=>{let r=65535&t|0,o=t>>>16&65535|0,s=0;for(;i!==0;){s=i>2e3?2e3:i,i-=s;do r=r+e[n++]|0,o=o+r|0;while(--s);r%=65521,o%=65521}return r|o<<16|0};const d5=new Uint32Array((()=>{let t,e=[];for(var i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e})());var Ei=(t,e,i,n)=>{const r=d5,o=n+i;t^=-1;for(let s=n;s<o;s++)t=t>>>8^r[255&(t^e[s])];return-1^t},hs={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"},Ua={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{_tr_init:l5,_tr_stored_block:_f,_tr_flush_block:u5,_tr_tally:bo,_tr_align:h5}=c5,{Z_NO_FLUSH:wo,Z_PARTIAL_FLUSH:p5,Z_FULL_FLUSH:_5,Z_FINISH:Vn,Z_BLOCK:YO,Z_OK:yi,Z_STREAM_END:qO,Z_STREAM_ERROR:Ar,Z_DATA_ERROR:E5,Z_BUF_ERROR:Ef,Z_DEFAULT_COMPRESSION:m5,Z_FILTERED:f5,Z_HUFFMAN_ONLY:dh,Z_RLE:g5,Z_FIXED:S5,Z_DEFAULT_STRATEGY:T5,Z_UNKNOWN:R5,Z_DEFLATED:lh}=Ua,mf=286,v5=30,C5=19,y5=2*mf+1,I5=15,ps=258,br=262,xa=42,_s=113,dd=666,Es=(t,e)=>(t.msg=hs[e],e),zO=t=>2*t-(t>4?9:0),Oo=t=>{let e=t.length;for(;--e>=0;)t[e]=0},A5=t=>{let e,i,n,r=t.w_size;e=t.hash_size,n=e;do i=t.head[--n],t.head[n]=i>=r?i-r:0;while(--e);e=r,n=e;do i=t.prev[--n],t.prev[n]=i>=r?i-r:0;while(--e)};let No=(t,e,i)=>(e<<t.hash_shift^i)&t.hash_mask;const pn=t=>{const e=t.state;let i=e.pending;i>t.avail_out&&(i=t.avail_out),i!==0&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+i),t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,e.pending===0&&(e.pending_out=0))},_n=(t,e)=>{u5(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,pn(t.strm)},ue=(t,e)=>{t.pending_buf[t.pending++]=e},ld=(t,e)=>{t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e},ff=(t,e,i,n)=>{let r=t.avail_in;return r>n&&(r=n),r===0?0:(t.avail_in-=r,e.set(t.input.subarray(t.next_in,t.next_in+r),i),t.state.wrap===1?t.adler=cd(t.adler,e,r,i):t.state.wrap===2&&(t.adler=Ei(t.adler,e,r,i)),t.next_in+=r,t.total_in+=r,r)},XO=(t,e)=>{let i,n,r=t.max_chain_length,o=t.strstart,s=t.prev_length,a=t.nice_match;const c=t.strstart>t.w_size-br?t.strstart-(t.w_size-br):0,d=t.window,l=t.w_mask,u=t.prev,h=t.strstart+ps;let p=d[o+s-1],g=d[o+s];t.prev_length>=t.good_match&&(r>>=2),a>t.lookahead&&(a=t.lookahead);do if(i=e,d[i+s]===g&&d[i+s-1]===p&&d[i]===d[o]&&d[++i]===d[o+1]){o+=2,i++;do;while(d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&d[++o]===d[++i]&&o<h);if(n=ps-(h-o),o=h-ps,n>s){if(t.match_start=e,s=n,n>=a)break;p=d[o+s-1],g=d[o+s]}}while((e=u[e&l])>c&&--r!=0);return s<=t.lookahead?s:t.lookahead},Va=t=>{const e=t.w_size;let i,n,r;do{if(n=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-br)&&(t.window.set(t.window.subarray(e,e+e-n),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),A5(t),n+=e),t.strm.avail_in===0)break;if(i=ff(t.strm,t.window,t.strstart+t.lookahead,n),t.lookahead+=i,t.lookahead+t.insert>=3)for(r=t.strstart-t.insert,t.ins_h=t.window[r],t.ins_h=No(t,t.ins_h,t.window[r+1]);t.insert&&(t.ins_h=No(t,t.ins_h,t.window[r+3-1]),t.prev[r&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=r,r++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<br&&t.strm.avail_in!==0)},JO=(t,e)=>{let i,n,r,o=t.pending_buf_size-5>t.w_size?t.w_size:t.pending_buf_size-5,s=0,a=t.strm.avail_in;do{if(i=65535,r=t.bi_valid+42>>3,t.strm.avail_out<r||(r=t.strm.avail_out-r,n=t.strstart-t.block_start,i>n+t.strm.avail_in&&(i=n+t.strm.avail_in),i>r&&(i=r),i<o&&(i===0&&e!==Vn||e===wo||i!==n+t.strm.avail_in)))break;s=e===Vn&&i===n+t.strm.avail_in?1:0,_f(t,0,0,s),t.pending_buf[t.pending-4]=i,t.pending_buf[t.pending-3]=i>>8,t.pending_buf[t.pending-2]=~i,t.pending_buf[t.pending-1]=~i>>8,pn(t.strm),n&&(n>i&&(n=i),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+n),t.strm.next_out),t.strm.next_out+=n,t.strm.avail_out-=n,t.strm.total_out+=n,t.block_start+=n,i-=n),i&&(ff(t.strm,t.strm.output,t.strm.next_out,i),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i)}while(s===0);return a-=t.strm.avail_in,a&&(a>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=a&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-a,t.strm.next_in),t.strstart),t.strstart+=a,t.insert+=a>t.w_size-t.insert?t.w_size-t.insert:a),t.block_start=t.strstart),t.high_water<t.strstart&&(t.high_water=t.strstart),s?4:e!==wo&&e!==Vn&&t.strm.avail_in===0&&t.strstart===t.block_start?2:(r=t.window_size-t.strstart,t.strm.avail_in>r&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,r+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),r>t.strm.avail_in&&(r=t.strm.avail_in),r&&(ff(t.strm,t.window,t.strstart,r),t.strstart+=r,t.insert+=r>t.w_size-t.insert?t.w_size-t.insert:r),t.high_water<t.strstart&&(t.high_water=t.strstart),r=t.bi_valid+42>>3,r=t.pending_buf_size-r>65535?65535:t.pending_buf_size-r,o=r>t.w_size?t.w_size:r,n=t.strstart-t.block_start,(n>=o||(n||e===Vn)&&e!==wo&&t.strm.avail_in===0&&n<=r)&&(i=n>r?r:n,s=e===Vn&&t.strm.avail_in===0&&i===n?1:0,_f(t,t.block_start,i,s),t.block_start+=i,pn(t.strm)),s?3:1)},gf=(t,e)=>{let i,n;for(;;){if(t.lookahead<br){if(Va(t),t.lookahead<br&&e===wo)return 1;if(t.lookahead===0)break}if(i=0,t.lookahead>=3&&(t.ins_h=No(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),i!==0&&t.strstart-i<=t.w_size-br&&(t.match_length=XO(t,i)),t.match_length>=3)if(n=bo(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do t.strstart++,t.ins_h=No(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart;while(--t.match_length!=0);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=No(t,t.ins_h,t.window[t.strstart+1]);else n=bo(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(_n(t,!1),t.strm.avail_out===0))return 1}return t.insert=t.strstart<2?t.strstart:2,e===Vn?(_n(t,!0),t.strm.avail_out===0?3:4):t.sym_next&&(_n(t,!1),t.strm.avail_out===0)?1:2},Fa=(t,e)=>{let i,n,r;for(;;){if(t.lookahead<br){if(Va(t),t.lookahead<br&&e===wo)return 1;if(t.lookahead===0)break}if(i=0,t.lookahead>=3&&(t.ins_h=No(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,i!==0&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-br&&(t.match_length=XO(t,i),t.match_length<=5&&(t.strategy===f5||t.match_length===3&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){r=t.strstart+t.lookahead-3,n=bo(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=r&&(t.ins_h=No(t,t.ins_h,t.window[t.strstart+3-1]),i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart);while(--t.prev_length!=0);if(t.match_available=0,t.match_length=2,t.strstart++,n&&(_n(t,!1),t.strm.avail_out===0))return 1}else if(t.match_available){if(n=bo(t,0,t.window[t.strstart-1]),n&&_n(t,!1),t.strstart++,t.lookahead--,t.strm.avail_out===0)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=bo(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===Vn?(_n(t,!0),t.strm.avail_out===0?3:4):t.sym_next&&(_n(t,!1),t.strm.avail_out===0)?1:2};function wr(t,e,i,n,r){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=n,this.func=r}const ud=[new wr(0,0,0,0,JO),new wr(4,4,8,4,gf),new wr(4,5,16,8,gf),new wr(4,6,32,32,gf),new wr(4,4,16,16,Fa),new wr(8,16,32,32,Fa),new wr(8,16,128,128,Fa),new wr(8,32,128,256,Fa),new wr(32,128,258,1024,Fa),new wr(32,258,258,4096,Fa)];function b5(){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=lh,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*y5),this.dyn_dtree=new Uint16Array(2*(2*v5+1)),this.bl_tree=new Uint16Array(2*(2*C5+1)),Oo(this.dyn_ltree),Oo(this.dyn_dtree),Oo(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(I5+1),this.heap=new Uint16Array(2*mf+1),Oo(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(2*mf+1),Oo(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 hd=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.status!==xa&&e.status!==57&&e.status!==69&&e.status!==73&&e.status!==91&&e.status!==103&&e.status!==_s&&e.status!==dd?1:0},QO=t=>{if(hd(t))return Es(t,Ar);t.total_in=t.total_out=0,t.data_type=R5;const e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap===2?57:e.wrap?xa:_s,t.adler=e.wrap===2?0:1,e.last_flush=-2,l5(e),yi},ZO=t=>{const e=QO(t);return e===yi&&(i=>{i.window_size=2*i.w_size,Oo(i.head),i.max_lazy_match=ud[i.level].max_lazy,i.good_match=ud[i.level].good_length,i.nice_match=ud[i.level].nice_length,i.max_chain_length=ud[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0})(t.state),e},$O=(t,e,i,n,r,o)=>{if(!t)return Ar;let s=1;if(e===m5&&(e=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>9||i!==lh||n<8||n>15||e<0||e>9||o<0||o>S5||n===8&&s!==1)return Es(t,Ar);n===8&&(n=9);const a=new b5;return t.state=a,a.strm=t,a.status=xa,a.wrap=s,a.gzhead=null,a.w_bits=n,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=e,a.strategy=o,a.method=i,ZO(t)};var w5=(t,e)=>{if(hd(t)||e>YO||e<0)return t?Es(t,Ar):Ar;const i=t.state;if(!t.output||t.avail_in!==0&&!t.input||i.status===dd&&e!==Vn)return Es(t,t.avail_out===0?Ef:Ar);const n=i.last_flush;if(i.last_flush=e,i.pending!==0){if(pn(t),t.avail_out===0)return i.last_flush=-1,yi}else if(t.avail_in===0&&zO(e)<=zO(n)&&e!==Vn)return Es(t,Ef);if(i.status===dd&&t.avail_in!==0)return Es(t,Ef);if(i.status===xa&&i.wrap===0&&(i.status=_s),i.status===xa){let r=lh+(i.w_bits-8<<4)<<8,o=-1;if(o=i.strategy>=dh||i.level<2?0:i.level<6?1:i.level===6?2:3,r|=o<<6,i.strstart!==0&&(r|=32),r+=31-r%31,ld(i,r),i.strstart!==0&&(ld(i,t.adler>>>16),ld(i,65535&t.adler)),t.adler=1,i.status=_s,pn(t),i.pending!==0)return i.last_flush=-1,yi}if(i.status===57){if(t.adler=0,ue(i,31),ue(i,139),ue(i,8),i.gzhead)ue(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),ue(i,255&i.gzhead.time),ue(i,i.gzhead.time>>8&255),ue(i,i.gzhead.time>>16&255),ue(i,i.gzhead.time>>24&255),ue(i,i.level===9?2:i.strategy>=dh||i.level<2?4:0),ue(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(ue(i,255&i.gzhead.extra.length),ue(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=Ei(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(ue(i,0),ue(i,0),ue(i,0),ue(i,0),ue(i,0),ue(i,i.level===9?2:i.strategy>=dh||i.level<2?4:0),ue(i,3),i.status=_s,pn(t),i.pending!==0)return i.last_flush=-1,yi}if(i.status===69){if(i.gzhead.extra){let r=i.pending,o=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+o>i.pending_buf_size;){let a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>r&&(t.adler=Ei(t.adler,i.pending_buf,i.pending-r,r)),i.gzindex+=a,pn(t),i.pending!==0)return i.last_flush=-1,yi;r=0,o-=a}let s=new Uint8Array(i.gzhead.extra);i.pending_buf.set(s.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending+=o,i.gzhead.hcrc&&i.pending>r&&(t.adler=Ei(t.adler,i.pending_buf,i.pending-r,r)),i.gzindex=0}i.status=73}if(i.status===73){if(i.gzhead.name){let r,o=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>o&&(t.adler=Ei(t.adler,i.pending_buf,i.pending-o,o)),pn(t),i.pending!==0)return i.last_flush=-1,yi;o=0}r=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,ue(i,r)}while(r!==0);i.gzhead.hcrc&&i.pending>o&&(t.adler=Ei(t.adler,i.pending_buf,i.pending-o,o)),i.gzindex=0}i.status=91}if(i.status===91){if(i.gzhead.comment){let r,o=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>o&&(t.adler=Ei(t.adler,i.pending_buf,i.pending-o,o)),pn(t),i.pending!==0)return i.last_flush=-1,yi;o=0}r=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,ue(i,r)}while(r!==0);i.gzhead.hcrc&&i.pending>o&&(t.adler=Ei(t.adler,i.pending_buf,i.pending-o,o))}i.status=103}if(i.status===103){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(pn(t),i.pending!==0))return i.last_flush=-1,yi;ue(i,255&t.adler),ue(i,t.adler>>8&255),t.adler=0}if(i.status=_s,pn(t),i.pending!==0)return i.last_flush=-1,yi}if(t.avail_in!==0||i.lookahead!==0||e!==wo&&i.status!==dd){let r=i.level===0?JO(i,e):i.strategy===dh?((o,s)=>{let a;for(;;){if(o.lookahead===0&&(Va(o),o.lookahead===0)){if(s===wo)return 1;break}if(o.match_length=0,a=bo(o,0,o.window[o.strstart]),o.lookahead--,o.strstart++,a&&(_n(o,!1),o.strm.avail_out===0))return 1}return o.insert=0,s===Vn?(_n(o,!0),o.strm.avail_out===0?3:4):o.sym_next&&(_n(o,!1),o.strm.avail_out===0)?1:2})(i,e):i.strategy===g5?((o,s)=>{let a,c,d,l;const u=o.window;for(;;){if(o.lookahead<=ps){if(Va(o),o.lookahead<=ps&&s===wo)return 1;if(o.lookahead===0)break}if(o.match_length=0,o.lookahead>=3&&o.strstart>0&&(d=o.strstart-1,c=u[d],c===u[++d]&&c===u[++d]&&c===u[++d])){l=o.strstart+ps;do;while(c===u[++d]&&c===u[++d]&&c===u[++d]&&c===u[++d]&&c===u[++d]&&c===u[++d]&&c===u[++d]&&c===u[++d]&&d<l);o.match_length=ps-(l-d),o.match_length>o.lookahead&&(o.match_length=o.lookahead)}if(o.match_length>=3?(a=bo(o,1,o.match_length-3),o.lookahead-=o.match_length,o.strstart+=o.match_length,o.match_length=0):(a=bo(o,0,o.window[o.strstart]),o.lookahead--,o.strstart++),a&&(_n(o,!1),o.strm.avail_out===0))return 1}return o.insert=0,s===Vn?(_n(o,!0),o.strm.avail_out===0?3:4):o.sym_next&&(_n(o,!1),o.strm.avail_out===0)?1:2})(i,e):ud[i.level].func(i,e);if(r!==3&&r!==4||(i.status=dd),r===1||r===3)return t.avail_out===0&&(i.last_flush=-1),yi;if(r===2&&(e===p5?h5(i):e!==YO&&(_f(i,0,0,!1),e===_5&&(Oo(i.head),i.lookahead===0&&(i.strstart=0,i.block_start=0,i.insert=0))),pn(t),t.avail_out===0))return i.last_flush=-1,yi}return e!==Vn?yi:i.wrap<=0?qO:(i.wrap===2?(ue(i,255&t.adler),ue(i,t.adler>>8&255),ue(i,t.adler>>16&255),ue(i,t.adler>>24&255),ue(i,255&t.total_in),ue(i,t.total_in>>8&255),ue(i,t.total_in>>16&255),ue(i,t.total_in>>24&255)):(ld(i,t.adler>>>16),ld(i,65535&t.adler)),pn(t),i.wrap>0&&(i.wrap=-i.wrap),i.pending!==0?yi:qO)},O5=(t,e)=>{let i=e.length;if(hd(t))return Ar;const n=t.state,r=n.wrap;if(r===2||r===1&&n.status!==xa||n.lookahead)return Ar;if(r===1&&(t.adler=cd(t.adler,e,i,0)),n.wrap=0,i>=n.w_size){r===0&&(Oo(n.head),n.strstart=0,n.block_start=0,n.insert=0);let c=new Uint8Array(n.w_size);c.set(e.subarray(i-n.w_size,i),0),e=c,i=n.w_size}const o=t.avail_in,s=t.next_in,a=t.input;for(t.avail_in=i,t.next_in=0,t.input=e,Va(n);n.lookahead>=3;){let c=n.strstart,d=n.lookahead-2;do n.ins_h=No(n,n.ins_h,n.window[c+3-1]),n.prev[c&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=c,c++;while(--d);n.strstart=c,n.lookahead=2,Va(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=2,n.match_available=0,t.next_in=s,t.input=a,t.avail_in=o,n.wrap=r,yi},pd={deflateInit:(t,e)=>$O(t,e,lh,15,8,T5),deflateInit2:$O,deflateReset:ZO,deflateResetKeep:QO,deflateSetHeader:(t,e)=>hd(t)||t.state.wrap!==2?Ar:(t.state.gzhead=e,yi),deflate:w5,deflateEnd:t=>{if(hd(t))return Ar;const e=t.state.status;return t.state=null,e===_s?Es(t,E5):yi},deflateSetDictionary:O5,deflateInfo:"pako deflate (from Nodeca project)"};const N5=(t,e)=>Object.prototype.hasOwnProperty.call(t,e);var uh={assign:function(t){const e=Array.prototype.slice.call(arguments,1);for(;e.length;){const i=e.shift();if(i){if(typeof i!="object")throw new TypeError(i+"must be non-object");for(const n in i)N5(i,n)&&(t[n]=i[n])}}return t},flattenChunks:t=>{let e=0;for(let n=0,r=t.length;n<r;n++)e+=t[n].length;const i=new Uint8Array(e);for(let n=0,r=0,o=t.length;n<o;n++){let s=t[n];i.set(s,r),r+=s.length}return i}};let tN=!0;try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){tN=!1}const _d=new Uint8Array(256);for(let t=0;t<256;t++)_d[t]=t>=252?6:t>=248?5:t>=240?4:t>=224?3:t>=192?2:1;_d[254]=_d[254]=1;var Ed={string2buf:t=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(t);let e,i,n,r,o,s=t.length,a=0;for(r=0;r<s;r++)i=t.charCodeAt(r),(64512&i)==55296&&r+1<s&&(n=t.charCodeAt(r+1),(64512&n)==56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),a+=i<128?1:i<2048?2:i<65536?3:4;for(e=new Uint8Array(a),o=0,r=0;o<a;r++)i=t.charCodeAt(r),(64512&i)==55296&&r+1<s&&(n=t.charCodeAt(r+1),(64512&n)==56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?e[o++]=i:i<2048?(e[o++]=192|i>>>6,e[o++]=128|63&i):i<65536?(e[o++]=224|i>>>12,e[o++]=128|i>>>6&63,e[o++]=128|63&i):(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63,e[o++]=128|i>>>6&63,e[o++]=128|63&i);return e},buf2string:(t,e)=>{const i=e||t.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(t.subarray(0,e));let n,r;const o=new Array(2*i);for(r=0,n=0;n<i;){let s=t[n++];if(s<128){o[r++]=s;continue}let a=_d[s];if(a>4)o[r++]=65533,n+=a-1;else{for(s&=a===2?31:a===3?15:7;a>1&&n<i;)s=s<<6|63&t[n++],a--;a>1?o[r++]=65533:s<65536?o[r++]=s:(s-=65536,o[r++]=55296|s>>10&1023,o[r++]=56320|1023&s)}}return((s,a)=>{if(a<65534&&s.subarray&&tN)return String.fromCharCode.apply(null,s.length===a?s:s.subarray(0,a));let c="";for(let d=0;d<a;d++)c+=String.fromCharCode(s[d]);return c})(o,r)},utf8border:(t,e)=>{(e=e||t.length)>t.length&&(e=t.length);let i=e-1;for(;i>=0&&(192&t[i])==128;)i--;return i<0||i===0?e:i+_d[t[i]]>e?i:e}},eN=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 iN=Object.prototype.toString,{Z_NO_FLUSH:D5,Z_SYNC_FLUSH:P5,Z_FULL_FLUSH:L5,Z_FINISH:k5,Z_OK:hh,Z_STREAM_END:M5,Z_DEFAULT_COMPRESSION:U5,Z_DEFAULT_STRATEGY:x5,Z_DEFLATED:V5}=Ua;function md(t){this.options=uh.assign({level:U5,method:V5,chunkSize:16384,windowBits:15,memLevel:8,strategy:x5},t||{});let e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new eN,this.strm.avail_out=0;let i=pd.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==hh)throw new Error(hs[i]);if(e.header&&pd.deflateSetHeader(this.strm,e.header),e.dictionary){let n;if(n=typeof e.dictionary=="string"?Ed.string2buf(e.dictionary):iN.call(e.dictionary)==="[object ArrayBuffer]"?new Uint8Array(e.dictionary):e.dictionary,i=pd.deflateSetDictionary(this.strm,n),i!==hh)throw new Error(hs[i]);this._dict_set=!0}}function Sf(t,e){const i=new md(e);if(i.push(t,!0),i.err)throw i.msg||hs[i.err];return i.result}md.prototype.push=function(t,e){const i=this.strm,n=this.options.chunkSize;let r,o;if(this.ended)return!1;for(o=e===~~e?e:e===!0?k5:D5,typeof t=="string"?i.input=Ed.string2buf(t):iN.call(t)==="[object ArrayBuffer]"?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;)if(i.avail_out===0&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),(o===P5||o===L5)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(r=pd.deflate(i,o),r===M5)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),r=pd.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===hh;if(i.avail_out!==0){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(i.avail_in===0)break}else this.onData(i.output)}return!0},md.prototype.onData=function(t){this.chunks.push(t)},md.prototype.onEnd=function(t){t===hh&&(this.result=uh.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var F5={Deflate:md,deflate:Sf,deflateRaw:function(t,e){return(e=e||{}).raw=!0,Sf(t,e)},gzip:function(t,e){return(e=e||{}).gzip=!0,Sf(t,e)},constants:Ua};const ph=16209;var B5=function(t,e){let i,n,r,o,s,a,c,d,l,u,h,p,g,m,f,T,R,A,N,O,w,L,M,j;const H=t.state;i=t.next_in,M=t.input,n=i+(t.avail_in-5),r=t.next_out,j=t.output,o=r-(e-t.avail_out),s=r+(t.avail_out-257),a=H.dmax,c=H.wsize,d=H.whave,l=H.wnext,u=H.window,h=H.hold,p=H.bits,g=H.lencode,m=H.distcode,f=(1<<H.lenbits)-1,T=(1<<H.distbits)-1;t:do{p<15&&(h+=M[i++]<<p,p+=8,h+=M[i++]<<p,p+=8),R=g[h&f];e:for(;;){if(A=R>>>24,h>>>=A,p-=A,A=R>>>16&255,A===0)j[r++]=65535&R;else{if(!(16&A)){if(!(64&A)){R=g[(65535&R)+(h&(1<<A)-1)];continue e}if(32&A){H.mode=16191;break t}t.msg="invalid literal/length code",H.mode=ph;break t}N=65535&R,A&=15,A&&(p<A&&(h+=M[i++]<<p,p+=8),N+=h&(1<<A)-1,h>>>=A,p-=A),p<15&&(h+=M[i++]<<p,p+=8,h+=M[i++]<<p,p+=8),R=m[h&T];i:for(;;){if(A=R>>>24,h>>>=A,p-=A,A=R>>>16&255,!(16&A)){if(!(64&A)){R=m[(65535&R)+(h&(1<<A)-1)];continue i}t.msg="invalid distance code",H.mode=ph;break t}if(O=65535&R,A&=15,p<A&&(h+=M[i++]<<p,p+=8,p<A&&(h+=M[i++]<<p,p+=8)),O+=h&(1<<A)-1,O>a){t.msg="invalid distance too far back",H.mode=ph;break t}if(h>>>=A,p-=A,A=r-o,O>A){if(A=O-A,A>d&&H.sane){t.msg="invalid distance too far back",H.mode=ph;break t}if(w=0,L=u,l===0){if(w+=c-A,A<N){N-=A;do j[r++]=u[w++];while(--A);w=r-O,L=j}}else if(l<A){if(w+=c+l-A,A-=l,A<N){N-=A;do j[r++]=u[w++];while(--A);if(w=0,l<N){A=l,N-=A;do j[r++]=u[w++];while(--A);w=r-O,L=j}}}else if(w+=l-A,A<N){N-=A;do j[r++]=u[w++];while(--A);w=r-O,L=j}for(;N>2;)j[r++]=L[w++],j[r++]=L[w++],j[r++]=L[w++],N-=3;N&&(j[r++]=L[w++],N>1&&(j[r++]=L[w++]))}else{w=r-O;do j[r++]=j[w++],j[r++]=j[w++],j[r++]=j[w++],N-=3;while(N>2);N&&(j[r++]=j[w++],N>1&&(j[r++]=j[w++]))}break}}break}}while(i<n&&r<s);N=p>>3,i-=N,p-=N<<3,h&=(1<<p)-1,t.next_in=i,t.next_out=r,t.avail_in=i<n?n-i+5:5-(i-n),t.avail_out=r<s?s-r+257:257-(r-s),H.hold=h,H.bits=p};const _h=15,j5=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]),G5=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]),W5=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]),H5=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 fd=(t,e,i,n,r,o,s,a)=>{const c=a.bits;let d,l,u,h,p,g,m=0,f=0,T=0,R=0,A=0,N=0,O=0,w=0,L=0,M=0,j=null;const H=new Uint16Array(16),ht=new Uint16Array(16);let lt,rt,Kt,Ft=null;for(m=0;m<=_h;m++)H[m]=0;for(f=0;f<n;f++)H[e[i+f]]++;for(A=c,R=_h;R>=1&&H[R]===0;R--);if(A>R&&(A=R),R===0)return r[o++]=20971520,r[o++]=20971520,a.bits=1,0;for(T=1;T<R&&H[T]===0;T++);for(A<T&&(A=T),w=1,m=1;m<=_h;m++)if(w<<=1,w-=H[m],w<0)return-1;if(w>0&&(t===0||R!==1))return-1;for(ht[1]=0,m=1;m<_h;m++)ht[m+1]=ht[m]+H[m];for(f=0;f<n;f++)e[i+f]!==0&&(s[ht[e[i+f]]++]=f);if(t===0?(j=Ft=s,g=20):t===1?(j=j5,Ft=G5,g=257):(j=W5,Ft=H5,g=0),M=0,f=0,m=T,p=o,N=A,O=0,u=-1,L=1<<A,h=L-1,t===1&&L>852||t===2&&L>592)return 1;for(;;){lt=m-O,s[f]+1<g?(rt=0,Kt=s[f]):s[f]>=g?(rt=Ft[s[f]-g],Kt=j[s[f]-g]):(rt=96,Kt=0),d=1<<m-O,l=1<<N,T=l;do l-=d,r[p+(M>>O)+l]=lt<<24|rt<<16|Kt|0;while(l!==0);for(d=1<<m-1;M&d;)d>>=1;if(d!==0?(M&=d-1,M+=d):M=0,f++,--H[m]==0){if(m===R)break;m=e[i+s[f]]}if(m>A&&(M&h)!==u){for(O===0&&(O=A),p+=T,N=m-O,w=1<<N;N+O<R&&(w-=H[N+O],!(w<=0));)N++,w<<=1;if(L+=1<<N,t===1&&L>852||t===2&&L>592)return 1;u=M&h,r[u]=A<<24|N<<16|p-o|0}}return M!==0&&(r[p+M]=m-O<<24|64<<16|0),a.bits=A,0};const{Z_FINISH:nN,Z_BLOCK:K5,Z_TREES:Eh,Z_OK:ms,Z_STREAM_END:Y5,Z_NEED_DICT:q5,Z_STREAM_ERROR:Fn,Z_DATA_ERROR:rN,Z_MEM_ERROR:oN,Z_BUF_ERROR:z5,Z_DEFLATED:sN}=Ua,mh=16180,fh=16190,zr=16191,Tf=16192,Rf=16194,gh=16199,Sh=16200,vf=16206,Le=16209,aN=t=>(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);function X5(){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 fs=t=>{if(!t)return 1;const e=t.state;return!e||e.strm!==t||e.mode<mh||e.mode>16211?1:0},cN=t=>{if(fs(t))return Fn;const e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=mh,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,ms},dN=t=>{if(fs(t))return Fn;const e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,cN(t)},lN=(t,e)=>{let i;if(fs(t))return Fn;const n=t.state;return e<0?(i=0,e=-e):(i=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?Fn:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=i,n.wbits=e,dN(t))},uN=(t,e)=>{if(!t)return Fn;const i=new X5;t.state=i,i.strm=t,i.window=null,i.mode=mh;const n=lN(t,e);return n!==ms&&(t.state=null),n};let Cf,yf,hN=!0;const J5=t=>{if(hN){Cf=new Int32Array(512),yf=new Int32Array(32);let e=0;for(;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(fd(1,t.lens,0,288,Cf,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;fd(2,t.lens,0,32,yf,0,t.work,{bits:5}),hN=!1}t.lencode=Cf,t.lenbits=9,t.distcode=yf,t.distbits=5},pN=(t,e,i,n)=>{let r;const o=t.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Uint8Array(o.wsize)),n>=o.wsize?(o.window.set(e.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(r=o.wsize-o.wnext,r>n&&(r=n),o.window.set(e.subarray(i-n,i-n+r),o.wnext),(n-=r)?(o.window.set(e.subarray(i-n,i),0),o.wnext=n,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0};var Q5=(t,e)=>{let i,n,r,o,s,a,c,d,l,u,h,p,g,m,f,T,R,A,N,O,w,L,M=0;const j=new Uint8Array(4);let H,ht;const lt=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(fs(t)||!t.output||!t.input&&t.avail_in!==0)return Fn;i=t.state,i.mode===zr&&(i.mode=Tf),s=t.next_out,r=t.output,c=t.avail_out,o=t.next_in,n=t.input,a=t.avail_in,d=i.hold,l=i.bits,u=a,h=c,L=ms;t:for(;;)switch(i.mode){case mh:if(i.wrap===0){i.mode=Tf;break}for(;l<16;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(2&i.wrap&&d===35615){i.wbits===0&&(i.wbits=15),i.check=0,j[0]=255&d,j[1]=d>>>8&255,i.check=Ei(i.check,j,2,0),d=0,l=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&d)<<8)+(d>>8))%31){t.msg="incorrect header check",i.mode=Le;break}if((15&d)!==sN){t.msg="unknown compression method",i.mode=Le;break}if(d>>>=4,l-=4,w=8+(15&d),i.wbits===0&&(i.wbits=w),w>15||w>i.wbits){t.msg="invalid window size",i.mode=Le;break}i.dmax=1<<i.wbits,i.flags=0,t.adler=i.check=1,i.mode=512&d?16189:zr,d=0,l=0;break;case 16181:for(;l<16;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(i.flags=d,(255&si(i))!==sN){t.msg="unknown compression method",i.mode=Le;break}if(57344&si(i)){t.msg="unknown header flags set",i.mode=Le;break}i.head&&(i.head.text=d>>8&1),512&si(i)&&4&i.wrap&&(j[0]=255&d,j[1]=d>>>8&255,i.check=Ei(i.check,j,2,0)),d=0,l=0,i.mode=16182;case 16182:for(;l<32;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}i.head&&(i.head.time=d),512&si(i)&&4&i.wrap&&(j[0]=255&d,j[1]=d>>>8&255,j[2]=d>>>16&255,j[3]=d>>>24&255,i.check=Ei(i.check,j,4,0)),d=0,l=0,i.mode=16183;case 16183:for(;l<16;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}i.head&&(i.head.xflags=255&d,i.head.os=d>>8),512&si(i)&&4&i.wrap&&(j[0]=255&d,j[1]=d>>>8&255,i.check=Ei(i.check,j,2,0)),d=0,l=0,i.mode=16184;case 16184:if(1024&si(i)){for(;l<16;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}i.length=d,i.head&&(i.head.extra_len=d),512&si(i)&&4&i.wrap&&(j[0]=255&d,j[1]=d>>>8&255,i.check=Ei(i.check,j,2,0)),d=0,l=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&si(i)&&(p=i.length,p>a&&(p=a),p&&(i.head&&(w=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(n.subarray(o,o+p),w)),512&si(i)&&4&i.wrap&&(i.check=Ei(i.check,n,p,o)),a-=p,o+=p,i.length-=p),i.length))break t;i.length=0,i.mode=16186;case 16186:if(2048&si(i)){if(a===0)break t;p=0;do w=n[o+p++],i.head&&w&&i.length<65536&&(i.head.name+=String.fromCharCode(w));while(w&&p<a);if(512&si(i)&&4&i.wrap&&(i.check=Ei(i.check,n,p,o)),a-=p,o+=p,w)break t}else i.head&&(i.head.name=null);i.length=0,i.mode=16187;case 16187:if(4096&si(i)){if(a===0)break t;p=0;do w=n[o+p++],i.head&&w&&i.length<65536&&(i.head.comment+=String.fromCharCode(w));while(w&&p<a);if(512&si(i)&&4&i.wrap&&(i.check=Ei(i.check,n,p,o)),a-=p,o+=p,w)break t}else i.head&&(i.head.comment=null);i.mode=16188;case 16188:if(512&si(i)){for(;l<16;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(4&i.wrap&&d!==(65535&i.check)){t.msg="header crc mismatch",i.mode=Le;break}d=0,l=0}i.head&&(i.head.hcrc=si(i)>>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=zr;break;case 16189:for(;l<32;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}t.adler=i.check=aN(d),d=0,l=0,i.mode=fh;case fh:if(i.havedict===0)return t.next_out=s,t.avail_out=c,t.next_in=o,t.avail_in=a,i.hold=d,i.bits=l,q5;t.adler=i.check=1,i.mode=zr;case zr:if(e===K5||e===Eh)break t;case Tf:if(i.last){d>>>=7&l,l-=7&l,i.mode=vf;break}for(;l<3;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}switch(i.last=1&d,d>>>=1,l-=1,3&d){case 0:i.mode=16193;break;case 1:if(J5(i),i.mode=gh,e===Eh){d>>>=2,l-=2;break t}break;case 2:i.mode=16196;break;case 3:t.msg="invalid block type",i.mode=Le}d>>>=2,l-=2;break;case 16193:for(d>>>=7&l,l-=7&l;l<32;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if((65535&d)!=(d>>>16^65535)){t.msg="invalid stored block lengths",i.mode=Le;break}if(i.length=65535&d,d=0,l=0,i.mode=Rf,e===Eh)break t;case Rf:i.mode=16195;case 16195:if(p=i.length,p){if(p>a&&(p=a),p>c&&(p=c),p===0)break t;r.set(n.subarray(o,o+p),s),a-=p,o+=p,c-=p,s+=p,i.length-=p;break}i.mode=zr;break;case 16196:for(;l<14;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(i.nlen=257+(31&d),d>>>=5,l-=5,i.ndist=1+(31&d),d>>>=5,l-=5,i.ncode=4+(15&d),d>>>=4,l-=4,i.nlen>286||i.ndist>30){t.msg="too many length or distance symbols",i.mode=Le;break}i.have=0,i.mode=16197;case 16197:for(;i.have<i.ncode;){for(;l<3;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}i.lens[lt[i.have++]]=7&d,d>>>=3,l-=3}for(;i.have<19;)i.lens[lt[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,H={bits:i.lenbits},L=fd(0,i.lens,0,19,i.lencode,0,i.work,H),i.lenbits=H.bits,L){t.msg="invalid code lengths set",i.mode=Le;break}i.have=0,i.mode=16198;case 16198:for(;i.have<i.nlen+i.ndist;){for(;M=i.lencode[d&(1<<i.lenbits)-1],f=M>>>24,T=M>>>16&255,R=65535&M,!(f<=l);){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(R<16)d>>>=f,l-=f,i.lens[i.have++]=R;else{if(R===16){for(ht=f+2;l<ht;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(d>>>=f,l-=f,i.have===0){t.msg="invalid bit length repeat",i.mode=Le;break}w=i.lens[i.have-1],p=3+(3&d),d>>>=2,l-=2}else if(R===17){for(ht=f+3;l<ht;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}d>>>=f,l-=f,w=0,p=3+(7&d),d>>>=3,l-=3}else{for(ht=f+7;l<ht;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}d>>>=f,l-=f,w=0,p=11+(127&d),d>>>=7,l-=7}if(i.have+p>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=Le;break}for(;p--;)i.lens[i.have++]=w}}if(i.mode===Le)break;if(i.lens[256]===0){t.msg="invalid code -- missing end-of-block",i.mode=Le;break}if(i.lenbits=9,H={bits:i.lenbits},L=fd(1,i.lens,0,i.nlen,i.lencode,0,i.work,H),i.lenbits=H.bits,L){t.msg="invalid literal/lengths set",i.mode=Le;break}if(i.distbits=6,i.distcode=i.distdyn,H={bits:i.distbits},L=fd(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,H),i.distbits=H.bits,L){t.msg="invalid distances set",i.mode=Le;break}if(i.mode=gh,e===Eh)break t;case gh:i.mode=Sh;case Sh:if(a>=6&&c>=258){t.next_out=s,t.avail_out=c,t.next_in=o,t.avail_in=a,i.hold=d,i.bits=l,B5(t,h),s=t.next_out,r=t.output,c=t.avail_out,o=t.next_in,n=t.input,a=t.avail_in,d=i.hold,l=i.bits,i.mode===zr&&(i.back=-1);break}for(i.back=0;M=i.lencode[d&(1<<i.lenbits)-1],f=M>>>24,T=M>>>16&255,R=65535&M,!(f<=l);){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(T&&!(240&T)){for(A=f,N=T,O=R;M=i.lencode[O+((d&(1<<A+N)-1)>>A)],f=M>>>24,T=M>>>16&255,R=65535&M,!(A+f<=l);){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}d>>>=A,l-=A,i.back+=A}if(d>>>=f,l-=f,i.back+=f,i.length=R,T===0){i.mode=16205;break}if(32&T){i.back=-1,i.mode=zr;break}if(64&T){t.msg="invalid literal/length code",i.mode=Le;break}i.extra=15&T,i.mode=16201;case 16201:if(i.extra){for(ht=i.extra;l<ht;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}i.length+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;M=i.distcode[d&(1<<i.distbits)-1],f=M>>>24,T=M>>>16&255,R=65535&M,!(f<=l);){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(!(240&T)){for(A=f,N=T,O=R;M=i.distcode[O+((d&(1<<A+N)-1)>>A)],f=M>>>24,T=M>>>16&255,R=65535&M,!(A+f<=l);){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}d>>>=A,l-=A,i.back+=A}if(d>>>=f,l-=f,i.back+=f,64&T){t.msg="invalid distance code",i.mode=Le;break}i.offset=R,i.extra=15&T,i.mode=16203;case 16203:if(i.extra){for(ht=i.extra;l<ht;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}i.offset+=d&(1<<i.extra)-1,d>>>=i.extra,l-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=Le;break}i.mode=16204;case 16204:if(c===0)break t;if(p=h-c,i.offset>p){if(p=i.offset-p,p>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=Le;break}p>i.wnext?(p-=i.wnext,g=i.wsize-p):g=i.wnext-p,p>i.length&&(p=i.length),m=i.window}else m=r,g=s-i.offset,p=i.length;p>c&&(p=c),c-=p,i.length-=p;do r[s++]=m[g++];while(--p);i.length===0&&(i.mode=Sh);break;case 16205:if(c===0)break t;r[s++]=i.length,c--,i.mode=Sh;break;case vf:if(i.wrap){for(;l<32;){if(a===0)break t;a--,d|=n[o++]<<l,l+=8}if(h-=c,t.total_out+=h,i.total+=h,4&i.wrap&&h&&(t.adler=i.check=si(i)?Ei(i.check,r,h,s-h):cd(i.check,r,h,s-h)),h=c,4&i.wrap&&(si(i)?d:aN(d))!==i.check){t.msg="incorrect data check",i.mode=Le;break}d=0,l=0}i.mode=16207;case 16207:if(i.wrap&&si(i)){for(;l<32;){if(a===0)break t;a--,d+=n[o++]<<l,l+=8}if(4&i.wrap&&d!==(4294967295&i.total)){t.msg="incorrect length check",i.mode=Le;break}d=0,l=0}i.mode=16208;case 16208:L=Y5;break t;case Le:L=rN;break t;case 16210:return oN;default:return Fn}return t.next_out=s,t.avail_out=c,t.next_in=o,t.avail_in=a,i.hold=d,i.bits=l,(i.wsize||h!==t.avail_out&&i.mode<Le&&(i.mode<vf||e!==nN))&&pN(t,t.output,t.next_out,h-t.avail_out),u-=t.avail_in,h-=t.avail_out,t.total_in+=u,t.total_out+=h,i.total+=h,4&i.wrap&&h&&(t.adler=i.check=si(i)?Ei(i.check,r,h,t.next_out-h):cd(i.check,r,h,t.next_out-h)),t.data_type=i.bits+(i.last?64:0)+(i.mode===zr?128:0)+(i.mode===gh||i.mode===Rf?256:0),(u===0&&h===0||e===nN)&&L===ms&&(L=z5),L},Xr={inflateReset:dN,inflateReset2:lN,inflateResetKeep:cN,inflateInit:t=>uN(t,15),inflateInit2:uN,inflate:Q5,inflateEnd:t=>{if(fs(t))return Fn;let e=t.state;return e.window&&(e.window=null),t.state=null,ms},inflateGetHeader:(t,e)=>{if(fs(t))return Fn;const i=t.state;return 2&i.wrap?(i.head=e,e.done=!1,ms):Fn},inflateSetDictionary:(t,e)=>{const i=e.length;let n,r,o;return fs(t)?Fn:(n=t.state,n.wrap!==0&&n.mode!==fh?Fn:n.mode===fh&&(r=1,r=cd(r,e,i,0),r!==n.check)?rN:(o=pN(t,e,i,i),o?(n.mode=16210,oN):(n.havedict=1,ms)))},inflateInfo:"pako inflate (from Nodeca project)"},Z5=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 _N=Object.prototype.toString,{Z_NO_FLUSH:$5,Z_FINISH:t4,Z_OK:gd,Z_STREAM_END:If,Z_NEED_DICT:Af,Z_STREAM_ERROR:e4,Z_DATA_ERROR:EN,Z_MEM_ERROR:i4}=Ua;function Sd(t){this.options=uh.assign({chunkSize:65536,windowBits:15,to:""},t||{});const e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new eN,this.strm.avail_out=0;let i=Xr.inflateInit2(this.strm,e.windowBits);if(i!==gd)throw new Error(hs[i]);if(this.header=new Z5,Xr.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Ed.string2buf(e.dictionary):_N.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(i=Xr.inflateSetDictionary(this.strm,e.dictionary),i!==gd)))throw new Error(hs[i])}function bf(t,e){const i=new Sd(e);if(i.push(t),i.err)throw i.msg||hs[i.err];return i.result}Sd.prototype.push=function(t,e){const i=this.strm,n=this.options.chunkSize,r=this.options.dictionary;let o,s,a;if(this.ended)return!1;for(s=e===~~e?e:e===!0?t4:$5,_N.call(t)==="[object ArrayBuffer]"?i.input=new Uint8Array(t):i.input=t,i.next_in=0,i.avail_in=i.input.length;;){for(i.avail_out===0&&(i.output=new Uint8Array(n),i.next_out=0,i.avail_out=n),o=Xr.inflate(i,s),o===Af&&r&&(o=Xr.inflateSetDictionary(i,r),o===gd?o=Xr.inflate(i,s):o===EN&&(o=Af));i.avail_in>0&&o===If&&i.state.wrap>0&&t[i.next_in]!==0;)Xr.inflateReset(i),o=Xr.inflate(i,s);switch(o){case e4:case EN:case Af:case i4:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(i.avail_out===0||o===If))if(this.options.to==="string"){let c=Ed.utf8border(i.output,i.next_out),d=i.next_out-c,l=Ed.buf2string(i.output,c);i.next_out=d,i.avail_out=n-d,d&&i.output.set(i.output.subarray(c,c+d),0),this.onData(l)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==gd||a!==0){if(o===If)return o=Xr.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(i.avail_in===0)break}}return!0},Sd.prototype.onData=function(t){this.chunks.push(t)},Sd.prototype.onEnd=function(t){t===gd&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=uh.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};var n4={Inflate:Sd,inflate:bf,inflateRaw:function(t,e){return(e=e||{}).raw=!0,bf(t,e)},ungzip:bf,constants:Ua};const{Deflate:SH,deflate:r4,deflateRaw:TH,gzip:RH}=F5,{Inflate:vH,inflate:o4,inflateRaw:CH,ungzip:yH}=n4;var s4=r4,a4=o4,mN=function(t){return t[t.ONE_BYTE=0]="ONE_BYTE",t[t.TWO_BYTE=1]="TWO_BYTE",t}(mN||{});class c4{constructor(){S(this,"_sequence",0),S(this,"_startTime",Date.now()),S(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 i={commonPacketHeader:{length:0,reserved:0,extension:0,sequence:this.sequence},commonStreamHeader:this.startTime,extension:void 0,payload:e};if(e.byteLength>128){const a=new Uint8Array(4);a.set([1,0,0,0]);const c={id:0,length:4,data:a.buffer},d={profile:this.isUseOneByte?0:1,length:this.isUseOneByte?5:6,datas:[c]};i.commonPacketHeader.extension=1,i.extension=d,i.payload=this.compress(e),i.commonPacketHeader.length=8+(i.extension.length+2)+i.payload.byteLength}else i.commonPacketHeader.length=8+i.payload.byteLength;y("SHOW_DATASTREAM2_LOG")&&_.debug("send data header: ".concat(JSON.stringify(i.commonPacketHeader)));const n=new ArrayBuffer(i.commonPacketHeader.length),r=new Uint8Array(n),o=new DataView(n);let s=0;if(o.setUint16(s,i.commonPacketHeader.extension<<15|i.commonPacketHeader.reserved<<14|i.commonPacketHeader.length,!0),s+=2,o.setUint32(s,i.commonPacketHeader.sequence,!0),s+=4,o.setUint16(s,i.commonStreamHeader,!0),s+=2,i.extension){const a=this.serializeExtension(i.extension);r.set(new Uint8Array(a),s),s+=a.byteLength}if(r.set(new Uint8Array(i.payload),s),s+=i.payload.byteLength,s!==i.commonPacketHeader.length)throw Error("serialize error!");return n}deserialize(e){if(e.byteLength<4)return new ArrayBuffer(0);const i=new DataView(e);let n=0;const r=i.getUint16(n,!0);n+=2;const o={length:16383&r,reserved:(16384&r)>>14,extension:(32768&r)>>15,sequence:i.getUint16(n+2,!0)<<16|i.getUint16(n,!0)};let s,a;if(n+=4,y("SHOW_DATASTREAM2_LOG")&&_.debug("receive data header: ".concat(JSON.stringify(o))),i.getUint16(n,!0),n+=2,o.extension){a=this.deserializeExtension(e.slice(n)),n+=2+a.length,s=e.slice(n);let c=!1;if(a.datas.length>0){const d=a.datas.find(l=>l.id===0);d&&(c=(1&new DataView(d.data).getUint32(0,!0))==1)}s=c?this.decompress(s):s}else s=e.slice(8);return s}serializeExtension(e){const{profile:i,length:n,datas:r}=e,o=new ArrayBuffer(n+2),s=new Uint8Array(o),a=new DataView(o);let c=0;if(a.setUint8(c++,i),a.setUint8(c++,n),r.forEach(d=>{i?(a.setUint8(c++,d.id),a.setUint8(c++,d.length),s.set(new Uint8Array(d.data),c),c+=d.data.byteLength):(a.setUint8(c++,d.id|d.length<<4),s.set(new Uint8Array(d.data),c),c+=d.data.byteLength)}),c!==n+2)throw Error("serialize extension error, is ".concat(c,"!==").concat(n+2));return o}deserializeExtension(e){const i=new DataView(e);let n=0;const r=i.getUint8(n);n++;const o=i.getUint8(n);n++;const s=r===mN.TWO_BYTE,a=[],c=new DataView(e,2);let d=0;for(;d<o;){let l=0,u=0,h=new ArrayBuffer(0);s?(l=c.getUint8(d),d++,u=c.getUint8(d),d++):(l=15&c.getUint8(d),u=c.getUint8(d)>>4,d++),u>0&&(h=c.buffer.slice(d+2,d+2+u),d+=h.byteLength),a.push({id:l,length:u,data:h})}if(d!==o)throw Error("parse error");return{profile:r,length:o,datas:a}}decompress(e){return a4(new Uint8Array(e))}compress(e){return s4(new Uint8Array(e))}}const d4={name:"DataStream",create:(t,e)=>{const i=e?new g3(t):new S3(t);return i.useDataStream(new c4),i}};class l4 extends $t{constructor(e,i,n){super(),S(this,"ws",void 0),S(this,"requestId",1),S(this,"heartBeatTimer",void 0),S(this,"joinInfo",void 0),S(this,"clientId",void 0),S(this,"onOpen",()=>{this.emit("open"),this.startHeartBeatCheck()}),S(this,"onClose",r=>{this.emit("close"),this.dispose()}),S(this,"onMessage",r=>{const o=JSON.parse(r.data);if(!o||o.command!=="serverResponse"||!o.requestId)return o&&o.command==="serverStatus"&&o.serverStatus&&o.serverStatus.command?(this.emit("status",o.serverStatus),void this.emit(o.serverStatus.command,o.serverStatus)):void 0;this.emit("req_".concat(o.requestId),o)}),this.joinInfo=e,this.clientId=i,this.ws=new Gc("cross-channel-".concat(this.clientId),n),this.ws.on(dt.RECONNECTING,()=>{this.ws.reconnectMode="retry",this.emit("reconnecting")}),this.ws.on(dt.CONNECTED,this.onOpen),this.ws.on(dt.ON_MESSAGE,this.onMessage),this.ws.on(dt.CLOSED,this.onClose)}isConnect(){return this.ws.state==="connected"}sendMessage(e){const i=this.requestId++;return e.requestId=i,e.seq=i,this.ws.sendMessage(e),i}waitStatus(e){return new K((i,n)=>{const r=window.setTimeout(()=>{n(new P(v.TIMEOUT,"wait status timeout, status: ".concat(e)))},5e3);this.once(e,o=>{window.clearTimeout(r),o.state&&o.state!==0?n(new P(v.CROSS_CHANNEL_WAIT_STATUS_ERROR,"wait status error, status: ".concat(e))):i(void 0)}),this.once("dispose",()=>{window.clearTimeout(r),n(new P(v.WS_ABORT))})})}request(e){return C(this,null,function*(){if(this.ws.state==="closed")throw new P(v.WS_DISCONNECT);const i=()=>new K((s,a)=>{this.ws.once(dt.CLOSED,()=>a(new P(v.WS_ABORT))),this.ws.once(dt.CONNECTED,s)});this.ws.state!=="connected"&&(yield i());const n=this.sendMessage(e),r=new K((s,a)=>{const c=()=>{a(new P(v.WS_ABORT))};this.ws.once(dt.RECONNECTING,c),this.ws.once(dt.CLOSED,c),this.once("req_".concat(n),s),Ue(3e3).then(()=>{this.removeAllListeners("req_".concat(n)),this.ws.off(dt.RECONNECTING,c),this.ws.off(dt.CLOSED,c),a(new P(v.TIMEOUT,"cross channel ws request timeout"))})}),o=yield r;if(!o||o.code!==200)throw new P(v.CROSS_CHANNEL_SERVER_ERROR_RESPONSE,"response: ".concat(JSON.stringify(o)));return o})}connect(e){return C(this,null,function*(){this.ws.removeAllListeners(dt.REQUEST_NEW_URLS),this.ws.on(dt.REQUEST_NEW_URLS,i=>{i(e)}),yield this.ws.init(e)})}dispose(){this.clearHeartBeatCheck(),this.emit("dispose"),this.removeAllListeners(),this.ws.close()}sendPing(e){const i=this.requestId++;return e.requestId=i,this.ws.sendMessage(e),i}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 u4 extends $t{set state(e){e!==this._state&&(e!==Di.RELAY_STATE_FAILURE&&(this.errorCode=va.RELAY_OK),this.emit("state",e,this.errorCode),this._state=e)}get state(){return this._state}constructor(e,i,n,r,o){super(),S(this,"joinInfo",void 0),S(this,"sid",void 0),S(this,"clientId",void 0),S(this,"cancelToken",Ti.CancelToken.source()),S(this,"workerToken",void 0),S(this,"requestId",0),S(this,"signal",void 0),S(this,"prevChannelMediaConfig",void 0),S(this,"httpRetryConfig",void 0),S(this,"_resolution",void 0),S(this,"_state",Di.RELAY_STATE_IDLE),S(this,"errorCode",va.RELAY_OK),S(this,"onStatus",s=>{_.debug("[".concat(this.clientId,"] ChannelMediaStatus: ").concat(JSON.stringify(s))),s&&s.command&&(s.command==="onAudioPacketReceived"&&this.emit("event",Wr.PACKET_RECEIVED_AUDIO_FROM_SRC),s.command==="onVideoPacketReceived"&&this.emit("event",Wr.PACKET_RECEIVED_VIDEO_FROM_SRC),s.command==="onSrcTokenPrivilegeDidExpire"&&(this.errorCode=va.SRC_TOKEN_EXPIRED,this.state=Di.RELAY_STATE_FAILURE),s.command==="onDestTokenPrivilegeDidExpire"&&(this.errorCode=va.DEST_TOKEN_EXPIRED,this.state=Di.RELAY_STATE_FAILURE))}),S(this,"onReconnect",()=>C(this,null,function*(){_.debug("[".concat(this.clientId,"] ChannelMediaSocket disconnect, reconnecting")),this.emit("event",Wr.NETWORK_DISCONNECTED),this.state=Di.RELAY_STATE_IDLE,this.prevChannelMediaConfig&&this.sendStartRelayMessage(this.prevChannelMediaConfig).catch(s=>{this.state!==Di.RELAY_STATE_IDLE&&(_.error("auto restart channel media relay failed",s.toString()),this.errorCode=va.SERVER_CONNECTION_LOST,this.state=Di.RELAY_STATE_FAILURE)})})),this.joinInfo=e,this.clientId=i,this.sid=Zo(),this.signal=new l4(this.joinInfo,this.clientId,n),this.httpRetryConfig=r,this._resolution=o}startChannelMediaRelay(e){return C(this,null,function*(){if(this.state!==Di.RELAY_STATE_IDLE)throw new P(v.INVALID_OPERATION);this.state=Di.RELAY_STATE_CONNECTING,yield this.connect(),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: connect success"));try{yield this.sendStartRelayMessage(e)}catch(i){throw i.data&&i.data.serverResponse&&i.data.serverResponse.command==="SetSourceChannel"?new P(v.CROSS_CHANNEL_FAILED_JOIN_SRC):i.data&&i.data.serverResponse&&i.serverResponse.command==="SetDestChannelStatus"?new P(v.CROSS_CHANNEL_FAILED_JOIN_DEST):i.data&&i.data.serverResponse&&i.serverResponse.command==="StartPacketTransfer"?new P(v.CROSS_CHANNEL_FAILED_PACKET_SENT_TO_DEST):i}this.prevChannelMediaConfig=e})}updateChannelMediaRelay(e){return C(this,null,function*(){if(this.state!==Di.RELAY_STATE_RUNNING)throw new P(v.INVALID_OPERATION);yield this.sendUpdateMessage(e),this.prevChannelMediaConfig=e})}setVideoProfile(e){return C(this,null,function*(){if(this._resolution=e,this.state!==Di.RELAY_STATE_RUNNING)throw new P(v.INVALID_OPERATION);const i=this.genMessage(_i.SetVideoProfile);yield this.signal.request(i),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: setVideoProfile success"))})}stopChannelMediaRelay(){return C(this,null,function*(){yield this.sendStopRelayMessage(),_.debug("[".concat(this.clientId,"] stopChannelMediaRelay: send stop message success")),this.state=Di.RELAY_STATE_IDLE,this.dispose()})}dispose(){_.debug("[".concat(this.clientId,"] disposeChannelMediaRelay")),this.cancelToken.cancel(),this.cancelToken=Ti.CancelToken.source(),this.state=Di.RELAY_STATE_IDLE,this.emit("dispose"),this.signal.dispose(),this.prevChannelMediaConfig=void 0}connect(){return C(this,null,function*(){const e=yield yW(this.joinInfo,this.cancelToken.token,this.httpRetryConfig);this.workerToken=e.workerToken,yield this.signal.connect(e.addressList),this.emit("event",Wr.NETWORK_CONNECTED),this.signal.on("status",this.onStatus),this.signal.on("reconnecting",this.onReconnect)})}sendStartRelayMessage(e){return C(this,null,function*(){const i=this.genMessage(_i.StopPacketTransfer);yield this.signal.request(i),yield this.signal.waitStatus("Normal Quit"),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: StopPacketTransfer success"));const n=this.genMessage(_i.SetSdkProfile,e);yield this.signal.request(n),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSdkProfile success"));const r=this.genMessage(_i.SetSourceChannel,e);yield this.signal.request(r),yield this.signal.waitStatus("SetSourceChannelStatus"),this.emit("event",Wr.PACKET_JOINED_SRC_CHANNEL),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceChannel success"));const o=this.genMessage(_i.SetSourceUserId,e);yield this.signal.request(o),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetSourceUserId success"));const s=this.genMessage(_i.SetDestChannel,e);yield this.signal.request(s),yield this.signal.waitStatus("SetDestChannelStatus"),this.emit("event",Wr.PACKET_JOINED_DEST_CHANNEL),_.debug("[".concat(this.clientId,"] startChannelMediaRelay: SetDestChannel success"));const a=this.genMessage(_i.StartPacketTransfer,e);yield this.signal.request(a),this.emit("event",Wr.PACKET_SENT_TO_DEST_CHANNEL),this.state=Di.RELAY_STATE_RUNNING,_.debug("[".concat(this.clientId,"] startChannelMediaRelay: StartPacketTransfer success")),this.setVideoProfile(this._resolution)})}sendUpdateMessage(e){return C(this,null,function*(){const i=this.genMessage(_i.UpdateDestChannel,e);yield this.signal.request(i),this.emit("event",Wr.PACKET_UPDATE_DEST_CHANNEL),_.debug("[".concat(this.clientId,"] sendUpdateMessage: UpdateDestChannel success"))})}sendStopRelayMessage(){return C(this,null,function*(){const e=this.genMessage(_i.StopPacketTransfer);yield this.signal.request(e),_.debug("[".concat(this.clientId,"] sendStopRelayMessage: StopPacketTransfer success"))})}genMessage(e,i){const n=[],r=[],o=[];this.requestId+=1;const s={appId:this.joinInfo.appId,cname:this.joinInfo.cname,uid:this.joinInfo.uid.toString(),sdkVersion:dn,sid:this.sid,ts:Date.now(),requestId:this.requestId,seq:this.requestId,allocate:!0,clientRequest:{}};s.sdkVersion==="4.23.4"&&(s.sdkVersion="0.0.1");let a=null,c=null;switch(e){case _i.SetSdkProfile:return s.clientRequest={command:"SetSdkProfile",type:"multi_channel"},s;case _i.SetSourceChannel:if(c=i&&i.getSrcChannelMediaInfo(),!c)throw new P(v.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceChannel",uid:"0",channelName:c.channelName,token:c.token||this.joinInfo.appId},s;case _i.SetSourceUserId:if(c=i&&i.getSrcChannelMediaInfo(),!c)throw new P(v.UNEXPECTED_ERROR,"can not find source config");return s.clientRequest={command:"SetSourceUserId",uid:c.uid+""},s;case _i.SetDestChannel:if(a=i&&i.getDestChannelMediaInfo(),!a)throw new P(v.UNEXPECTED_ERROR,"can not find dest config");return a.forEach(d=>{n.push(d.channelName),r.push(d.uid+""),o.push(d.token||this.joinInfo.appId)}),s.clientRequest={command:"SetDestChannel",channelName:n,uid:r,token:o},s;case _i.StartPacketTransfer:return s.clientRequest={command:"StartPacketTransfer"},s;case _i.Reconnect:return s.clientRequest={command:"Reconnect"},s;case _i.StopPacketTransfer:return s.clientRequest={command:"StopPacketTransfer"},s;case _i.UpdateDestChannel:if(a=i&&i.getDestChannelMediaInfo(),!a)throw new P(v.UNEXPECTED_ERROR,"can not find dest config");return a.forEach(d=>{n.push(d.channelName),r.push(d.uid+""),o.push(d.token||this.joinInfo.appId)}),s.clientRequest={command:"UpdateDestChannel",channelName:n,uid:r,token:o},s;case _i.SetVideoProfile:s.clientRequest={command:"SetVideoProfile",width:this._resolution.width,height:this._resolution.height}}return s}}const h4={name:"ChannelMediaRelay",create:function(t){return new u4(t.joinInfo,t.clientId,t.websocketRetryConfig||ge,t.httpRetryConfig||ge,t.resolution)}};function fN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Td(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?fN(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):fN(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}class p4 extends $t{constructor(e,i,n,r){super(),S(this,"spec",void 0),S(this,"token",void 0),S(this,"websocket",void 0),S(this,"pingpongTimer",void 0),S(this,"reconnectMode","retry"),S(this,"serviceMode",void 0),S(this,"reqId",0),S(this,"commandReqId",0),S(this,"handleWebSocketOpen",()=>{this.reconnectMode="retry",this.startPingPong()}),S(this,"handleWebSocketMessage",o=>{if(!o.data)return;const s=JSON.parse(o.data);s.requestId?this.emit("@".concat(s.requestId,"-").concat(s.sid),s):(Z.workerEvent(this.spec.sid,{actionType:"status",serverCode:s.code,workerType:this.serviceMode===Gr.TRANSCODE?1:2}),this.emit(fo.PUBLISH_STREAM_STATUS,s))}),this.spec=i,this.token=e,this.serviceMode=r,this.websocket=new Gc("live-streaming",n),this.websocket.on(dt.CONNECTED,this.handleWebSocketOpen),this.websocket.on(dt.ON_MESSAGE,this.handleWebSocketMessage),this.websocket.on(dt.REQUEST_NEW_URLS,(o,s)=>{We(this,fo.REQUEST_NEW_ADDRESS).then(o).catch(s)}),this.websocket.on(dt.RECONNECTING,()=>{this.websocket.reconnectMode=this.reconnectMode})}init(e){return this.websocket.init(e)}request(e,i,n,r){return C(this,null,function*(){this.reqId+=1,e==="request"&&(this.commandReqId+=1);const o=this.commandReqId,s=this.reqId;if(!s||!this.websocket)throw new P(v.UNEXPECTED_ERROR);const a=Td({command:e,sdkVersion:dn==="4.23.4"?"0.0.1":dn,seq:s,requestId:s,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)},i);if(this.websocket.state==="closed")throw new P(v.WS_DISCONNECT);const c=()=>new K((h,p)=>{this.websocket.once(dt.CLOSED,()=>p(new P(v.WS_ABORT))),this.websocket.once(dt.CONNECTED,h)});this.websocket.state!=="connected"&&(yield c()),a.clientRequest&&(a.clientRequest.workerToken=this.token);const d=new K((h,p)=>{const g=()=>{p(new P(v.WS_ABORT))};this.websocket.once(dt.RECONNECTING,g),this.websocket.once(dt.CLOSED,g),this.once("@".concat(s,"-").concat(this.spec.sid),m=>{h(m)})});r&&Z.workerEvent(this.spec.sid,Td(Td({},r),{},{requestId:o,actionType:"request",payload:JSON.stringify(i.clientRequest),serverCode:0,code:0}));const l=Date.now();this.websocket.sendMessage(a);let u=null;try{u=yield d}catch(h){if(this.websocket.state==="closed")throw h;return yield c(),yield this.request(e,i,n)}return r&&Z.workerEvent(this.spec.sid,Td(Td({},r),{},{requestId:o,actionType:"response",payload:JSON.stringify(u.serverResponse),serverCode:u.code,success:u.code===200,responseTime:Date.now()-l})),u.code!==200&&this.handleResponseError(u),u})}tryNextAddress(){this.reconnectMode="tryNext",this.websocket.reconnect("tryNext")}close(){const e=dn==="4.23.4"?"0.0.1":dn;this.reqId+=1,this.websocket.state==="connected"?(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 Ce.LIVE_STREAM_RESPONSE_ALREADY_EXISTS_STREAM:return void _.warning("live stream response already exists stream");case Ce.LIVE_STREAM_RESPONSE_TRANSCODING_PARAMETER_ERROR:case Ce.LIVE_STREAM_RESPONSE_BAD_STREAM:case Ce.LIVE_STREAM_RESPONSE_WM_PARAMETER_ERROR:return new P(v.LIVE_STREAMING_INVALID_ARGUMENT,"",{code:e.code}).throw();case Ce.LIVE_STREAM_RESPONSE_WM_WORKER_NOT_EXIST:if(e.serverResponse.command==="UnpublishStream")return;throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Ce.LIVE_STREAM_RESPONSE_NOT_AUTHORIZED:return new P(v.LIVE_STREAMING_PUBLISH_STREAM_NOT_AUTHORIZED,"",{code:e.code}).throw();case Ce.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const i=new P(v.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE);return this.emit(fo.WARNING,i,e.serverResponse.url)}case Ce.LIVE_STREAM_RESPONSE_REQUEST_TOO_OFTEN:{const i=new P(v.LIVE_STREAMING_WARN_FREQUENT_REQUEST);return this.emit(fo.WARNING,i,e.serverResponse.url)}case Ce.LIVE_STREAM_RESPONSE_NOT_FOUND_PUBLISH:throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream response wm worker not exist",{retry:!0});case Ce.LIVE_STREAM_RESPONSE_NOT_SUPPORTED:return new P(v.LIVE_STREAMING_TRANSCODING_NOT_SUPPORTED,"",{code:e.code}).throw();case Ce.LIVE_STREAM_RESPONSE_MAX_STREAM_NUM:{const i=new P(v.LIVE_STREAMING_WARN_STREAM_NUM_REACH_LIMIT);return this.emit(fo.WARNING,i,e.serverResponse.url)}case Ce.LIVE_STREAM_RESPONSE_INTERNAL_SERVER_ERROR:return new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code}).throw();case Ce.LIVE_STREAM_RESPONSE_RESOURCE_LIMIT:throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"live stream resource limit",{retry:!0,changeAddress:!0});case Ce.LIVE_STREAM_RESPONSE_WORKER_LOST:case Ce.LIVE_STREAM_RESPONSE_WORKER_QUIT:if(e.serverResponse.command==="UnpublishStream")return;throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Ce.ERROR_FAIL_SEND_MESSAGE:if(e.serverResponse.command==="UnpublishStream")return;if(e.serverResponse.command==="UpdateTranscoding"||e.serverResponse.command==="ControlStream")return new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{code:e.code}).throw();throw new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"error fail send message",{retry:!0,changeAddress:!0});case Ce.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:return new P(v.LIVE_STREAMING_CDN_ERROR,"",{code:e.code}).throw()}}startPingPong(){this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(()=>{this.websocket.state==="connected"&&this.request("ping",{}).catch(lu)},6e3)}}function gN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Pi(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?gN(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):gN(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}class _4 extends $t{constructor(e){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ge,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ge;super(),S(this,"onLiveStreamWarning",void 0),S(this,"onLiveStreamError",void 0),S(this,"spec",void 0),S(this,"retryTimeout",1e4),S(this,"connection",void 0),S(this,"httpRetryConfig",void 0),S(this,"wsRetryConfig",void 0),S(this,"streamingTasks",new Map),S(this,"isStartingStreamingTask",!1),S(this,"taskMutex",new qe("live-streaming")),S(this,"cancelToken",Ti.CancelToken.source()),S(this,"transcodingConfig",void 0),S(this,"uapResponse",void 0),S(this,"lastTaskId",1),S(this,"statusError",new Map),this.spec=e,this.httpRetryConfig=n,this.wsRetryConfig=i}setTranscodingConfig(e){return C(this,null,function*(){const i=Pi(Pi({},nW),e);i.videoCodecProfile!==66&&i.videoCodecProfile!==77&&i.videoCodecProfile!==100&&(_.debug("[".concat(this.spec.clientId,"] set transcoding config, fix video codec profile: ").concat(i.videoCodecProfile," -> 100")),i.videoCodecProfile=100),i.transcodingUsers||(i.transcodingUsers=i.userConfigs),i.transcodingUsers&&(i.transcodingUsers=i.transcodingUsers.map(s=>Pi(Pi(Pi({},iW),s),{},{zOrder:s.zOrder?s.zOrder+1:1}))),function(s){re(s.width)||xt(s.width,"config.width",0,1e4),re(s.height)||xt(s.height,"config.height",0,1e4),re(s.videoBitrate)||xt(s.videoBitrate,"config.videoBitrate",1,1e6),re(s.videoFrameRate)||xt(s.videoFrameRate,"config.videoFrameRate"),re(s.lowLatency)||Fr(s.lowLatency,"config.lowLatency"),re(s.audioSampleRate)||Ae(s.audioSampleRate,"config.audioSampleRate",[32e3,44100,48e3]),re(s.audioBitrate)||xt(s.audioBitrate,"config.audioBitrate",1,128),re(s.audioChannels)||Ae(s.audioChannels,"config.audioChannels",[1,2,3,4,5]),re(s.videoGop)||xt(s.videoGop,"config.videoGop"),re(s.videoCodecProfile)||Ae(s.videoCodecProfile,"config.videoCodecProfile",[66,77,100]),re(s.userCount)||xt(s.userCount,"config.userCount",0,17),re(s.backgroundColor)||xt(s.backgroundColor,"config.backgroundColor",0,16777215),re(s.userConfigExtraInfo)||Me(s.userConfigExtraInfo,"config.userConfigExtraInfo",0,4096,!1),s.transcodingUsers&&!re(s.transcodingUsers)&&(Br(s.transcodingUsers,"config.transcodingUsers"),s.transcodingUsers.forEach((a,c)=>{ku(a.uid),re(a.x)||xt(a.x,"transcodingUser[".concat(c,"].x"),0,1e4),re(a.y)||xt(a.y,"transcodingUser[".concat(c,"].y"),0,1e4),re(a.width)||xt(a.width,"transcodingUser[".concat(c,"].width"),0,1e4),re(a.height)||xt(a.height,"transcodingUser[".concat(c,"].height"),0,1e4),re(a.zOrder)||xt(a.zOrder-1,"transcodingUser[".concat(c,"].zOrder"),0,100),re(a.alpha)||xt(a.alpha,"transcodingUser[".concat(c,"].alpha"),0,1,!1)})),re(s.watermark)||Im(s.watermark,"watermark"),re(s.backgroundImage)||Im(s.backgroundImage,"backgroundImage"),s.images&&!re(s.images)&&(Br(s.images,"config.images"),s.images.forEach((a,c)=>{Im(a,"images[".concat(c,"]"))}))}(i);const n=[];i.images&&n.push(...i.images.map(s=>Pi(Pi(Pi({},ym),s),{},{zOrder:255}))),i.backgroundImage&&(n.push(Pi(Pi(Pi({},ym),i.backgroundImage),{},{zOrder:0})),delete i.backgroundImage),i.watermark&&(n.push(Pi(Pi(Pi({},ym),i.watermark),{},{zOrder:255})),delete i.watermark),i.images=n,i.transcodingUsers&&(i.userConfigs=i.transcodingUsers.map(s=>Pi({},s)),i.userCount=i.transcodingUsers.length,delete i.transcodingUsers);const r=(i.userConfigs||[]).map(s=>typeof s.uid=="number"?K.resolve(s.uid):jw(s.uid,this.spec,this.cancelToken.token,this.httpRetryConfig));if((yield K.all(r)).forEach((s,a)=>{i.userConfigs&&i.userConfigs[a]&&(i.userConfigs[a].uid=s)}),this.transcodingConfig=i,this.connection)try{var o;const s=yield this.connection.request("request",{clientRequest:{command:"UpdateTranscoding",transcodingConfig:this.transcodingConfig}},!1,{command:"UpdateTranscoding",workerType:1,requestByUser:!0,tid:Array.from(Ui(o=this.streamingTasks).call(o)).map(a=>a.taskId).join("#")});_.debug("[".concat(this.spec.clientId,"] update live transcoding config success, code: ").concat(s.code,", config:"),JSON.stringify(this.transcodingConfig))}catch(s){if(!s.data||!s.data.retry)throw s;s.data.changeAddress&&this.connection.tryNextAddress(),this.streamingTasks.forEach(a=>{_.warning("[".concat(this.spec.clientId,"] live streaming receive error"),s.toString(),"try to republish",a.url),this.startLiveStreamingTask(a.url,a.mode,s).then(()=>{_.debug("[".concat(this.spec.clientId,"] live streaming republish ").concat(a.url," success"))}).catch(c=>{_.error("[".concat(this.spec.clientId,"] live streaming republish failed"),a.url,c.toString()),this.onLiveStreamError&&this.onLiveStreamError(a.url,c)})})}})}startLiveStreamingTask(e,i,n){return C(this,null,function*(){if(!this.transcodingConfig&&i===Gr.TRANSCODE)throw new P(v.INVALID_OPERATION,"[LiveStreaming] no transcoding config found, can not start transcoding streaming task");const r={command:"PublishStream",ts:Date.now(),url:e,uid:this.spec.uid.toString(),autoDestroyTime:100,acceptImageTimeout:!0};_.debug("[".concat(this.spec.clientId,"] start live streaming ").concat(e,", mode: ").concat(i));const o=yield this.taskMutex.lock();if(!this.connection&&n)return void o();if(this.streamingTasks.get(e)&&!n)return o(),new P(v.LIVE_STREAMING_TASK_CONFLICT).throw();try{this.connection||(this.connection=yield this.connect(i))}catch(a){throw o(),a}switch(i){case Gr.TRANSCODE:r.transcodingConfig=Pi({},this.transcodingConfig)}this.uapResponse&&this.uapResponse.vid&&(r.vid=this.uapResponse.vid),this.isStartingStreamingTask=!0;const s=this.lastTaskId++;try{const a=new K((d,l)=>{Ue(this.retryTimeout).then(()=>{if(n)return l(n);const u=this.statusError.get(e);return u?(this.statusError.delete(e),l(u)):void 0})}),c=yield K.race([this.connection.request("request",{clientRequest:r},!0,{url:e,command:"PublishStream",workerType:i===Gr.TRANSCODE?1:2,requestByUser:!n,tid:s.toString()}),a]);this.isStartingStreamingTask=!1,_.debug("[".concat(this.spec.clientId,"] live streaming started, code: ").concat(c.code)),this.streamingTasks.set(e,{clientRequest:r,mode:i,url:e,taskId:s}),o()}catch(a){if(o(),this.isStartingStreamingTask=!1,!a.data||!a.data.retry||n)throw a;return a.data.changeAddress?(this.connection.tryNextAddress(),yield this.startLiveStreamingTask(e,i,a)):yield this.startLiveStreamingTask(e,i,a)}})}stopLiveStreamingTask(e){return new K((i,n)=>{const r=this.streamingTasks.get(e);if(!r||!this.connection)return new P(v.UNEXPECTED_ERROR,"can not find streaming task to stop").throw();const o=r.mode;r.abortTask=()=>{_.debug("[".concat(this.spec.clientId,"] stop live streaming success(worker exception)")),this.streamingTasks.delete(e),i()},this.connection.request("request",{clientRequest:{command:"UnpublishStream",url:r.url}},!1,{url:e,command:"UnPublishStream",workerType:o===Gr.TRANSCODE?1:2,requestByUser:!0,tid:(this.lastTaskId++).toString()}).then(s=>{_.debug("[".concat(this.spec.clientId,"] stop live streaming success, code: ").concat(s.code)),this.streamingTasks.delete(e),this.streamingTasks.size===0&&(this.connection&&this.connection.close(),this.connection=void 0),i()}).catch(n)})}resetAllTask(){var e;const i=Array.from(Ui(e=this.streamingTasks).call(e));this.terminate();for(const n of i)this.startLiveStreamingTask(n.url,n.mode).catch(r=>{this.onLiveStreamError&&this.onLiveStreamError(n.url,r)})}terminate(){this.cancelToken&&this.cancelToken.cancel(),this.streamingTasks=new Map,this.isStartingStreamingTask=!1,this.statusError=new Map,this.cancelToken=Ti.CancelToken.source(),this.uapResponse=void 0,this.connection&&this.connection.close(),this.connection=void 0}connect(e){return C(this,null,function*(){if(this.connection)throw new P(v.UNEXPECTED_ERROR,"live streaming connection has already connected");const i=yield We(this,Am.REQUEST_WORKER_MANAGER_LIST,e);return this.uapResponse=i,this.connection=new p4(i.workerToken,this.spec,this.wsRetryConfig,e),this.connection.on(fo.WARNING,(n,r)=>this.onLiveStreamWarning&&this.onLiveStreamWarning(r,n)),this.connection.on(fo.PUBLISH_STREAM_STATUS,n=>this.handlePublishStreamServer(n)),this.connection.on(fo.REQUEST_NEW_ADDRESS,(n,r)=>{if(!this.connection)return r(new P(v.UNEXPECTED_ERROR,"can not get new live streaming address list"));We(this,Am.REQUEST_WORKER_MANAGER_LIST,e).then(o=>{this.uapResponse=o,n(o.addressList)}).catch(r)}),yield this.connection.init(i.addressList),this.connection})}handlePublishStreamServer(e){const i=e.serverStatus&&e.serverStatus.url||"empty_url",n=this.streamingTasks.get(i),r=e.reason;switch(e.code){case Ce.PUBLISH_STREAM_STATUS_ERROR_PUBLISH_BROKEN:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_CONNECT:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_HANDSHAKE:case Ce.PUBLISH_STREAM_STATUS_ERROR_RTMP_PUBLISH:{const s=new P(v.LIVE_STREAMING_CDN_ERROR,"",{code:e.code});if(n)return _.error(s.toString()),this.onLiveStreamError&&this.onLiveStreamError(i,s);if(!this.isStartingStreamingTask)return;this.statusError.set(i,s)}case Ce.LIVE_STREAM_RESPONSE_FAILED_LOAD_IMAGE:{const s=new P(v.LIVE_STREAMING_WARN_FAILED_LOAD_IMAGE,r);return this.onLiveStreamWarning&&this.onLiveStreamWarning(i,s)}case Ce.LIVE_STREAM_RESPONSE_WORKER_LOST:case Ce.LIVE_STREAM_RESPONSE_WORKER_QUIT:{var o;if(!this.connection)return;this.connection.tryNextAddress();const s=Array.from(Ui(o=this.streamingTasks).call(o));for(const a of s)a.abortTask?a.abortTask():(_.warning("[".concat(this.spec.clientId,"] publish stream status code"),e.code,"try to republish",a.url),this.startLiveStreamingTask(a.url,a.mode,new P(v.LIVE_STREAMING_INTERNAL_SERVER_ERROR,"",{code:e.code})).then(()=>{_.debug("[".concat(this.spec.clientId,"] republish live stream success"),a.url)}).catch(c=>{_.error(c.toString()),this.onLiveStreamError&&this.onLiveStreamError(a.url,c)}));return}}}hasUrl(e){return this.streamingTasks.has(e)}}const E4={name:"LiveStreaming",create:function(t){return new _4(t.joinInfo,t.websocketRetryConfig||ge,t.httpRetryConfig||ge)}};function m4(t){let e=RN();return function(i,n){let r=i.appId;r!==void 0&&(Dt(n,10),Or(n,r));let o=i.cid;o!==void 0&&(Dt(n,16),Dt(n,o));let s=i.cname;s!==void 0&&(Dt(n,26),Or(n,s));let a=i.deviceId;a!==void 0&&(Dt(n,34),Or(n,a));let c=i.elapse;c!==void 0&&(Dt(n,40),Do(n,c));let d=i.fileSize;d!==void 0&&(Dt(n,48),Do(n,Ba(d)));let l=i.height;l!==void 0&&(Dt(n,56),Do(n,Ba(l)));let u=i.jpg;u!==void 0&&(Dt(n,66),Dt(n,u.length),function(Ii,U){let B=ja(Ii,U.length);Ii.bytes.set(U,B)}(n,u));let h=i.networkType;h!==void 0&&(Dt(n,72),Do(n,Ba(h)));let p=i.osType;p!==void 0&&(Dt(n,80),Do(n,Ba(p)));let g=i.requestId;g!==void 0&&(Dt(n,90),Or(n,g));let m=i.sdkVersion;m!==void 0&&(Dt(n,98),Or(n,m));let f=i.sequence;f!==void 0&&(Dt(n,104),Do(n,Ba(f)));let T=i.sid;T!==void 0&&(Dt(n,114),Or(n,T));let R=i.timestamp;R!==void 0&&(Dt(n,120),Do(n,R));let A=i.uid;A!==void 0&&(Dt(n,128),Dt(n,A));let N=i.vid;N!==void 0&&(Dt(n,136),Dt(n,N));let O=i.width;O!==void 0&&(Dt(n,144),Do(n,Ba(O)));let w=i.service;w!==void 0&&(Dt(n,152),Dt(n,w));let L=i.callbackData;L!==void 0&&(Dt(n,162),Or(n,L));let M=i.jpgEncryption;M!==void 0&&(Dt(n,168),Dt(n,M));let j=i.requestType;j!==void 0&&(Dt(n,176),Dt(n,j));let H=i.scorePorn;H!==void 0&&(Dt(n,185),Pf(n,H));let ht=i.scoreSexy;ht!==void 0&&(Dt(n,193),Pf(n,ht));let lt=i.scoreNeutral;lt!==void 0&&(Dt(n,201),Pf(n,lt));let rt=i.scene;rt!==void 0&&(Dt(n,208),Dt(n,rt));let Kt=i.ossFilePrefix;Kt!==void 0&&(Dt(n,218),Or(n,Kt));let Ft=i.serviceVendor;if(Ft!==void 0)for(let Ii of Ft){Dt(n,226);let U=RN();S4(Ii,U),Dt(n,U.limit),C4(n,U),v4(U)}}(t,e),function(i){let n=i.bytes,r=i.limit;return n.length===r?n:n.subarray(0,r)}(e)}function f4(t){return function(i){let n={};t:for(;!vN(i);){let r=Nr(i);switch(r>>>3){case 0:break t;case 1:n.code=Nr(i);break;case 2:n.msg=CN(i,Nr(i));break;case 3:{let o=T4(i);n.data=g4(i),i.limit=o;break}default:SN(i,7&r)}}return n}({bytes:e=t,offset:0,limit:e.length});var e}function g4(t){let e={};t:for(;!vN(t);){let i=Nr(t);switch(i>>>3){case 0:break t;case 1:e.requestId=CN(t,Nr(t));break;case 2:e.requestType=Nr(t)>>>0;break;case 3:e.scorePorn=Df(t);break;case 4:e.scoreSexy=Df(t);break;case 5:e.scoreNeutral=Df(t);break;case 6:e.requestScene=Nr(t)>>>0;break;case 7:e.scene=Nr(t)>>>0;break;default:SN(t,7&i)}}return e}function S4(t,e){let i=t.service;i!==void 0&&(Dt(e,8),Dt(e,i));let n=t.vendor;n!==void 0&&(Dt(e,16),Dt(e,n));let r=t.token;r!==void 0&&(Dt(e,26),Or(e,r));let o=t.callbackUrl;o!==void 0&&(Dt(e,34),Or(e,o))}function T4(t){let e=Nr(t),i=t.limit;return t.limit=t.offset+e,i}function SN(t,e){switch(e){case 0:for(;128&yN(t););break;case 2:Of(t,Nr(t));break;case 5:Of(t,4);break;case 1:Of(t,8);break;default:throw new Error("Unimplemented type: "+e)}}let R4=new Float32Array(1);new Uint8Array(R4.buffer);let wf=new Float64Array(1),Li=new Uint8Array(wf.buffer);function Ba(t){return{low:t|=0,high:t>>31,unsigned:t>=0}}let TN=[];function RN(){const t=TN.pop();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function v4(t){TN.push(t)}function Of(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function vN(t){return t.offset>=t.limit}function ja(t,e){let i=t.bytes,n=t.offset,r=t.limit,o=n+e;if(o>i.length){let s=new Uint8Array(2*o);s.set(i),t.bytes=s}return t.offset=o,o>r&&(t.limit=o),n}function Nf(t,e){let i=t.offset;if(i+e>t.limit)throw new Error("Read past limit");return t.offset+=e,i}function CN(t,e){let i=Nf(t,e),n=String.fromCharCode,r=t.bytes,o="<22>",s="";for(let a=0;a<e;a++){let c,d,l,u,h=r[a+i];128&h?(224&h)==192?a+1>=e?s+=o:(c=r[a+i+1],(192&c)!=128?s+=o:(u=(31&h)<<6|63&c,u<128?s+=o:(s+=n(u),a++))):(240&h)==224?a+2>=e?s+=o:(c=r[a+i+1],d=r[a+i+2],(49344&(c|d<<8))!=32896?s+=o:(u=(15&h)<<12|(63&c)<<6|63&d,u<2048||u>=55296&&u<=57343?s+=o:(s+=n(u),a+=2))):(248&h)==240?a+3>=e?s+=o:(c=r[a+i+1],d=r[a+i+2],l=r[a+i+3],(12632256&(c|d<<8|l<<16))!=8421504?s+=o:(u=(7&h)<<18|(63&c)<<12|(63&d)<<6|63&l,u<65536||u>1114111?s+=o:(u-=65536,s+=n(55296+(u>>10),56320+(1023&u)),a+=3))):s+=o:s+=n(h)}return s}function Or(t,e){let i=e.length,n=0;for(let s=0;s<i;s++){let a=e.charCodeAt(s);a>=55296&&a<=56319&&s+1<i&&(a=(a<<10)+e.charCodeAt(++s)-56613888),n+=a<128?1:a<2048?2:a<65536?3:4}Dt(t,n);let r=ja(t,n),o=t.bytes;for(let s=0;s<i;s++){let a=e.charCodeAt(s);a>=55296&&a<=56319&&s+1<i&&(a=(a<<10)+e.charCodeAt(++s)-56613888),a<128?o[r++]=a:(a<2048?o[r++]=a>>6&31|192:(a<65536?o[r++]=a>>12&15|224:(o[r++]=a>>18&7|240,o[r++]=a>>12&63|128),o[r++]=a>>6&63|128),o[r++]=63&a|128)}}function C4(t,e){let i=ja(t,e.limit),n=t.bytes,r=e.bytes;for(let o=0,s=e.limit;o<s;o++)n[o+i]=r[o]}function yN(t){return t.bytes[Nf(t,1)]}function IN(t,e){let i=ja(t,1);t.bytes[i]=e}function Df(t){let e=Nf(t,8),i=t.bytes;return Li[0]=i[e++],Li[1]=i[e++],Li[2]=i[e++],Li[3]=i[e++],Li[4]=i[e++],Li[5]=i[e++],Li[6]=i[e++],Li[7]=i[e++],wf[0]}function Pf(t,e){let i=ja(t,8),n=t.bytes;wf[0]=e,n[i++]=Li[0],n[i++]=Li[1],n[i++]=Li[2],n[i++]=Li[3],n[i++]=Li[4],n[i++]=Li[5],n[i++]=Li[6],n[i++]=Li[7]}function Nr(t){let e,i=0,n=0;do e=yN(t),i<32&&(n|=(127&e)<<i),i+=7;while(128&e);return n}function Dt(t,e){for(e>>>=0;e>=128;)IN(t,127&e|128),e>>>=7;IN(t,e)}function Do(t,e){let i=e.low>>>0,n=(e.low>>>28|e.high<<4)>>>0,r=e.high>>>24,o=r===0?n===0?i<16384?i<128?1:2:i<1<<21?3:4:n<16384?n<128?5:6:n<1<<21?7:8:r<128?9:10,s=ja(t,o),a=t.bytes;switch(o){case 10:a[s+9]=r>>>7&1;case 9:a[s+8]=o!==9?128|r:127&r;case 8:a[s+7]=o!==8?n>>>21|128:n>>>21&127;case 7:a[s+6]=o!==7?n>>>14|128:n>>>14&127;case 6:a[s+5]=o!==6?n>>>7|128:n>>>7&127;case 5:a[s+4]=o!==5?128|n:127&n;case 4:a[s+3]=o!==4?i>>>21|128:i>>>21&127;case 3:a[s+2]=o!==3?i>>>14|128:i>>>14&127;case 2:a[s+1]=o!==2?i>>>7|128:i>>>7&127;case 1:a[s]=o!==1?128|i:127&i}}function AN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}const y4=new Map([["moderation",1],["supervise",2]]);class I4 extends $t{get connectionState(){return this._connectionState}set connectionState(e){if(this._connectionState===e)return;const i=this._connectionState;this._connectionState=e,this.emit(Pe.CONNECTION_STATE_CHANGE,i,e)}get inspectType(){return this._inspectType}set inspectType(e){var i;this._inspectMode=Tn(i=e.map(n=>y4.get(n)||0)).call(i,(n,r)=>n+r),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(),S(this,"name","AgoraRTCVideoContentInspect"),S(this,"_connectionState",Pn.CONNECTING),S(this,"_innerConnectionState",void 0),S(this,"sequence",0),S(this,"inspectStartTime",void 0),S(this,"workerManagerConnection",void 0),S(this,"workerConnection",void 0),S(this,"workerMessageLengthLimit",void 0),S(this,"inspectIntervalMinimum",void 0),S(this,"qualityRatio",void 0),S(this,"_connectInfo",void 0),S(this,"_cancelTokenSource",Ti.CancelToken.source()),S(this,"_retryConfig",void 0),S(this,"wmSequence",0),S(this,"inspectInterval",void 0),S(this,"inspectTimer",null),S(this,"ossFilePrefix",void 0),S(this,"extraInfo",void 0),S(this,"_inspectType",void 0),S(this,"_inspectMode",void 0),S(this,"_quality",1),S(this,"qualityTimer",null),S(this,"_inspectId",void 0),S(this,"_needWorkUrlOnly",!1),S(this,"inspectImage",()=>{if(this.connectionState!==Pn.CONNECTED)throw new P(v.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===Pn.CONNECTED?this.requestToInspectImage():_.debug("[".concat(this._inspectId,"] Inspect State is not connected , "),this.connectionState)},this.inspectInterval<this.inspectIntervalMinimum?this.inspectIntervalMinimum:this.inspectInterval),this.requestToInspectImage()}),this._inspectId=Gt(5,"inspect-"),this.workerMessageLengthLimit=y("VIDEO_INSPECT_WORKER_MESSAGE_LENGTH_LIMIT"),this.inspectIntervalMinimum=y("VIDEO_INSPECT_INTERVAL_MINIMUM"),this.qualityRatio=y("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 Gc("worker-manager-"+this._inspectId,ge),this.on(Pe.STATE_CHANGE,(i,n)=>{this._innerConnectionState=i,_.debug("[".concat(this._inspectId,"] Inspect operation :").concat(Ln[i]," ").concat(n||""))}),this.handleWorkerManagerEvents(),this.workerConnection=new Gc("worker-"+this._inspectId,ge),this.handleWorkerEvents()}init(e,i){return C(this,null,function*(){this.emit(Pe.STATE_CHANGE,Ln.CONNECT_AP),this._connectInfo=e;const n=this._cancelTokenSource.token;return this._retryConfig=i,new K((r,o)=>{this.on(Pe.CONNECTION_STATE_CHANGE,(s,a)=>{a===Pn.CONNECTED&&r()}),this.requestAP(e,n,i).then(s=>{this.connectWorkerManager(s)}).catch(s=>{o(s)})})})}requestAP(e,i,n){return C(this,null,function*(){const r=y("WEBCS_DOMAIN").map(a=>"https://".concat(a,"/api/v1")),o=yield function(a,c,d,l){let{appId:u,areaCode:h,cname:p,sid:g,token:m,uid:f}=c;Oa++;const T="image_moderation_api",R={service_name:T,json_body:JSON.stringify({appId:u,areaCode:h,cname:p,command:"allocateEdge",requestId:Oa,seq:Oa,sid:g,token:m,ts:Date.now(),uid:f+""})};let A,N,O=a[0];return Jn(()=>C(this,null,function*(){A=Date.now();const w=yield er(O,{data:R,cancelToken:d,headers:{"X-Packet-Service-Type":"0","X-Packet-URI":"61"},params:{action:"wrtc_gateway"}});if(N=Date.now()-A,w.code!==0){const H=new P(v.UNEXPECTED_RESPONSE,"image inspect ap error, code"+w.code,{retry:!0,responseTime:N});throw _.error(H.toString()),H}const L=JSON.parse(w.json_body);if(L.code!==200){const H=new P(v.UNEXPECTED_RESPONSE,"image inspect ap error, code: ".concat(L.code,", reason: ").concat(L.reason),{code:L.code,responseTime:N});throw _.error(H.toString()),H}if(!L.servers||!Array.isArray(L.servers)||L.servers.length===0){const H=new P(v.UNEXPECTED_RESPONSE,"image inspect ap empty server",{code:L.code,responseTime:N});throw _.error(H.toString()),H}const M=y("VIDEO_INSPECT_WORKER_MANAGER_HOST"),j=y("VIDEO_INSPECT_WORKER_MANAGER_PORT");return{addressList:L.servers.map(H=>{let{address:ht,wss:lt}=H;if(ht&&lt)return"wss://".concat(ht.replace(/\./g,"-"),".").concat(M,":").concat(j||lt)}).filter(H=>!!H),workerToken:L.workerToken,vid:L.vid,responseTime:N}}),(w,L)=>(Z.apworkerEvent(g,{success:!0,sc:200,serviceName:T,responseDetail:JSON.stringify(w.addressList),firstSuccess:L===0,responseTime:N,serverIp:a[L%a.length]}),!1),(w,L)=>(Z.apworkerEvent(g,{success:!1,sc:w.data&&w.data.code||200,serviceName:T,responseTime:N,serverIp:a[L%a.length]}),!!(w.code!==v.OPERATION_ABORTED&&w.code!==v.UNEXPECTED_RESPONSE||w.data&&w.data.retry)&&(O=a[(L+1)%a.length],!0)),l)}(r,e,i,n);this.emit(Pe.STATE_CHANGE,Ln.AP_CONNECTED);const{addressList:s}=o;return this.wmSequence++,s})}connectWorkerManager(i){return C(this,arguments,function*(e){let n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._needWorkUrlOnly=n,this.emit(Pe.STATE_CHANGE,Ln.CONNECT_WORKER_MANAGER),yield this.workerManagerConnection.init(e,1e4)})}connectWorker(e){return C(this,null,function*(){yield this.workerConnection.init([e])})}handleWorkerManagerEvents(){this.workerManagerConnection.on(dt.CONNECTED,()=>C(this,null,function*(){this.emit(Pe.STATE_CHANGE,Ln.WORKER_MANAGER_CONNECTED,this.workerManagerConnection.url),this.workerManagerConnection.sendMessage({appId:this._connectInfo.appId,cname:this._connectInfo.cname,uid:this._connectInfo.uid+"",sdkVersion:"4.23.4",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(dt.CLOSED,()=>{this._innerConnectionState<Ln.GET_WORKER_MANAGER_RESPONSE&&_.debug("[".concat(this._inspectId,"] Inspect worker manager is closed before connecting worker"))}),this.workerManagerConnection.on(dt.FAILED,()=>{this._innerConnectionState<Ln.GET_WORKER_MANAGER_RESPONSE&&_.debug("[".concat(this._inspectId,"] Connecting inspect worker manager is failed before connecting worker"))}),this.workerManagerConnection.on(dt.RECONNECTING,()=>{this._innerConnectionState<Ln.GET_WORKER_MANAGER_RESPONSE&&_.debug("[".concat(this._inspectId,"] Inspect worker manager is reconnecting before connecting worker"))}),this.workerManagerConnection.on(dt.ON_MESSAGE,e=>C(this,null,function*(){this.emit(Pe.STATE_CHANGE,Ln.GET_WORKER_MANAGER_RESPONSE);const i=this.workerManagerConnection.url;this.workerManagerConnection.close();const n=JSON.parse(e.data);if(n.code!==200)throw _.error("[".concat(this._inspectId,"] Unexpected code ").concat(n.code," from worker manager")),new P(v.UNEXPECTED_RESPONSE,"response code of worker is unexpected",n);if(!(n.serverResponse&&n.serverResponse.portWss&&i))throw _.error("[".concat(this._inspectId,"] Unexpected content from worker manager : ").concat(JSON.stringify(n))),new P(v.UNEXPECTED_RESPONSE,"response content of worker is unexpected",n);{const r=y("VIDEO_INSPECT_WORKER_PORT")||n.serverResponse.portWss,o=i.replace(/:\d+\/?$/,":".concat(r));this.emit(Pe.STATE_CHANGE,Ln.CONNECT_WORKER,o),this._needWorkUrlOnly?this.emit(Pe.REQUEST_NEW_WORKER_URL,o):yield this.connectWorker(o)}})),this.workerManagerConnection.on(dt.WILL_RECONNECT,(e,i,n)=>{n(e)}),this.workerManagerConnection.on(dt.REQUEST_NEW_URLS,(e,i)=>{this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(e).catch(i)})}handleWorkerEvents(){this.workerConnection.on(dt.CONNECTED,()=>C(this,null,function*(){this.emit(Pe.STATE_CHANGE,Ln.WORKER_CONNECTED,this.workerConnection.url),this.connectionState=Pn.CONNECTED})),this.workerConnection.on(dt.ON_MESSAGE,e=>C(this,null,function*(){if(e.data instanceof ArrayBuffer){const n=f4(new Uint8Array(e.data));if(y("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")&&_.debug("[".concat(this._inspectId,"] Response message for worker of inspect content "),JSON.stringify(n)),n.code===200){if(Array.isArray(this.inspectType)&&this.inspectType.length===1&&this.inspectType[0]==="supervise")return void this.emit(Pe.INSPECT_RESULT,void 0,void 0);if(n.data&&n.data.scorePorn&&n.data.scoreSexy&&n.data.scoreNeutral){var i;const r={porn:n.data.scorePorn,sexy:n.data.scoreSexy,neutral:n.data.scoreNeutral},o=Tn(i=Object.keys(r)).call(i,(a,c)=>r[a]>r[c]?a:c,"porn"),s=Object.keys(r).find(a=>a===o);this.emit(Pe.INSPECT_RESULT,s)}else this.emit(Pe.INSPECT_RESULT,void 0,new P(v.UNEXPECTED_RESPONSE,n.code+"","There is an unexpected data on message"))}else this.emit(Pe.INSPECT_RESULT,void 0,new P(v.UNEXPECTED_RESPONSE,n.code+"",n.msg))}else _.error("[".concat(this._inspectId,"] Unexpected message type from worker")),this.emit(Pe.INSPECT_RESULT,void 0,new P(v.UNEXPECTED_RESPONSE,"invalid worker message type"))})),this.workerConnection.on(dt.CLOSED,()=>{this.connectionState=Pn.CLOSED}),this.workerConnection.on(dt.FAILED,()=>{this.connectionState=Pn.CLOSED}),this.workerConnection.on(dt.RECONNECTING,()=>{this.connectionState=this.connectionState===Pn.CONNECTED?Pn.RECONNECTING:Pn.CONNECTING}),this.workerConnection.on(dt.WILL_RECONNECT,(e,i,n)=>{e==="recover"&&n(e),n("tryNext")}),this.workerConnection.on(dt.REQUEST_NEW_URLS,(e,i)=>{this.workerManagerConnection.close(),this.once(Pe.REQUEST_NEW_WORKER_URL,n=>{e([n])}),this.requestAP(this._connectInfo,this._cancelTokenSource.token,this._retryConfig).then(n=>{this.connectWorkerManager(n,!0)}).catch(n=>{i(n)})})}requestToInspectImage(){return C(this,null,function*(){this.sequence++;const e=zi(this,Pe.CLIENT_LOCAL_VIDEO_TRACK),i={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(Pe.INSPECT_RESULT,void 0,new P(v.INVALID_OPERATION,"Only the track being played can be inspected"));const n=yield this.generateRequestData(e,i);this.workerConnection.sendMessage(n,!0,!0)}else this.emit(Pe.INSPECT_RESULT,void 0,new P(v.INVALID_OPERATION,"Only the track being published can be inspected"))})}generateRequestData(e,i){return C(this,null,function*(){let{appId:n,cname:r,cid:o,vid:s,sid:a,uid:c}=i;const d=Date.now(),l=yield e.getCurrentFrameImage("image/jpeg",this.quality),u=yield cA(l,n,r),h=this.sequence+"-"+o+"-"+c+"-"+d+"-"+Gt(12,""),p={appId:n,cid:o,cname:r,deviceId:"",elapse:(g=Number(d-this.inspectStartTime),{low:g|=0,high:g>>31,unsigned:g>=0}),fileSize:u.byteLength,jpgEncryption:2,height:l.height,width:l.width,jpg:u,networkType:6,osType:7,requestId:h,sdkVersion:"4.23.4",sequence:this.sequence,sid:a,timestamp:k0(d),uid:c,vid:s,service:this._inspectMode,callbackData:this.extraInfo,ossFilePrefix:this.ossFilePrefix};var g;this.extraInfo===void 0&&delete p.callbackData,this.ossFilePrefix===void 0&&delete p.ossFilePrefix;const m=m4(p);if(m.byteLength<this.workerMessageLengthLimit){if(y("SHOW_VIDEO_INSPECT_WORKER_MESSAGE")){const f=function(T){for(var R=1;R<arguments.length;R++){var A=arguments[R]!=null?arguments[R]:{};R%2?AN(Object(A),!0).forEach(function(N){S(T,N,A[N])}):Object.getOwnPropertyDescriptors?Object.defineProperties(T,Object.getOwnPropertyDescriptors(A)):AN(Object(A)).forEach(function(N){Object.defineProperty(T,N,Object.getOwnPropertyDescriptor(A,N))})}return T}({},p);delete f.jpg,_.debug("[".concat(this._inspectId,"] Request message for worker of inspect content "),JSON.stringify(f))}return m}{const f=this.quality*this.qualityRatio;return this.quality=f,yield this.generateRequestData(e,{appId:n,cname:r,cid:o,vid:s,sid:a,uid:c})}})}close(){this._cancelTokenSource.cancel(),this._cancelTokenSource=Ti.CancelToken.source(),this.workerManagerConnection&&this.workerManagerConnection.close(),this.workerConnection&&this.workerConnection.close(),this.inspectTimer&&window.clearInterval(this.inspectTimer),this.inspectTimer=null,this.connectionState=Pn.CLOSED,this.emit(Pe.STATE_CHANGE,Ln.CLOSED)}}const A4={name:"ContentInspect",create:function(t){let{config:e}=t;return function(i){if(!i)throw new P(v.INVALID_PARAMS,"inspectConfig is necessary.");if(!i.inspectType||!Array.isArray(i.inspectType))throw new P(v.INVALID_PARAMS,"inspectConfig.inspectType is necessary and is an instance of Array.");{const n=[...new Set(i.inspectType)];n.forEach(r=>{var o;if(!G(o=["supervise","moderation"]).call(o,r))throw new P(v.INVALID_PARAMS,"".concat(r," is not a valid inspect type."))}),i.inspectType=n}if(i&&i.extraInfo&&i.extraInfo.length>1024)throw new P(v.INVALID_PARAMS,"inspectConfig.extraInfo length cannot exceed 1024 bytes")}(e),new I4(e)}};var bN=Pt(sn.Object.getOwnPropertySymbols),b4=Nt,w4=Hh.indexOf,O4=kd,Lf=Ka([].indexOf),wN=!!Lf&&1/Lf([1],1,-0)<0;b4({target:"Array",proto:!0,forced:wN||!O4("indexOf")},{indexOf:function(t){var e=arguments.length>1?arguments[1]:void 0;return wN?Lf(this,t,e)||0:w4(this,t,e)}});var N4=Sn("Array","indexOf"),D4=$e,P4=N4,kf=Array.prototype,L4=function(t){var e=t.indexOf;return t===kf||D4(kf,t)&&e===kf.indexOf?P4:e},ON=Pt(L4);function k4(t,e){if(t==null)return{};var i,n,r=function(s,a){if(s==null)return{};var c={};for(var d in s)if({}.hasOwnProperty.call(s,d)){if(ON(a).call(a,d)!==-1)continue;c[d]=s[d]}return c}(t,e);if(bN){var o=bN(t);for(n=0;n<o.length;n++)i=o[n],ON(e).call(e,i)===-1&&{}.propertyIsEnumerable.call(t,i)&&(r[i]=t[i])}return r}let NN=class{get localCapabilities(){return te(this._localCapabilities)}get rtpCapabilities(){return te(this._rtpCapabilities)}get candidates(){return te(this._candidates)}get iceParameters(){return te(this._iceParameters)}get dtlsParameters(){return te(this._dtlsParameters)}constructor(t){S(this,"sessionDesc",void 0),S(this,"_localCapabilities",void 0),S(this,"_rtpCapabilities",void 0),S(this,"_candidates",void 0),S(this,"_iceParameters",void 0),S(this,"_dtlsParameters",void 0),S(this,"setup",void 0),S(this,"currentMidIndex",void 0),S(this,"cname","o/i14u9pJrxRKAsu"),S(this,"firefoxSsrcMidMap",new Map),t=te(t);const{remoteIceParameters:e,remoteDtlsParameters:i,candidates:n,remoteRTPCapabilities:r,localCapabilities:o,direction:s,setup:a,videoCodec:c,audioCodec:d}=t;let l;this.setup=a,l=s===pi.RECEIVE_ONLY?Ni(`v=0
o=- 0 0 IN IP4 127.0.0.1
s=AgoraGateway
t=0 0
a=group:BUNDLE 0 1
a=msid-semantic: WMS
a=extmap-allow-mixed
m=video 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 127.0.0.1
a=rtcp:9 IN IP4 0.0.0.0
a=sendonly
a=rtcp-mux
a=rtcp-rsize
a=mid:0
m=audio 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 127.0.0.1
a=rtcp:9 IN IP4 0.0.0.0
a=sendonly
a=rtcp-mux
a=rtcp-rsize
a=mid:1
`):Ni(`v=0
o=- 0 0 IN IP4 127.0.0.1
s=AgoraGateway
t=0 0
a=group:BUNDLE 0 1
a=msid-semantic: WMS
a=extmap-allow-mixed
m=video 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 127.0.0.1
a=rtcp:9 IN IP4 0.0.0.0
a=recvonly
a=rtcp-mux
a=rtcp-rsize
a=mid:0
m=audio 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 127.0.0.1
a=rtcp:9 IN IP4 0.0.0.0
a=recvonly
a=rtcp-mux
a=rtcp-rsize
a=mid:1
`),this._rtpCapabilities=r,this._candidates=n,this._iceParameters=e,this._dtlsParameters=i,this._localCapabilities=o;const u=s===pi.RECEIVE_ONLY?this.rtpCapabilities.send:this.rtpCapabilities.recv,h=s===pi.RECEIVE_ONLY?this._localCapabilities.recv:this._localCapabilities.send,p=s===pi.RECEIVE_ONLY?r.send.videoCodecs:Kc(q.VIDEO,u,h,c),g=s===pi.RECEIVE_ONLY?r.send.audioCodecs:Kc(q.AUDIO,u,h,d);for(const m of l.mediaDescriptions)m.attributes.iceUfrag=e.iceUfrag,m.attributes.icePwd=e.icePwd,m.attributes.fingerprints=i.fingerprints,m.attributes.candidates=n,m.attributes.setup=this.setup,m.media.mediaType==="application"&&(m.attributes.sctpPort="5000"),m.media.mediaType==="video"&&(m.media.fmts=p.map(f=>f.payloadType.toString(10)),m.attributes.payloads=p,m.attributes.extmaps=u.videoExtensions),m.media.mediaType==="audio"&&(m.media.fmts=g.map(f=>f.payloadType.toString(10)),m.attributes.payloads=g,m.attributes.extmaps=u.audioExtensions,wa(m));this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return mo(this.sessionDesc)}hasMid(t){return Array.isArray(t)?t.every(e=>this.hasMid(e)):this.sessionDesc.mediaDescriptions.some(e=>e.attributes.mid===t)}send(t,e,i,n,r){i=i.replace(/ /g,"-");const{ssrcs:o,ssrcGroups:s}=as(e,this.cname,y("SYNC_GROUP")?i:void 0),a=this.findPreloadMediaDesc(o);if(a){if(ne()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,a.attributes.mid),r&&(r.twcc||r.remb)){const c=this.sessionDesc.mediaDescriptions.indexOf(a);return this.sessionDesc.mediaDescriptions[c]=this.mungSendMediaDesc(a,r),{mid:a.attributes.mid,needExchangeSDP:!0}}return{mid:a.attributes.mid,needExchangeSDP:!1}}{const c=this.findAvailableMediaIndex(t,o,n);let d;return c===-1?(d=this.createOrRecycleSendMedia(t,o,s,"sendonly",n,r),this.updateBundleMids()):(d=te(this.sessionDesc.mediaDescriptions[c]),d.attributes.direction="sendonly",d.attributes.ssrcs=o,d.attributes.ssrcGroups=s,this.sessionDesc.mediaDescriptions[c]=this.mungSendMediaDesc(d,r)),ne()&&this.firefoxSsrcMidMap.set(o[0].ssrcId,d.attributes.mid),{needExchangeSDP:!0,mid:d.attributes.mid}}}stopSending(t){const e=this.sessionDesc.mediaDescriptions.filter(i=>i.attributes.mid&&t.indexOf(i.attributes.mid)!==-1);if(e.length!==t.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.stopSending.");e.forEach(i=>{i.attributes.ssrcs=[]}),this.updateBundleMids()}receive(t,e,i){const n=[];return t.forEach(r=>{const o=r._mediaStreamTrack.kind,s=this.findAvailableRecvMediaIndex(o);let a,c=!1;s===-1?(c=!0,a=this.createOrRecycleRecvMedia(r,[],"recvonly",e,i),this.updateBundleMids()):(a=te(this.sessionDesc.mediaDescriptions[s]),a.attributes.direction="recvonly"),n.push({mid:a.attributes.mid,needCreateTransceiver:c})}),n}stopReceiving(t){const e=this.sessionDesc.mediaDescriptions.filter(i=>t.indexOf(i.attributes.mid)!==-1);if(e.length!==t.length)throw new Error("MediaDescriptions' length doesn't match mids's length when calling RemoteSDP.receive.");e.forEach(i=>{i.media.port="0",i.attributes.direction="inactive"}),this.updateBundleMids()}addRemoteCandidate(t){const{foundation:e,protocol:i,address:n,port:r,type:o,relatedAddress:s,relatedPort:a,priority:c}=new RTCIceCandidate(t),d={foundation:e!=null?e:"",componentId:"1",transport:i!=null?i:"",priority:c?c+"":"",connectionAddress:n!=null?n:"",port:r?r+"":"",type:o?o+"":"",relAddr:s!=null?s:"",relPort:a?a+"":"",extension:{}};this.candidates.some(l=>l.priority===d.priority&&l.connectionAddress===d.connectionAddress&&l.port===d.port)||(this._candidates.push(d),this.sessionDesc.mediaDescriptions.forEach(l=>{l.attributes.candidates=this.candidates}))}clearRemoteCandidate(){this._candidates=[],this.sessionDesc.mediaDescriptions[0].attributes.candidates=this._candidates}createOrRecycleRecvMedia(t,e,i,n,r){const o=t._mediaStreamTrack.kind,s=this.rtpCapabilities.recv,a=Kc(o,s,this.localCapabilities.send,o===q.AUDIO?r:n),c=o===q.VIDEO?s.videoExtensions:s.audioExtensions,d="".concat(++this.currentMidIndex);let l={media:{mediaType:o,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(h=>h.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:e,ssrcGroups:[],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.mungRecvMediaDsec(l,t);const u=this.findFirstClosedMedia(o);if(u){const h=this.sessionDesc.mediaDescriptions.indexOf(u);this.sessionDesc.mediaDescriptions[h]=l}else this.sessionDesc.mediaDescriptions.push(l);return l}muteRemote(t){const e=this.sessionDesc.mediaDescriptions.filter(i=>G(t).call(t,i.attributes.mid||""));if(e.length!==t.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");e.forEach(i=>{i.attributes.direction="inactive"})}unmuteRemote(t){const e=this.sessionDesc.mediaDescriptions.filter(i=>G(t).call(t,i.attributes.mid||""));if(e.length!==t.length)throw new Error("mediaDescriptions' length doesn't match mids' length when calling RemoteSDP.muteRemote.");e.forEach(i=>{i.attributes.direction="recvonly"})}findAvailableMediaIndex(t,e,i){return this.sessionDesc.mediaDescriptions.findIndex(n=>{const r=n.media.mediaType===t&&n.media.port!=="0"&&(n.attributes.direction==="sendonly"||n.attributes.direction==="sendrecv")&&n.attributes.ssrcs.length===0;if(ne()){if(r){const o=this.firefoxSsrcMidMap.get(e[0].ssrcId);return!(o||n.attributes.mid!=="0"&&n.attributes.mid!=="1")||!(!o||o!==n.attributes.mid)}return!1}return r&&n.attributes.mid===i})}findAvailableRecvMediaIndex(t){return this.sessionDesc.mediaDescriptions.findIndex(e=>{const i=e.media.mediaType===t&&e.media.port!=="0"&&(e.attributes.direction==="recvonly"||e.attributes.direction==="sendrecv");return e.attributes.mid!=="0"&&e.attributes.mid!=="1"&&i})}predictReceivingMids(t){const e=[];for(let i=0;i<t;i++)e.push((this.currentMidIndex+i+1).toString(10));return e}restartICE(t){t=te(t),this._iceParameters=t,this.sessionDesc.mediaDescriptions.forEach(e=>{e.attributes.iceUfrag=t.iceUfrag,e.attributes.icePwd=t.icePwd})}createOrRecycleSendMedia(t,e,i,n,r,o){const s=this.rtpCapabilities.send,a=t===q.VIDEO?s.videoCodecs:s.audioCodecs,c=t===q.VIDEO?s.videoExtensions:s.audioExtensions;ne()&&(r="".concat(++this.currentMidIndex));let d={media:{mediaType:t,port:"9",protos:["UDP","TLS","RTP","SAVPF"],fmts:a.map(u=>u.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:e,ssrcGroups:i,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:r}};d=this.mungSendMediaDesc(d,o);const l=this.findFirstClosedMedia(t);if(l){const u=this.sessionDesc.mediaDescriptions.indexOf(l);this.sessionDesc.mediaDescriptions[u]=d}else this.sessionDesc.mediaDescriptions.push(d);return d}mungRecvMediaDsec(t,e,i){const n=te(t);return Pm(n),ba(n,e),Lm(n,e),Rw(n),ju(n,i,this.localCapabilities.send),n}mungSendMediaDesc(t,e){const i=te(t);return ju(i,e,this.localCapabilities.recv),wa(i),i}updateRecvMedia(t,e){const i=this.sessionDesc.mediaDescriptions.findIndex(n=>n.attributes.mid===t);if(i!==-1){const n=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[i],e);this.sessionDesc.mediaDescriptions[i]=n}}updateBundleMids(){this.sessionDesc.attributes.groups[0].identificationTag=this.sessionDesc.mediaDescriptions.filter(t=>t.media.port!=="0").map(t=>t.attributes.mid)}findPreloadMediaDesc(t){return this.sessionDesc.mediaDescriptions.find(e=>{var i;return((i=e.attributes)===null||i===void 0||(i=i.ssrcs[0])===null||i===void 0?void 0:i.ssrcId)===t[0].ssrcId})}findFirstClosedMedia(t){return this.sessionDesc.mediaDescriptions.find(e=>ne()?e.media.port==="0"&&e.media.mediaType===t:e.media.port==="0")}};const M4=["sdp"];var qt;function DN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Po(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?DN(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):DN(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}let PN=(qt=class Wa extends nw{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,i;return(e=(i=this.peerConnection.getReceivers()[0])===null||i===void 0||(i=i.transport)===null||i===void 0?void 0:i.state)!==null&&e!==void 0?e:null}get localCodecs(){return[]}set isInRestartIce(e){this._isInRestartIce=e}get isInRestartIce(){return this._isInRestartIce}constructor(e,i,n){super(e,i),S(this,"direction",void 0),S(this,"name",void 0),S(this,"store",void 0),S(this,"spec",void 0),S(this,"peerConnection",void 0),S(this,"initialOffer",void 0),S(this,"transport",void 0),S(this,"statsFilter",void 0),S(this,"localCandidateCount",0),S(this,"_isInRestartIce",!1),S(this,"mutex",void 0),S(this,"onLocalCandidate",void 0),S(this,"remoteSDP",void 0),S(this,"pendingCandidates",[]),S(this,"localCapabilities",void 0),S(this,"isReady",!1),S(this,"restartCnt",0),S(this,"curTurnServerIndex",0),this.store=i,this.spec=e,this.mutex=new qe("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(Wa.resolvePCConfiguration(e,i.p2pTransport),{optional:[{googDscp:!0}]}),this.direction=n!=null?n:pi.SEND_ONLY,this.name=this.direction===pi.SEND_ONLY?"sendP2PConnection":"recvP2PConnection",this.statsFilter=KE(this.peerConnection,y("STATS_UPDATE_INTERVAL"),void 0,ne()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1}establish(e){return C(this,null,function*(){try{const i=yield Cw();if(this.localCapabilities=Gu(i),e){const{sdp:n}=e,r=k4(e,M4),o=function(){const l={audioCodecs:[],videoCodecs:[],audioExtensions:[],videoExtensions:[]},u=Hc(arguments.length>2?arguments[2]:void 0,arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},"sendonly"),h={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},p={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},g={audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]};if(kn(u,l,"videoExtensions",h,p,g),kn(u,l,"videoCodecs",h,p,g),kn(u,l,"audioExtensions",h,p,g),kn(u,l,"audioCodecs",h,p,g),y("RAISE_H264_BASELINE_PRIORITY")){const m=g.videoCodecs.findIndex(f=>f.rtpMap&&f.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&f.fmtp&&f.fmtp.parameters["profile-level-id"]==="42001f");if(m!==-1){const f=g.videoCodecs.findIndex(T=>T.rtpMap&&T.rtpMap.encodingName.toLocaleLowerCase()==="h264");if(f<m){_.debug("raising H264 baseline profile priority");const T=g.videoCodecs[m];g.videoCodecs.splice(m,1),g.videoCodecs.splice(f,0,T)}f!==-1&&y("FILTER_SEND_H264_BASELINE")&&(h.videoCodecs=h.videoCodecs.filter(T=>!(T.rtpMap&&T.rtpMap.encodingName.toLocaleLowerCase()==="h264"&&T.fmtp&&T.fmtp.parameters["profile-level-id"]!=="42001f")))}}return{send:h,recv:p,sendrecv:g}}({},{},n);this.remoteSDP=new NN({remoteIceParameters:r.iceParameters,remoteDtlsParameters:r.dtlsParameters,candidates:[],remoteRTPCapabilities:o,localCapabilities:this.localCapabilities,direction:this.direction,setup:"actpass",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),yield this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()}),this.isReady=!0;const s=yield this.peerConnection.createAnswer();if(!s.sdp)throw new Error("Cannot get answer sdp when trying to establish PeerConnection.");const a=Ro(s.sdp);yield this.peerConnection.setLocalDescription(s);const c=yield yw({},{},s.sdp);this.localCapabilities=Gu(c);const d=this.peerConnection.getTransceivers()[0];return d!=null&&d.receiver&&d.receiver.transport&&this.tryBindTransportEvents(d.receiver.transport),Po(Po({},a),{},{sdp:s.sdp})}{this.peerConnection.addTransceiver("video",{direction:"sendonly"}),this.peerConnection.addTransceiver("audio",{direction:"sendonly"});const n=yield this.peerConnection.createOffer();if(!n.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const r=Ro(n.sdp);return this.initialOffer=n,Po(Po({},r),{},{sdp:n.sdp})}}catch(i){throw new k(v.GET_LOCAL_CONNECTION_PARAMS_FAILED,i.toString())}})}connect(e){return C(this,null,function*(){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");yield this.peerConnection.setLocalDescription(this.initialOffer);const{sdp:i,iceParameters:n,dtlsParameters:r}=e,o=yield yw({},{},i);this.remoteSDP=new NN({remoteIceParameters:n,remoteDtlsParameters:r,candidates:[],remoteRTPCapabilities:o,localCapabilities:this.localCapabilities,direction:this.direction,setup:"active",videoCodec:this.store.codec,audioCodec:this.store.audioCodec}),yield this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()});const s=this.peerConnection.getTransceivers()[0];s!=null&&s.sender&&s.sender.transport&&this.tryBindTransportEvents(s.sender.transport)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(i.toString()))}})}addRemoteCandidate(e){return C(this,null,function*(){try{e&&this.pendingCandidates.push(e),this.peerConnection.remoteDescription&&this.isReady&&(this.pendingCandidates.forEach(i=>{this.peerConnection.addIceCandidate(i)}),this.pendingCandidates=[])}catch(i){throw new k(v.ADD_CANDIDATE_FAILED,"P2PConnection.addRemoteCandidate failed; ".concat(i.toString()))}})}send(e,i,n){var r=this;return cn(function*(){const o=yield Rt(r.mutex.lock("From P2PConnection.send"));try{if(!r.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const s=[],a=r.remoteSDP.receive(e,i,n);e.forEach((f,T)=>{if(a[T].needCreateTransceiver){const R=r.peerConnection.addTransceiver(f._mediaStreamTrack,{direction:"sendonly"});s.push(R),f._updateRtpTransceiver(R)}else{const R=r.peerConnection.getTransceivers().find(A=>A.mid===a[T].mid);if(!R)throw new Error("cannot find transceiver when sendPeerconnection send, mid is ".concat(a[T].mid));s.push(R),f._updateRtpTransceiver(R)}}),ne()&&y("SIMULCAST")===!0&&(yield Rt(r.applySimulcastForFirefox(s,e)));const c=a.map(f=>f.mid),d=yield Rt(r.peerConnection.createOffer()),l=r.mungSendOfferSDP(d.sdp,e,c),u=Ni(l),h=c.map(f=>{const T=u.mediaDescriptions.find(R=>R.attributes.mid===f);if(!T)throw new Error("Cannot extract ssrc from mediaDescription.");return gw(T,y("USE_PUB_RTX"))}),p=s.map((f,T)=>{const R=c[T];return{localSSRC:h[T],id:R}});yield Rt(r.peerConnection.setLocalDescription({type:"offer",sdp:l}));try{yield p}catch(f){const T=r.remoteSDP.toString();throw yield Rt(r.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield Rt(r.peerConnection.setRemoteDescription({type:"answer",sdp:T})),yield Rt(r.stopSending(c,!0)),f}yield Rt(r.applySimulcastEncodings(s,e)),yield Rt(r.applySendEncodings(s,e));const g=r.remoteSDP.toString(),m=r.logSDPExchange(l,"offer","local","send");return m==null||m(g),yield Rt(r.setRemoteDescription({type:"answer",sdp:g})),s.map((f,T)=>{const R=c[T];return{localSSRC:h[T],id:R}})}catch(s){throw s instanceof k?s:new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(s.toString()))}finally{o()}})()}stopSending(e,i){return C(this,null,function*(){const n=i?void 0:yield this.mutex.lock("From P2PConnection.stopSending");try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const r=this.peerConnection.getTransceivers().filter(c=>e.indexOf(c.mid)!==-1);if(r.length!==e.length)throw new Error("Transceivers' length (".concat(r.length,") doesn't match mids' length (").concat(e.length,") when trying to call P2PConnection.stopSending."));r.map(c=>{var d;c.direction="inactive",(d=c.stop)===null||d===void 0||d.call(c)});const o=yield this.peerConnection.createOffer(),s=this.logSDPExchange(o.sdp||"","offer","local","stopSending");yield this.peerConnection.setLocalDescription(o),this.remoteSDP.stopReceiving(e);const a=this.remoteSDP.toString();s==null||s(a),yield this.setRemoteDescription({type:"answer",sdp:a})}catch(r){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(r.toString()))}finally{n&&n()}})}receive(e,i,n,r){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(e,i,n,r);if(s){const c=this.remoteSDP.toString(),d=this.logSDPExchange(c,"offer","remote","receive");yield this.setRemoteDescription({type:"offer",sdp:c});const l=yield this.peerConnection.createAnswer(),u=this.mungReceiveAnswerSDP(l.sdp,o,e);d==null||d(u||""),yield this.peerConnection.setLocalDescription({type:"answer",sdp:u}),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else _.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."));const a=this.peerConnection.getTransceivers().find(c=>c.mid===o);if(!a||a.mid===null)throw new Error("Cannot get transceiver after setLocalDescription.");return{track:a.receiver.track,mid:a.mid,transceiver:a}}catch(o){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}})}mockReceive(e,i,n,r){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{mid:o,needExchangeSDP:s}=this.remoteSDP.send(e,i,n,r);if(s){const a=this.remoteSDP.toString(),c=this.logSDPExchange(a,"offer","remote","receive");yield this.setRemoteDescription({type:"offer",sdp:a});const d=yield this.peerConnection.createAnswer(),l=this.mungReceiveAnswerSDP(d.sdp,o,e);c==null||c(l||""),yield this.peerConnection.setLocalDescription({type:"answer",sdp:l}),_.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," by exchanging SDP."))}else _.debug("[".concat(this.store.clientId,"] [P2PConnection] receive ").concat(e," no need to exchange SDP."))}catch(o){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}})}stopReceiving(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const i=this.remoteSDP.toString(),n=this.logSDPExchange(i,"offer","remote","stopReceiving");yield this.setRemoteDescription({type:"offer",sdp:i});const r=yield this.peerConnection.createAnswer();n==null||n(r.sdp||""),yield this.peerConnection.setLocalDescription(r)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(i.toString()))}})}restartICE(e){return C(this,null,function*(){try{if(this.store.p2pTransport===$o.Auto&&(this.store.p2pTransport=$o.SdRtn,Ct().supportPCSetConfiguration&&this.peerConnection.setConfiguration(Wa.resolvePCConfiguration(this.spec,this.store.p2pTransport))),this.restartCnt>3&&(this.restartCnt=0,Ct().supportPCSetConfiguration&&this.peerConnection.setConfiguration(Wa.resolvePCConfiguration(this.spec,this.store.p2pTransport,++this.curTurnServerIndex))),!e){this.restartCnt++,this.isReady=!1;const i=yield this.peerConnection.createOffer({iceRestart:!0});if(!i.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const{iceParameters:n}=Ro(i.sdp);return this.store.descriptionStart(),this.direction===pi.SEND_ONLY&&(yield this.peerConnection.setLocalDescription(i)),n}if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");if(this.remoteSDP.restartICE(e),this.store.descriptionStart(),this.direction===pi.RECEIVE_ONLY){this.restartCnt++,yield this.setRemoteDescription({type:"offer",sdp:this.remoteSDP.toString()});const i=yield this.peerConnection.createAnswer();if(!i.sdp)throw new Error("Cannot get answer sdp when trying to iceRestart.");const{iceParameters:n}=Ro(i.sdp);return yield this.peerConnection.setLocalDescription(i),n}yield this.setRemoteDescription({type:"answer",sdp:this.remoteSDP.toString()}),this.isReady=!0}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(i.toString()))}})}close(){var e;this.peerConnection.close(),this.peerConnection.onicecandidate=null,(e=this.onConnectionStateChange)===null||e===void 0||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)}updateEncoderConfig(e,i){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const n=yield this.peerConnection.createOffer(),r=this.mungSendOfferSDP(n.sdp,[i],[e]);this.remoteSDP.updateRecvMedia(e,i);const o=this.remoteSDP.toString(),s=this.logSDPExchange(r,"offer","local","updateEncoderConfig");yield this.peerConnection.setLocalDescription({type:"offer",sdp:r}),s==null||s(o),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new k(v.EXCHANGE_SDP_FAILED,n.toString())}})}updateSendParameters(e,i){return C(this,null,function*(){const n=this.peerConnection.getTransceivers().filter(r=>r.mid===e);n.length===1&&(this.isVP8Simulcast(i)?ne()||(yield this.applySimulcastEncodings(n,[i])):yield this.applySendEncodings(n,[i]))})}setStatsRemoteVideoIsReady(e,i){this.statsFilter.setVideoIsReady2(e,i)}replaceTrack(e,i){return C(this,null,function*(){const n=this.peerConnection.getTransceivers().find(r=>r.mid===i);n&&(yield n.sender.replaceTrack(e._mediaStreamTrack))})}getSelectedCandidatePair(){return C(this,null,function*(){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 i=e[0].transport.iceTransport,{local:n,remote:r}=i.getSelectedCandidatePair();return{local:Po(Po({},mr),{},{candidateType:n.type,protocol:n.protocol,address:n.address,port:n.port}),remote:Po(Po({},mr),{},{candidateType:r.type,protocol:r.protocol,address:r.address,port:r.port})}}return this.statsFilter.getSelectedCandidatePair()})}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e,i;G(e=["connected","completed"]).call(e,this.peerConnection.iceConnectionState)&&(this.isReady=!1),(i=this.onICEConnectionStateChange)===null||i===void 0||i.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;this.peerConnection.connectionState==="connected"&&(this.restartCnt=0),(e=this.onConnectionStateChange)===null||e===void 0||e.call(this,this.peerConnection.connectionState)},this.startICECandidate()}startICECandidate(){this.peerConnection.onicecandidate||(this.localCandidateCount=0,this.peerConnection.onicecandidate=e=>{if(e.candidate){var i;e.candidate.candidate&&((i=this.onLocalCandidate)===null||i===void 0||i.call(this,e.candidate.toJSON())),this.localCandidateCount+=1}else _.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(e,i){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;const r={iceServers:[]};var o;return e.iceServers?r.iceServers=e.iceServers:e.turnServer&&e.turnServer.mode!=="off"&&(Nc(e.turnServer.servers)?r.iceServers=e.turnServer.servers:(r.iceServers&&r.iceServers.push(...Wa.turnServerConfigToIceServers(e.turnServer.servers,i,n)),y("USE_TURN_SERVER_OF_GATEWAY")&&r.iceServers&&e.turnServer.serversFromGateway&&r.iceServers.push(...Wa.turnServerConfigToIceServers(e.turnServer.serversFromGateway,i,n)),G(o=[$o.Relay,$o.SdRtn]).call(o,i)&&(r.iceTransportPolicy="relay"),y("FORCE_TURN_TCP")?r.iceTransportPolicy="relay":e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(s=>{s.forceturn&&(r.iceTransportPolicy="relay")}))),y("ENABLE_ENCODED_TRANSFORM")&&Ct().supportWebRTCEncodedTransform&&(r.encodedInsertableStreams=!0),_.debug("P2PConnection p2pTransport is ".concat(i)),r}static turnServerConfigToIceServers(e,i){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0;const r=[],o=e.filter(a=>a.tcpport);_.debug("P2PConnection turnServers is ".concat(o,", current index is ").concat(n));const s=o.length>n?o[n]:o[0];switch(i){case $o.SdRtn:const a=e.filter(d=>{var l;return G(l=d.username).call(l,"glb:")&&d.turnServerURL==d.turnServerURL}),c=a.length>n?a[n]:a[0];c&&(r.push({username:c.username,credential:c.password,credentialType:"password",urls:"turn:".concat(So(c.turnServerURL),":").concat(c.tcpport,"?transport=udp")}),r.push({username:c.username,credential:c.password,credentialType:"password",urls:"turns:".concat(So(c.turnServerURL),":").concat(c.tcpport,"?transport=tcp")}));break;case $o.Relay:s&&(r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(So(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}));break;default:s&&(r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turn:".concat(s.turnServerURL,":").concat(s.tcpport,"?transport=udp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"turns:".concat(So(s.turnServerURL),":").concat(s.tcpport,"?transport=tcp")}),r.push({username:s.username,credential:s.password,credentialType:"password",urls:"stun:".concat(s.turnServerURL,":").concat(s.tcpport)}))}return r}tryBindTransportEvents(e){if(e){this.transport=e,e.onstatechange=()=>{var n;e!=null&&e.state&&((n=this.onDTLSTransportStateChange)===null||n===void 0||n.call(this,e.state))},e.onerror=n=>{var r;(r=this.onDTLSTransportError)===null||r===void 0||r.call(this,"error"in n?n.error:n)};const i=e.iceTransport;i&&(i.onstatechange=()=>{const n=e==null?void 0:e.iceTransport.state;var r;n&&((r=this.onICETransportStateChange)===null||r===void 0||r.call(this,n))},i.getSelectedCandidatePair&&(i.onselectedcandidatepairchange=()=>{if(i.getSelectedCandidatePair()){const{local:n,remote:r}=i.getSelectedCandidatePair();_.info("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] selectedcandidatepairchange: local ").concat(JSON.stringify({candidateType:n.type,protocol:n.protocol}),", remote ").concat(JSON.stringify({candidateType:r.type,protocol:r.protocol,address:r.address,port:r.port})," )"))}}))}}tryUnbindTransportEvents(){this.transport&&(this.transport.onstatechange=null,this.transport.onerror=null,this.transport.iceTransport&&(this.transport.iceTransport.onstatechange=null))}updateRtpSenderEncodings(e,i){return C(this,null,function*(){var n;if(i||(i=this.peerConnection.getSenders().find(l=>l.track===e._mediaStreamTrack)),!i)return _.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(this.isVP8Simulcast(e))return _.warn("[updateRtpSenderEncodings] Track is VP8 simulcast, please apply simulcast encodings");if(!Ct().supportSetRtpSenderParameters)return _.warn("[updateRtpSenderEncodings] Browser not support set rtp-sender parameters");const r={},o={};switch(e._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;default:r.degradationPreference="balanced"}if(e._encoderConfig){var s;const{bitrateMax:l,frameRate:u,scaleResolutionDownBy:h}=e._encoderConfig;l&&(o.maxBitrate=1e3*l),G(s=e._hints).call(s,Vt.LOW_STREAM)&&(u&&(o.maxFramerate=Bi(u)),h&&h>=1&&(o.scaleResolutionDownBy=h))}if(y("DSCP_TYPE")&&Vr()){var a;const l=y("DSCP_TYPE");G(a=["very-low","low","medium","high"]).call(a,l)&&(o.networkPriority=l)}const c=i.getParameters(),d=(n=c.encodings)===null||n===void 0?void 0:n[0];ne()&&!d&&(r.encodings=[o]),d&&Object.assign(d,o),Object.assign(c,r),_.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(c.encodings))),yield i.setParameters(c)})}applySendEncodings(e,i){return C(this,null,function*(){try{if(!Ct().supportSetRtpSenderParameters||e.length!==i.length)return;for(let n=0;n<e.length;n++){const r=e[n],o=i[n];o instanceof Yt&&!this.isVP8Simulcast(o)&&(yield this.updateRtpSenderEncodings(o,r.sender))}}catch(n){_.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}})}mungSendOfferSDP(e,i,n){const r=Ni(e);return i.forEach((o,s)=>{const a=n[s],c=r.mediaDescriptions.find(d=>d.attributes.mid===a);c&&(ba(c,o),vw(c,o,this.store.codec))}),mo(r)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var i;(i=this.onFirstAudioReceived)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var i;(i=this.onFirstVideoReceived)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var i;(i=this.onFirstAudioDecoded)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,i,n)=>{var r;(r=this.onFirstVideoDecoded)===null||r===void 0||r.call(this,e,i,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,i)=>{var n;(n=this.onSelectedLocalCandidateChanged)===null||n===void 0||n.call(this,e,i)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,i)=>{var n;(n=this.onSelectedRemoteCandidateChanged)===null||n===void 0||n.call(this,e,i)},this.statsFilter.onFirstVideoDecodedTimeout=e=>{var i;(i=this.onFirstVideoDecodedTimeout)===null||i===void 0||i.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}applySimulcastForFirefox(e,i){return C(this,null,function*(){if(e.length===i.length)for(let c=0;c<e.length;c++){var n,r,o,s,a;const d=e[c],l=i[c];if(l instanceof Yt&&!G(n=l._hints).call(n,Vt.LOW_STREAM)&&(r=l._encoderConfig)!==null&&r!==void 0&&r.bitrateMax&&((o=l._encoderConfig)===null||o===void 0?void 0:o.bitrateMax)>200&&(s=l._scalabilityMode)!==null&&s!==void 0&&s.numSpatialLayers&&((a=l._scalabilityMode)===null||a===void 0?void 0:a.numSpatialLayers)>1&&this.store.codec==="vp8"){const u={},h={high:1e3*(l._encoderConfig.bitrateMax-50),medium:5e4};u.encodings=[{rid:"m",active:!0,maxBitrate:h.medium,scaleResolutionDownBy:4},{rid:"h",active:!0,maxBitrate:h.high}];const p=d.sender.getParameters();yield d.sender.setParameters(Object.assign(p,u))}}})}applySimulcastEncodings(e,i){return C(this,null,function*(){if(!ne()&&e.length===i.length)for(let n=0;n<e.length;n++){const r=i[n];if(r instanceof Yt&&this.isVP8Simulcast(r)){const o=e[n],s={},a={high:1e3*(r._encoderConfig.bitrateMax-50),medium:5e4};s.encodings=[{active:!0,adaptivePtime:!1,networkPriority:"high",priority:"high",maxBitrate:a.high},{active:!0,adaptivePtime:!1,networkPriority:"low",priority:"low",maxBitrate:a.medium,scaleResolutionDownBy:4}];const c=o.sender.getParameters();yield o.sender.setParameters(Object.assign(c,s))}}})}isVP8Simulcast(e){var i,n,r,o,s;return!!(e instanceof Yt&&y("SIMULCAST")&&this.store.codec==="vp8"&&!G(i=e._hints).call(i,Vt.LOW_STREAM)&&(n=e._encoderConfig)!==null&&n!==void 0&&n.bitrateMax&&((r=e._encoderConfig)===null||r===void 0?void 0:r.bitrateMax)>200&&(o=e._scalabilityMode)!==null&&o!==void 0&&o.numSpatialLayers&&((s=e._scalabilityMode)===null||s===void 0?void 0:s.numSpatialLayers)>1)}logSDPExchange(e,i,n,r){if(y("SDP_LOGGING"))return _.upload("[".concat(this.store.clientId,"] exchanging ").concat(n," ").concat(i," SDP during P2PConnection.").concat(r,`
`),e),i==="offer"?o=>{this.logSDPExchange(o,"answer",n==="local"?"remote":"local",r)}:void 0}muteLocal(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const i=this.peerConnection.getTransceivers().filter(s=>s.mid&&e.indexOf(s.mid)!==-1);if(i.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");i.map(s=>{s.direction="inactive"});const n=yield this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","muteLocal");yield this.peerConnection.setLocalDescription(n),this.remoteSDP.muteRemote(e);const o=this.remoteSDP.toString();r==null||r(o),yield this.setRemoteDescription({type:"answer",sdp:o})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(i.toString()))}})}unmuteLocal(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const i=this.peerConnection.getTransceivers().filter(s=>s.mid&&e.indexOf(s.mid)!==-1);if(i.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length.");i.map(s=>C(this,null,function*(){s.direction="sendonly"}));const n=yield this.peerConnection.createOffer(),r=this.logSDPExchange(n.sdp||"","offer","local","unmuteLocal");yield this.peerConnection.setLocalDescription(n),this.remoteSDP.unmuteRemote(e);const o=this.remoteSDP.toString();r==null||r(o),yield this.setRemoteDescription({type:"answer",sdp:o})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(i.toString()))}})}getRemoteSSRC(e,i){return C(this,null,function*(){var n;if(i=i!=null?i:(n=this.currentRemoteDescription)===null||n===void 0?void 0:n.sdp){var r;const o=(r=Ni(i).mediaDescriptions.find(s=>s.attributes.mid===e))===null||r===void 0?void 0:r.attributes.ssrcs;return o==null?void 0:o[0].ssrcId}})}setRemoteDescription(e){return C(this,null,function*(){var i;yield this.peerConnection.setRemoteDescription(e),G(i=["connected","completed"]).call(i,this.peerConnection.iceConnectionState)||(this.isReady=!0,this.addRemoteCandidate())})}mungReceiveAnswerSDP(e,i,n){const r=Ni(e),o=r.mediaDescriptions.find(s=>s.attributes.mid===i);return o&&n===q.AUDIO&&o.media.mediaType==="audio"&&wa(o),mo(r)}},Q(qt.prototype,"establish",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"establish"),qt.prototype),Q(qt.prototype,"connect",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"connect"),qt.prototype),Q(qt.prototype,"receive",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"receive"),qt.prototype),Q(qt.prototype,"mockReceive",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"mockReceive"),qt.prototype),Q(qt.prototype,"stopReceiving",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"stopReceiving"),qt.prototype),Q(qt.prototype,"restartICE",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"restartICE"),qt.prototype),Q(qt.prototype,"close",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"close"),qt.prototype),Q(qt.prototype,"updateEncoderConfig",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"updateEncoderConfig"),qt.prototype),Q(qt.prototype,"updateSendParameters",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"updateSendParameters"),qt.prototype),Q(qt.prototype,"replaceTrack",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"replaceTrack"),qt.prototype),Q(qt.prototype,"muteLocal",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"muteLocal"),qt.prototype),Q(qt.prototype,"unmuteLocal",[Bn],Object.getOwnPropertyDescriptor(qt.prototype,"unmuteLocal"),qt.prototype),qt);function Bn(t,e,i){const n=t[e];if(typeof n!="function")throw new Error("Cannot use mutex on object property.");return i.value=function(){return C(this,arguments,function*(){const r=this.mutex,o=yield r.lock("From P2PConnection.".concat(e));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return yield n.apply(this,a)}finally{o()}})},i}let nr=function(t){return t.SEND_ONLY="SEND_ONLY",t.RECEIVE_ONLY="RECEIVE_ONLY",t}({});var LN,kN,MN,UN,xN,VN,FN,BN,jN,GN,WN,Zt;function HN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Th(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?HN(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):HN(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}let U4=(LN=rr(nr.SEND_ONLY),kN=rr(nr.SEND_ONLY),MN=rr(),UN=rr(nr.RECEIVE_ONLY),xN=rr(nr.RECEIVE_ONLY),VN=rr(nr.RECEIVE_ONLY),FN=rr(nr.RECEIVE_ONLY),BN=rr(nr.RECEIVE_ONLY),jN=rr(nr.RECEIVE_ONLY),GN=rr(),WN=rr(nr.RECEIVE_ONLY),Zt=class extends $t{get state(){return this._state}set state(t){const e=this._state;this._state=t,this.emit($.StateChange,e,this._state)}constructor(t,e){super(),S(this,"isPlanB",!1),S(this,"store",void 0),S(this,"statsUploader",void 0),S(this,"sendConnection",void 0),S(this,"recvConnection",void 0),S(this,"localTrackMap",new Map),S(this,"remoteUserMap",new Map),S(this,"localDataChannels",[]),S(this,"pendingLocalTracks",[]),S(this,"pendingRemoteTracks",[]),S(this,"statsCollector",void 0),S(this,"dtlsFailedCount",0),S(this,"sendMutex",void 0),S(this,"recvMutex",void 0),S(this,"_state",wt.Disconnected),S(this,"_restartStates",["disconnected","failed"]),S(this,"reconnectInterval",void 0),S(this,"uploadUnplinkStarted",!1),S(this,"uploadDownlinkStarted",!1),S(this,"uplinkStateUploadInterval",void 0),S(this,"downlinkStatsUploadInterval",void 0),S(this,"handleMuteLocalTrack",(i,n,r)=>C(this,null,function*(){const o=yield this.sendMutex.lock("Locking from P2PChannel2.handleMuteLocalTrack");try{if(!this.sendConnection||this.state!==wt.Connected)return void r(new k(v.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established."));const c=this.filterTobeMutedTracks(i);if(c.length===0)return void n();const d=c.find(p=>p[0]==="videoLowTrack");d&&d[1].track._originMediaStreamTrack.stop(),yield this.sendConnection.muteLocal(c.map(p=>{let[,{id:g}]=p;return g}));let l=!1;var s,a;i.trackMediaType==="video"?l=!((s=this.localTrackMap.get(V.LocalAudioTrack))===null||s===void 0||!s.track._muted):l=((a=this.localTrackMap.get(V.LocalVideoTrack))===null||a===void 0?void 0:a.id)===void 0;const u=this.createMuteMessage(c);yield Bt(this,$.RequestMuteLocal,u);const h=i.trackMediaType==="video"?go.MUTE_LOCAL_VIDEO:go.MUTE_LOCAL_AUDIO;yield Bt(this,$.RequestP2PMuteLocal,{action:h,message:u,isMuteAll:l}),n()}catch(c){r(c)}finally{o()}})),S(this,"handleUnmuteLocalTrack",(i,n,r)=>C(this,null,function*(){const o=yield this.sendMutex.lock("Locking from P2PChannel2.handleUnmuteLocalTrack");try{if(!this.sendConnection||this.state!==wt.Connected)return void r(new k(v.INVALID_OPERATION,"Cannot call P2PChannel2.handleUnmuteLocalTrack before sendConnection established."));const s=this.filterTobeUnmutedTracks(i);if(s.length===0)return void n();yield this.sendConnection.unmuteLocal(s.map(d=>{let[,{id:l}]=d;return l}));const a=this.createUnmuteMessage(s),c=i.trackMediaType==="video"?go.UNMUTE_LOCAL_VIDEO:go.UNMUTE_LOCAL_AUDIO;yield Bt(this,$.RequestP2PMuteLocal,{action:c,message:a}),n()}catch(s){r(s)}finally{o()}})),S(this,"handleUpdateVideoEncoder",(i,n,r,o)=>C(this,null,function*(){let s;typeof o=="boolean"&&o||(s=yield this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoEncoder"));try{const c=this.localTrackMap.get(V.LocalVideoTrack);if(!this.sendConnection||!c||c.track!==i||this.state!==wt.Connected)return void n();const{id:d,track:l}=c;d&&(yield this.sendConnection.updateSendParameters(d,l),yield this.sendConnection.updateEncoderConfig(d,l),this.emit($.UpdateVideoEncoder,l)),n()}catch(c){r(c)}finally{var a;(a=s)===null||a===void 0||a()}})),S(this,"handleUpdateVideoSendParameters",(i,n,r)=>C(this,null,function*(){const o=yield this.sendMutex.lock("Locking from P2PChannel2.handleUpdateVideoSendParameters");try{const s=this.localTrackMap.get(V.LocalVideoTrack);if(!this.sendConnection||!s||s.track!==i||this.state!==wt.Connected)return void n();const{id:a,track:c}=s;a&&(yield this.sendConnection.updateSendParameters(a,c)),n()}catch(s){r(s)}finally{o()}})),S(this,"handleReplaceTrack",(i,n,r,o)=>C(this,null,function*(){let s;_.debug("[".concat(this.store.clientId,"] P2PChannel2 handleReplaceTrack for [track-id-").concat(i.getTrackId(),"]")),typeof o=="boolean"&&o||(s=yield this.sendMutex.lock("From P2PChannel2.handleReplaceTrack"));try{var a;const d=Array.from(this.localTrackMap.entries()).find(l=>{let[,{track:u}]=l;return i===u});if(!this.sendConnection||!d||d[1].id===void 0||this.state!==wt.Connected)return void n();if(yield(a=this.sendConnection)===null||a===void 0?void 0:a.replaceTrack(i,d[1].id),d[0]===V.LocalVideoTrack&&Ct().supportDualStreamEncoding){const l=this.localTrackMap.get(V.LocalVideoLowTrack);if(l){const u=i._mediaStreamTrack.clone();l.track._originMediaStreamTrack.stop(),l.track._mediaStreamTrack=u,l.track._originMediaStreamTrack=u,yield new K((h,p)=>{this.handleReplaceTrack(l.track,h,p,!0)})}}n()}catch(d){r(d)}finally{var c;(c=s)===null||c===void 0||c()}})),S(this,"handleGetLocalVideoStats",i=>{i(this.statsCollector.getLocalVideoTrackStats())}),S(this,"handleGetLocalAudioStats",i=>{i(this.statsCollector.getLocalAudioTrackStats())}),S(this,"handleGetRemoteVideoStats",i=>this.statsCollector.getRemoteVideoTrackStats(i.uid)[i.uid]),S(this,"handleGetRemoteAudioStats",i=>this.statsCollector.getRemoteAudioTrackStats(i.uid)[i.uid]),this.store=t,this.statsCollector=e,this.statsCollector.addP2PChannel(this),this.statsUploader=new a0(t),this.bindStatsUploaderEvents(),this.sendMutex=new qe("P2PChannel2-send-mutex",t.clientId),this.recvMutex=new qe("P2PChannel2-recv-mutex",t.clientId),this.reconnectInterval=window.setInterval(()=>{[this.sendConnection,this.recvConnection].forEach(i=>{i&&(i.iceConnectionState!=="disconnected"&&i.iceConnectionState!=="failed"||this.handleDisconnect(i.direction))})},y("ICE_RESTART_INTERVAL"))}startP2PConnection(t,e){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED,"p2p mode does not support startP2PConnection.")})}connect(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED,"p2p mode does not support connect.")})}startP2P(t,e){return C(this,null,function*(){let i;try{if(e){this.recvConnection&&(_.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset recvConnection.")),this.recvConnection.close(),this.unbindConnectionEvents(this.recvConnection)),i=yield this.recvMutex.lock("From P2PChannel.startP2P"),this.recvConnection=new PN(t,this.store,pi.RECEIVE_ONLY),this.bindConnectionEvents(this.recvConnection);const n=yield this.recvConnection.establish(e);return{iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp}}{this.state=wt.New,this.sendConnection&&(_.warning("[".concat(this.store.clientId,"] P2PChannel.startP2P reset sendConnection.")),this.sendConnection.close(),this.unbindConnectionEvents(this.sendConnection)),i=yield this.sendMutex.lock("From P2PChannel.startP2P"),this.sendConnection=new PN(t,this.store),this.store.peerConnectionStart(),this.bindConnectionEvents(this.sendConnection);const n=yield this.sendConnection.establish();return{iceParameters:n.iceParameters,dtlsParameters:n.dtlsParameters,sdp:n.sdp}}}finally{i&&i()}})}p2pConnect(t){return C(this,null,function*(){if(!this.sendConnection)throw new k(v.UNEXPECTED_ERROR,"Cannot P2PChannel2.p2pConnect before P2PChannel2.startP2PConnection .");this.store.peerConnectionStart(),yield this.sendConnection.connect(t),this.statsUploader.startUploadTransportStats(),this.statsUploader.startUploadExtensionUsageStats(),this.state=wt.Connected})}addRemoteCandidate(t,e){return C(this,null,function*(){if(e===pi.RECEIVE_ONLY){if(!this.sendConnection)throw new k(v.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");yield this.sendConnection.addRemoteCandidate(t)}else{if(!this.recvConnection)throw new k(v.UNEXPECTED_ERROR,"Cannot P2PChannel2.connect before P2PChannel2.addRemoteCandidate .");yield this.recvConnection.addRemoteCandidate(t)}})}publish(t,e,i){var n=this;return cn(function*(){const r=yield Rt(n.sendMutex.lock("From P2PChannel.publish"));try{if(!n.sendConnection||n.state!==wt.Connected){n.throwIfTrackTypeNotMatch(t);const d=t.filter(l=>n.pendingLocalTracks.indexOf(l)===-1);return void(n.pendingLocalTracks=n.pendingLocalTracks.concat(d))}n.store.pubId=n.store.pubId+1,Je.markPublishStart(n.store.clientId,n.store.pubId);const o=n.filterTobePublishedTracks(t,e,i);if(o.length===0)return void(yield Rt(n.tryToUnmuteAudio(t)));o.forEach(d=>{let{track:l,type:u}=d;const h=Date.now();n.store.publish(l.getTrackId(),u===V.LocalAudioTrack?"audio":"video",h)}),n.bindLocalTrackEvents(o);const s=yield Rt(n.sendConnection.send(o.map(d=>{let{track:l}=d;return l}),n.store.codec,n.store.audioCodec)),a=(yield Rt(s.next())).value,c=n.createGatewayPublishMessage(o,a);try{yield c}catch(d){throw s.throw(d),(d==null?void 0:d.code)===v.WS_ABORT&&o.forEach(l=>{let{track:u}=l;n.pendingLocalTracks.indexOf(u)===-1&&n.pendingLocalTracks.push(u)}),n.unbindLocalTrackEvents(o),d}yield Rt(s.next()),o.forEach(d=>{let{type:l}=d;n.statsCollector.addLocalStats(l)}),n.statsUploader.startUploadOutboundStats(),n.assignLocalTracks(o,a),o.forEach(d=>{let{track:l,type:u}=d;const h=Date.now();n.store.publish(l.getTrackId(),u===V.LocalAudioTrack?"audio":"video",void 0,h)}),n.startUploadUplinkState()}finally{r()}})()}unpublish(t){return C(this,null,function*(){if(!this.sendConnection||this.state!==wt.Connected)return void(t.length===0?this.pendingLocalTracks.length=0:this.pendingLocalTracks=this.pendingLocalTracks.filter(r=>!G(t).call(t,r)));const e=this.filterTobeUnpublishedTracks(t);if(e.length===0)return;const i=e.find(r=>r[0]==="videoLowTrack");i&&i[1].track.close();const n=this.createGatewayUnpublishMessage(e);if(yield this.sendConnection.stopSending(e.map(r=>{let[,{id:o}]=r;return o})),this.withdrawLocalTracks(e),this.unbindLocalTrackEvents(e.map(r=>{let[o,{track:s}]=r;return{type:o,track:s}})),e.forEach(r=>{let[o]=r;this.statsCollector.removeLocalStats(o)}),this.localTrackMap.size===0&&(this.statsUploader.stopUploadOutboundStats(),this.stopUploadUplinkState()),this.sendConnection&&this.state===wt.Connected)return i&&i[1].track.close(),n;t.forEach(r=>{const o=this.pendingLocalTracks.indexOf(r);o!==-1&&this.pendingLocalTracks.splice(o,1)})})}startUploadUplinkState(){if(this.uploadUnplinkStarted)return;this.uploadUnplinkStarted=!0,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval);const t=()=>{const e=[],i=[];Array.from(this.localTrackMap.entries()).forEach(n=>{let[r,{track:o,ssrcs:s}]=n;const a={stream_type:NW(o,r),ssrcs:s};o._muted||!o._enabled?e.push(a):i.push(a)}),e.length>0&&e.forEach(n=>{Bt(this,$.RequestMuteLocal,[n])}),i.length>0&&i.forEach(n=>{Bt(this,$.RequestUnmuteLocal,[n])})};t(),this.uplinkStateUploadInterval=window.setInterval(()=>{t()},3e3)}stopUploadUplinkState(){this.uploadUnplinkStarted&&(this.uploadUnplinkStarted=!1,this.uplinkStateUploadInterval&&window.clearInterval(this.uplinkStateUploadInterval))}publishLowStream(t){return cn(function*(){throw new k(v.NOT_SUPPORTED,"p2p mode does not support publishLowStream.")})()}republish(){return C(this,null,function*(){this.pendingLocalTracks.length>0&&(_.debug("[".concat(this.store.clientId,"] Emit P2PChannelEvents.RequestRePublish to republish tracks.")),yield We(this,$.RequestRePublish,this.pendingLocalTracks),this.emit($.MediaReconnectEnd,this.store.uid),this.pendingLocalTracks=[])})}unpublishLowStream(){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED,"p2p mode does not support unpublishLowStream.")})}subscribe(t,e,i,n){return C(this,null,function*(){var r;if(!this.recvConnection)throw new k(v.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");if((r=this.remoteUserMap.get(t))!==null&&r!==void 0&&r.has(e))return;const{track:o,mid:s,transceiver:a}=yield this.recvConnection.receive(e,[{ssrcId:i}],String(t.uid),n);e===q.AUDIO?(t._audioTrack?t._audioTrack._updateOriginMediaStreamTrack(o):(t._audioTrack=new Sa(o,t.uid,t._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote audio track: ").concat(t._audioTrack.getTrackId()))),a&&t._audioTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(t,t._audioTrack)):(t._videoSSRC=i,t._videoTrack?t._videoTrack._updateOriginMediaStreamTrack(o):(t._videoTrack=new ga(o,t.uid,t._uintid,this.store),_.info("[".concat(this.store.clientId,"] [").concat(this.store.p2pId,"] create remote video track: ").concat(t._videoTrack.getTrackId()))),a&&t._videoTrack._updateRtpTransceiver(a),this.bindRemoteTrackEvents(t,t._videoTrack));const c=this.remoteUserMap.get(t);c?c.set(e,s):this.remoteUserMap.set(t,new Map([[e,s]])),this.statsCollector.addRemoteStats(t.uid),this.statsUploader.startUploadInboundStats(),this.startUploadDownlinkState();const d=this.pendingRemoteTracks.findIndex(l=>{let{user:u,kind:h}=l;return u.uid===t.uid&&e===h});d!==-1&&(this.pendingRemoteTracks.splice(d,1),this.emit($.MediaReconnectEnd,t.uid))})}mockSubscribe(t,e,i,n){return C(this,null,function*(){if(!this.recvConnection)throw new k(v.INVALID_OPERATION,"Cannot subscribe remote user when recvConnection disconnected.");yield this.recvConnection.mockReceive(e,[{ssrcId:i}],String(t.uid),n)})}unsubscribe(t,e,i){return C(this,null,function*(){const n=this.pendingRemoteTracks.filter(o=>{let{user:s,kind:a}=o;return e!==void 0?s.uid===t.uid&&e===a:s.uid===t.uid});if(n.forEach(o=>{const s=this.pendingRemoteTracks.indexOf(o);this.pendingRemoteTracks.splice(s,1)}),this.recvConnection||i||n.forEach(o=>{let{kind:s}=o;var a;if(s===q.AUDIO)(a=t._audioTrack)===null||a===void 0||a._destroy(),t._audioTrack=void 0;else if(s===q.VIDEO){var c;(c=t._videoTrack)===null||c===void 0||c._destroy(),t._videoTrack=void 0}}),!this.recvConnection)return;const r=this.filterTobeUnSubscribedTracks(t,e);r.length!==0&&(yield this.recvConnection.stopReceiving(r.map(o=>{let[,{id:s}]=o;return s})),this.withdrawRemoteTracks(r),this.remoteUserMap.size===0&&(this.statsUploader.stopUploadInboundStats(),this.stopUploadDownlinkState()),r.forEach(o=>{let[s,{kind:a}]=o;var c,d;if(a===q.VIDEO&&s._videoSSRC&&((c=this.recvConnection)===null||c===void 0||c.setStatsRemoteVideoIsReady(s._videoSSRC,!1)),a===q.VIDEO)this.unbindRemoteTrackEvents(s._videoTrack),i||((d=s._videoTrack)===null||d===void 0||d._destroy(),s._videoTrack=void 0);else if(a===q.AUDIO){var l;this.unbindRemoteTrackEvents(s._audioTrack),!i&&((l=s._audioTrack)===null||l===void 0||l._destroy(),s._audioTrack=void 0)}}),r.forEach(o=>{let[,{kind:s}]=o;Bt(this,$.RequestP2PMuteRemote,s)}))})}startUploadDownlinkState(){if(this.uploadDownlinkStarted)return;this.uploadDownlinkStarted=!0,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval);const t=()=>Array.from(this.remoteUserMap.entries()).forEach(e=>{let[,i]=e;[q.VIDEO,q.AUDIO].forEach(n=>{i.has(n)?Bt(this,$.RequestP2PUnmuteRemote,n):Bt(this,$.RequestP2PMuteRemote,n)})});t(),this.downlinkStatsUploadInterval=window.setInterval(()=>{t()},3e3)}stopUploadDownlinkState(){this.uploadDownlinkStarted&&(this.uploadDownlinkStarted=!1,this.downlinkStatsUploadInterval&&window.clearInterval(this.downlinkStatsUploadInterval))}getAllDataChannels(){return this.localDataChannels}massSubscribe(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED,"p2p mode does not support massSubscribe.")})}massSubscribeNoLock(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED,"p2p mode does not support massSubscribeNoLock.")})}massUnsubscribe(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED,"p2p mode does not support massUnsubscribe.")})}massUnsubscribeNoLock(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED,"p2p mode does not support massUnsubscribeNoLock.")})}muteRemote(t,e){return C(this,null,function*(){if(!this.recvConnection)return;const i=this.remoteUserMap.get(t);if(!i)return void _.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(t.uid,"."));if(!i.get(e))return void _.warning("[".concat(this.store.clientId,"] P2PChannel2.muteRemote has no remote user ").concat(t.uid," media type ").concat(e,"."));const n=e===q.VIDEO?t._videoSSRC:t._audioSSRC;n!==void 0&&this.recvConnection.setStatsRemoteVideoIsReady(n,!1)})}unmuteRemote(t,e){return C(this,null,function*(){return this.unmuteRemoteNoLock(t,e)})}unmuteRemoteNoLock(t,e){return C(this,null,function*(){if(!this.recvConnection)return;const i=this.remoteUserMap.get(t);if(!i)return void _.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(t.uid,"."));i.get(e)||_.warning("[".concat(this.store.clientId,"] P2PChannel2.unmuteRemote has no remote user ").concat(t.uid," media type ").concat(e,"."))})}getAllTracks(t){const e=this.localTrackMap.get(V.LocalAudioTrack);if((e==null?void 0:e.track)instanceof ve){const i=e.track;return Array.from(this.localTrackMap.entries()).filter(n=>{let[r]=n;return r!==V.LocalAudioTrack}).filter(n=>{let[r]=n;return!(t&&r===V.LocalVideoLowTrack)}).map(n=>{let[,{track:r}]=n;return r}).concat(i.trackList)}return Array.from(this.localTrackMap.entries()).filter(i=>{let[n]=i;return!(t&&n===V.LocalVideoLowTrack)}).map(i=>{let[,{track:n}]=i;return n})}reportPublishEvent(t,e,i,n,r){if(t){const s=this.localTrackMap.get(V.LocalAudioTrack),a=n?this.localTrackMap.get(V.LocalVideoLowTrack):this.localTrackMap.get(V.LocalVideoTrack);Z.publish(this.store.sessionId,{eventElapse:Je.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:t,ec:e,audioName:s==null?void 0:s.track.getTrackLabel(),videoName:a==null?void 0:a.track.getTrackLabel(),screenshare:(a==null?void 0:a.track._hints.indexOf(Vt.SCREEN_TRACK))!==-1,audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}else{var o;i||(i=[]);const s=i.find(c=>c instanceof ae),a=n?(o=this.localTrackMap.get(V.LocalVideoTrack))===null||o===void 0?void 0:o.track:i.find(c=>c instanceof Yt);Z.publish(this.store.sessionId,{eventElapse:Je.measureFromPublishStart(this.store.clientId,this.store.pubId),succ:t,ec:e,audioName:s==null?void 0:s.getTrackLabel(),videoName:a==null?void 0:a.getTrackLabel(),screenshare:(a==null?void 0:a._hints.indexOf(Vt.SCREEN_TRACK))!==-1,audio:!!s,video:!!a,p2pid:this.store.p2pId,publishRequestid:this.store.pubId,extend:r})}}reportSubscribeEvent(t,e,i,n){const r=n===q.VIDEO?i._videoSSRC:i._audioSSRC;r&&Z.subscribe(this.store.sessionId,{succ:t,ec:e,video:n===q.VIDEO,audio:n===q.AUDIO,peerid:i.uid,subscribeRequestid:n===q.VIDEO?i._videoSSRC:i._audioSSRC,p2pid:this.store.p2pId,eventElapse:Je.measureFromSubscribeStart(this.store.clientId,r)})}reset(){_.debug("[".concat(this.store.clientId,"] P2PChannel2.reset")),this.sendMutex=new qe("P2PChannel2-send-mutex",this.store.clientId),this.sendMutex=new qe("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 t=this.localTrackMap.get(V.LocalAudioTrack);if((t==null?void 0:t.track)instanceof ve){if(t.track.trackList.length>0){const e=t.track;t.track.trackList.forEach(i=>{e.removeAudioTrack(i)})}t.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=wt.Disconnected}getStats(t){var e,i;return t?(i=this.recvConnection)===null||i===void 0?void 0:i.getStats():(e=this.sendConnection)===null||e===void 0?void 0:e.getStats()}getRemoteVideoIsReady(t){var e;return((e=this.recvConnection)===null||e===void 0?void 0:e.getRemoteVideoIsReady(t))||!1}getLocalAudioVolume(){const t=this.localTrackMap.get(V.LocalAudioTrack);if(t)return t.track.getVolumeLevel()}getLocalVideoSize(){const t=this.localTrackMap.get(V.LocalVideoTrack);if(t)return{width:t.track.videoWidth||0,height:t.track.videoHeight||0}}getEncoderConfig(t){const e=this.localTrackMap.get(t);return e&&e.track instanceof Yt||e&&e.track instanceof ae?e.track._encoderConfig:void 0}getLocalMedia(t){return this.localTrackMap.get(t)}hasLocalMedia(){return this.localTrackMap.size>0}hasRemoteMedia(t,e){if(!t)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(t);return!!i&&(!e||i.has(e))}hasRemoteMediaWithLock(t,e){return C(this,null,function*(){if(!t)return this.remoteUserMap.size>0;const i=this.remoteUserMap.get(t);return!!i&&(!e||i.has(e))})}getRemoteMedia(t){var e;const i=Array.from(Ji(e=this.remoteUserMap).call(e)).find(n=>n.uid===t);return i?{audioTrack:i.audioTrack,audioSSRC:i._audioSSRC,videoTrack:i.videoTrack,videoSSRC:i._videoSSRC}:{}}getAudioLevels(){let t=Array.from(this.remoteUserMap.entries()).map(i=>{let[n]=i;return{uid:n.uid,level:n.audioTrack?100*n.audioTrack._source.getAccurateVolumeLevel():0}});const e=this.localTrackMap.get(V.LocalAudioTrack);return e&&t.push({level:100*e.track._source.getAccurateVolumeLevel(),uid:this.store.uid}),t=jo(t).call(t,(i,n)=>i.level-n.level),t}disconnectForReconnect(){return C(this,null,function*(){this.sendConnection&&this.recvConnection&&(_.debug("[".concat(this.store.clientId,"] P2PChannel2.disconnectForReconnect closing P2PConnection")),this.state=wt.Reconnecting,y("KEEP_LAST_FRAME")&&this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(t=>{let[e]=t;var i;e._videoTrack&&e._videoTrack._player&&((i=e._videoTrack._player.getVideoElement())===null||i===void 0||i.pause(),e._videoTrack._player.isKeepLastFrame=!0,e._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,this.localTrackMap.size!==0&&(Array.from(this.localTrackMap.entries()).forEach(t=>{var e;let[i,{track:n}]=t;switch(i){case V.LocalVideoTrack:G(e=n._hints).call(e,Vt.LOW_STREAM)?n.close():this.pendingLocalTracks.push(n);break;case V.LocalAudioTrack:n instanceof ve?this.pendingLocalTracks=this.pendingLocalTracks.concat(n.trackList):this.pendingLocalTracks.push(n);case V.LocalVideoLowTrack:}}),this.emit($.MediaReconnectStart,this.store.uid)),this.unbindLocalTrackEvents(),this.localTrackMap.clear(),this.remoteUserMap.size!==0&&Array.from(this.remoteUserMap.entries()).forEach(t=>{let[e,i]=t;Array.from(Ji(i).call(i)).forEach(n=>{this.setPendingRemoteMedia(e,n)}),this.emit($.MediaReconnectStart,e.uid)}),this.unbindAllRemoteTrackEvents(),this.remoteUserMap.clear(),this.stopUploadUplinkState(),this.stopUploadDownlinkState(),this.statsUploader.stopUploadOutboundStats(),this.statsUploader.stopUploadInboundStats(),this.statsUploader.stopUploadTransportStats(),_.debug("[".concat(this.store.clientId,"] P2PChannel2 disconnected, waiting to reconnect.")))})}hasPendingRemoteMedia(t,e){for(const i of this.pendingRemoteTracks){const{user:n,kind:r}=i;if((t instanceof Co?t.uid:t)===n.uid&&e===r)return!0}return!1}setPendingRemoteMedia(t,e){this.hasPendingRemoteMedia(t,e)||this.pendingRemoteTracks.push({user:t,kind:e})}restartICE(t,e){return C(this,null,function*(){let i,n;if(t===pi.SEND_ONLY){if(!this.sendConnection)throw new k(v.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before sendConnection established.");i=yield this.sendMutex.lock("From P2PChannel.restartICE"),n=this.sendConnection}else{if(!this.recvConnection)throw new k(v.INVALID_OPERATION,"Cannot call P2PChannel2.handleMuteLocalTrack before recvConnection established.");i=yield this.recvMutex.lock("From P2PChannel.restartICE"),n=this.recvConnection}try{if(e){const r=yield n.restartICE(e);return n.isInRestartIce=!1,r}{const r=yield n.restartICE();if(r){const o=yield We(this,$.RequestP2PRestartICE,{direction:pi.RECEIVE_ONLY,iceParameter:r});yield n.restartICE(o),n.isInRestartIce=!1}}}finally{i()}})}getUplinkNetworkQuality(){if(!this.sendConnection)return 0;const t=this.sendConnection.getStats(),e=this.localTrackMap.get(V.LocalVideoTrack),i=this.localTrackMap.get(V.LocalAudioTrack),n=t.videoSend.find(p=>{var g;return p.ssrc===(e==null||(g=e.ssrcs)===null||g===void 0?void 0:g[0].ssrcId)}),r=t.audioSend.find(p=>{var g;return p.ssrc===(i==null||(g=i.ssrcs)===null||g===void 0?void 0:g[0].ssrcId)});if(!n||!r)return 1;const o=zi(this,$.NeedSignalRTT),s=n?n.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*t.sendPacketLossRate*.7/50+.3*d/1500,u=l<.17?1:l<.36?2:l<.59?3:l<.1?4:5,h=e==null?void 0:e.track;if(h&&h._encoderConfig&&h._hints.indexOf(Vt.SCREEN_TRACK)===-1){const p=h._encoderConfig.bitrateMax,g=t.bitrate.actualEncoded;if(p&&g){const m=(1e3*p-g)/(1e3*p);return Xb[m<.15?0:m<.3?1:m<.45?2:m<.6?3:4][u]}}return u}getDownlinkNetworkQuality(){if(!this.recvConnection)return 0;const t=this.recvConnection.getStats();let e=0;return Array.from(this.remoteUserMap.entries()).forEach(i=>{let[n]=i;const r=n._audioSSRC,o=n._videoSSRC,s=t.audioRecv.find(g=>g.ssrc===r),a=t.videoRecv.find(g=>g.ssrc===o);if(!s&&!a)return void(e+=1);const c=zi(this,$.NeedSignalRTT),d=t.rtt,l=(d&&c?(d+c)/2:d||c)||0,u=s?s.jitterMs:void 0,h=t.recvPacketLossRate;let p=.7*h*100/50+.3*l/1500;u&&(p=.6*h*100/50+.2*l/1500+.2*u/400),e+=p<.1?1:p<.17?2:p<.36?3:p<.59?4:5}),this.remoteUserMap.size>0?Math.round(e/this.remoteUserMap.size):e}muteLocalTrack(t){return C(this,null,function*(){return new K((e,i)=>{this.handleMuteLocalTrack(t,e,i)})})}filterTobePublishedTracks(t,e,i){const n=[],r=Ct(),o=this.getAllTracks();t=oa(t=t.filter(c=>o.indexOf(c)===-1));let s=!1,a=!1;for(const c of t){if(c instanceof Yt&&(this.localTrackMap.has(V.LocalVideoTrack)||s?new k(v.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS).throw():(n.push({track:c,type:V.LocalVideoTrack}),s=!0),e)){const d=this.getLowVideoTrack(c,i);n.push({track:d,type:V.LocalVideoLowTrack})}if(c instanceof ae){const d=this.localTrackMap.get(V.LocalAudioTrack);if(d){if(!(d.track instanceof ve))throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(c._bypassWebAudio)throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");d.track.addAudioTrack(c),this.bindLocalAudioTrackEvents(c,!0)}else if(a){const l=n.find(u=>{let{type:h}=u;return h===V.LocalAudioTrack});if(!(l.track instanceof ve))throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser does not support audio mixing");if(c._bypassWebAudio)throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio");l.track.addAudioTrack(c)}else{if(!r.webAudioMediaStreamDest||c instanceof ve||c._bypassWebAudio)n.push({track:c,type:V.LocalAudioTrack});else{const l=new ve;l.addAudioTrack(c),n.push({track:l,type:V.LocalAudioTrack})}a=!0}}}return n}filterTobeUnpublishedTracks(t){const e=[],i=this.getAllTracks();t=oa(t=t.filter(n=>i.indexOf(n)!==-1));for(const n of t){if(n instanceof ae){const r=this.localTrackMap.get(V.LocalAudioTrack);if(!r)continue;r.track instanceof ve?(r.track.removeAudioTrack(n),this.unbindLocalAudioTrackEvents(n),r.track.trackList.length===0&&(e.push([V.LocalAudioTrack,r]),r.track.close())):e.push([V.LocalAudioTrack,r])}if(n instanceof Yt){const r=this.localTrackMap.get(V.LocalVideoTrack);if(!r)continue;e.push([V.LocalVideoTrack,r]);const o=this.localTrackMap.get(V.LocalVideoLowTrack);o&&e.push([V.LocalVideoLowTrack,o])}}return e}bindLocalTrackEvents(t){t.forEach(e=>{let{track:i,type:n}=e;switch(n){case V.LocalVideoTrack:i.addListener(J.GET_STATS,this.handleGetLocalVideoStats),i.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.addListener(J.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),i.addListener(J.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),i.addListener(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),i.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case V.LocalAudioTrack:this.bindLocalAudioTrackEvents(i);case V.LocalVideoLowTrack:}})}bindLocalAudioTrackEvents(t,e){t instanceof ve?t.trackList.forEach(i=>{i.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.addListener(J.GET_STATS,this.handleGetLocalAudioStats),i.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(t.addListener(J.GET_STATS,this.handleGetLocalAudioStats),t.addListener(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.addListener(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.addListener(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.addListener(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack),e||t.addListener(J.NEED_REPLACE_TRACK,this.handleReplaceTrack))}unbindLocalTrackEvents(t){t||(t=Array.from(this.localTrackMap.entries()).map(e=>{let[i,{track:n}]=e;return{track:n,type:i}})),t.forEach(e=>{let{track:i,type:n}=e;switch(n){case V.LocalVideoTrack:i.off(J.GET_STATS,this.handleGetLocalVideoStats),i.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),i.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),i.off(J.NEED_UPDATE_VIDEO_ENCODER,this.handleUpdateVideoEncoder),i.off(J.NEED_UPDATE_VIDEO_SEND_PARAMETERS,this.handleUpdateVideoSendParameters),i.off(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),i.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),i.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack);break;case V.LocalAudioTrack:this.unbindLocalAudioTrackEvents(i);case V.LocalVideoLowTrack:}})}unbindLocalAudioTrackEvents(t){t instanceof ve?t.trackList.forEach(e=>{e.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),e.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),e.off(J.GET_STATS,this.handleGetLocalAudioStats),e.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),e.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack)}):(t.off(J.GET_STATS,this.handleGetLocalAudioStats),t.off(J.NEED_DISABLE_TRACK,this.handleMuteLocalTrack),t.off(J.NEED_ENABLE_TRACK,this.handleUnmuteLocalTrack),t.off(J.NEED_REPLACE_TRACK,this.handleReplaceTrack),t.off(J.NEED_MUTE_TRACK,this.handleMuteLocalTrack),t.off(J.NEED_UNMUTE_TRACK,this.handleUnmuteLocalTrack))}bindRemoteTrackEvents(t,e){e instanceof ga&&e.addListener(J.GET_STATS,i=>{i(this.handleGetRemoteVideoStats(t))}),e instanceof Sa&&e.addListener(J.GET_STATS,i=>{i(this.handleGetRemoteAudioStats(t))})}unbindRemoteTrackEvents(t){t&&t.removeAllListeners(J.GET_STATS)}unbindAllRemoteTrackEvents(){Array.from(this.remoteUserMap.entries()).forEach(t=>{let[e,i]=t;i.has(q.AUDIO)&&this.unbindRemoteTrackEvents(e._audioTrack),i.has(q.VIDEO)&&this.unbindRemoteTrackEvents(e._videoTrack)})}createGatewayPublishMessage(t,e){return t.map((i,n)=>{var r;let o,{track:s,type:a}=i;switch(a){case V.LocalAudioTrack:o=Ot.Audio;break;case V.LocalVideoTrack:o=G(r=s._hints).call(r,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High;break;case V.LocalVideoLowTrack:o=Ot.Low}return{kind:a===V.LocalAudioTrack?q.AUDIO:q.VIDEO,stream_type:o,mid:e[n].id,ssrcs:e[n].localSSRC,isMuted:s.muted||!s.enabled}})}createGatewayUnpublishMessage(t){return t.map(e=>{var i;let n,[r,{track:o,ssrcs:s,id:a}]=e;switch(r){case V.LocalVideoTrack:n=G(i=o._hints).call(i,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High;break;case V.LocalAudioTrack:n=Ot.Audio;break;case V.LocalVideoLowTrack:n=Ot.Low}return{stream_type:n,ssrcs:s,mid:a}})}assignLocalTracks(t,e){t.forEach((i,n)=>{let{track:r,type:o}=i;this.localTrackMap.set(o,{track:r,id:e[n].id,ssrcs:e[n].localSSRC})})}withdrawLocalTracks(t){t.forEach(e=>{let[i]=e;this.localTrackMap.delete(i)})}bindConnectionEvents(t){t.onConnectionStateChange=e=>C(this,null,function*(){var i;_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: ").concat(t.name,".onConnectionStateChange(").concat(e,")")),this.emit($.PeerConnectionStateChange,e),e!=="connected"||this.store.keyMetrics.peerConnectionEnd||this.store.peerConnectionEnd(),e==="connected"&&(t.isInRestartIce=!1),G(i=this._restartStates).call(i,e)&&!t.isInRestartIce&&(e==="disconnected"&&(yield Ue(800)),t.iceConnectionState!=="disconnected"&&t.iceConnectionState!=="failed"||this.handleDisconnect(t.direction))}),t.onICEConnectionStateChange=e=>{e!=="connected"||this.store.keyMetrics.iceConnectionEnd||this.store.iceConnectionEnd(),_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICEConnectionStateChange(").concat(e,")")),Z.reportApiInvoke(this.store.sessionId,{name:"ICEConnectionStateChange",options:e,tag:oe.TRACER}).onSuccess(),this.emit($.IceConnectionStateChange,e)},t.onICETransportStateChange=e=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onICETransportStateChange(").concat(e,")"))},t.onDTLSTransportStateChange=e=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportStateChange(").concat(e,")"))},t.onDTLSTransportError=e=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.onDTLSTransportError(").concat(e,")"))},t.onFirstAudioDecoded=e=>{var i;const n=Array.from(Ji(i=this.remoteUserMap).call(i)).find(o=>o._audioSSRC===e);var r;n&&(this.store.subscribe(n.uid,"audio",void 0,void 0,void 0,Date.now()),(r=n.audioTrack)===null||r===void 0||r.emit(pa.FIRST_FRAME_DECODED),Z.firstRemoteFrame(this.store.sessionId,Oe.FIRST_AUDIO_DECODE,Jt.FIRST_AUDIO_DECODE,{peer:n._uintid,subscribeElapse:Je.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId}))},t.onFirstAudioReceived=e=>{var i;const n=Array.from(Ji(i=this.remoteUserMap).call(i)).find(r=>r._audioSSRC===e);n&&Z.firstRemoteFrame(this.store.sessionId,Oe.FIRST_AUDIO_RECEIVED,Jt.FIRST_AUDIO_RECEIVED,{peer:n._uintid,subscribeElapse:Je.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},t.onFirstVideoDecoded=(e,i,n)=>{this.reportVideoFirstFrameDecoded(e,i,n)},t.onFirstVideoReceived=e=>{var i;const n=Array.from(Ji(i=this.remoteUserMap).call(i)).find(r=>r._videoSSRC===e);n&&Z.firstRemoteFrame(this.store.sessionId,Oe.FIRST_VIDEO_RECEIVED,Jt.FIRST_VIDEO_RECEIVED,{peer:n._uintid,subscribeElapse:Je.measureFromSubscribeStart(this.store.clientId,e),subscribeRequestid:e,p2pid:this.store.p2pId})},t.onSelectedLocalCandidateChanged=(e,i)=>{const n=e.candidateType==="relay",r=i.candidateType==="relay";i.candidateType!=="unknown"&&n===r||this.emit($.ConnectionTypeChange,n),_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedLocalCandidateChanged(").concat(JSON.stringify(To(i))," -> ").concat(JSON.stringify(To(e)),")"))},t.onSelectedRemoteCandidateChanged=(e,i)=>{_.info("[".concat(this.store.clientId,"] [p2pId: ").concat(this.store.p2pId,"]: P2PConnection.SelectedRemoteCandidateChanged(").concat(JSON.stringify(To(i))," -> ").concat(JSON.stringify(To(e)),")"))},t.onFirstVideoDecodedTimeout=e=>{this.reportVideoFirstFrameDecoded(e,void 0,void 0,!0)},t.onLocalCandidate=e=>{this.emit($.LocalCandidate,{candidate:e,direction:t.direction})}}unbindConnectionEvents(t){t.onConnectionStateChange=void 0,t.onICEConnectionStateChange=void 0,t.onICETransportStateChange=void 0,t.onDTLSTransportStateChange=void 0,t.onDTLSTransportError=void 0,t.onFirstAudioDecoded=void 0,t.onFirstAudioReceived=void 0,t.onFirstVideoDecoded=void 0,t.onFirstVideoReceived=void 0,t.onSelectedLocalCandidateChanged=void 0,t.onSelectedRemoteCandidateChanged=void 0,t.onFirstVideoDecodedTimeout=void 0,t.onLocalCandidate=void 0}handleDisconnect(t){return C(this,null,function*(){const e=t===pi.SEND_ONLY?this.sendConnection:this.recvConnection;e&&!e.isInRestartIce&&(e.isInRestartIce=!0,_.debug("[".concat(this.store.clientId,"] [P2PChannel-").concat(e.name,"] start use restartICE")),t===pi.SEND_ONLY?this.restartICE(t):We(this,$.RequestP2PRestartICE,{direction:pi.SEND_ONLY}))})}filterTobeMutedTracks(t){const e=[];if(this.getAllTracks().indexOf(t)===-1)return e;const i=this.localTrackMap.get(V.LocalAudioTrack);if(t instanceof ae&&(i==null?void 0:i.track)instanceof ve)return i.track.isActive||e.push([V.LocalAudioTrack,i]),e;const n=Array.from(this.localTrackMap.entries()).find(r=>{let[,{track:o}]=r;return t===o});if(n&&(e.push(n),n[0]===V.LocalVideoTrack)){const r=this.localTrackMap.get(V.LocalVideoLowTrack);r&&e.push([V.LocalVideoLowTrack,r])}return e}filterTobeUnmutedTracks(t){const e=[],i=this.localTrackMap.get(V.LocalAudioTrack);if(t instanceof ae&&(i==null?void 0:i.track)instanceof ve)return i.track.isActive&&e.push([V.LocalAudioTrack,i]),e;const n=Array.from(this.localTrackMap.entries()).find(r=>{let[,{track:o}]=r;return t===o});if(n)if(n[0]===V.LocalVideoTrack){e.push(n);const r=this.localTrackMap.get(V.LocalVideoLowTrack);r&&e.push([V.LocalVideoLowTrack,r])}else e.push(n);return e}createMuteMessage(t){return t.map(e=>{var i;let n,[r,{track:o,ssrcs:s,id:a}]=e;switch(r){case V.LocalAudioTrack:n=Ot.Audio;break;case V.LocalVideoTrack:n=G(i=o._hints).call(i,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High;break;case V.LocalVideoLowTrack:n=Ot.Low}return{stream_type:n,ssrcs:s,mid:a}})}createUnmuteMessage(t){return t.map(e=>{var i;let n,[r,{track:o,ssrcs:s,id:a}]=e;switch(r){case V.LocalAudioTrack:n=Ot.Audio;break;case V.LocalVideoTrack:n=G(i=o._hints).call(i,Vt.SCREEN_TRACK)?Ot.Screen:Ot.High;break;case V.LocalVideoLowTrack:n=Ot.Low}return{stream_type:n,ssrcs:s,mid:a}})}filterTobeUnSubscribedTracks(t,e){const i=[],n=this.remoteUserMap.get(t);if(!n)return i;if(e){const r=n.get(e);if(!r)return i;i.push([t,{kind:e,id:r}])}else Array.from(n.entries()).forEach(r=>{let[o,s]=r;i.push([t,{kind:o,id:s}])});return i}createUnsubscribeMessage(t){const e=[];return t.forEach(i=>{let[n,{kind:r,id:o}]=i;switch(r){case q.VIDEO:return void(n._videoSSRC&&e.push({stream_type:q.VIDEO,ssrcId:n._videoSSRC}));case q.AUDIO:return void(n._audioSSRC&&e.push({stream_type:q.AUDIO,ssrcId:n._audioSSRC}))}}),e}withdrawRemoteTracks(t){t.forEach(e=>{let[i,{kind:n}]=e;const r=this.remoteUserMap.get(i);r&&(r.delete(n),Array.from(r.entries()).length===0&&this.remoteUserMap.delete(i))})}updateBitrateLimit(t){return C(this,null,function*(){const e=this.localTrackMap.get(V.LocalVideoTrack),i=this.localTrackMap.get(V.LocalVideoLowTrack);e&&(yield e.track.setBitrateLimit(t.uplink),yield new K((n,r)=>{this.handleUpdateVideoEncoder(e.track,n,r,!0)})),i&&t.low_stream_uplink&&(yield i.track.setBitrateLimit({max_bitrate:t.low_stream_uplink.bitrate,min_bitrate:t.low_stream_uplink.bitrate||0}),yield new K((n,r)=>{this.handleUpdateVideoEncoder(i.track,n,r,!0)}))})}isP2PDisconnected(){if(this.sendConnection&&this.recvConnection){const t=this.sendConnection.peerConnectionState,e=this.recvConnection.peerConnectionState;return t!=="connected"&&e!=="connected"}return!0}tryToUnmuteAudio(t){return C(this,null,function*(){for(let e=0;e<t.length;e++)if(t[e]instanceof ae){const i=this.filterTobeUnmutedTracks(t[e]);if(i.length===0)continue;const n=this.createUnmuteMessage(i);return void(yield Bt(this,$.RequestUnmuteLocal,n))}})}bindStatsUploaderEvents(){this.statsUploader.requestStats=t=>this.getStats(t),this.statsUploader.requestLocalMedia=()=>Array.from(this.localTrackMap.entries()).filter(t=>{let[,{ssrcs:e}]=t;return!!e}),this.statsUploader.requestRemoteMedia=()=>Array.from(this.remoteUserMap.entries()),this.statsUploader.requestVideoIsReady=t=>{var e;return!((e=this.recvConnection)===null||e===void 0||!e.getRemoteVideoIsReady(t))},this.statsUploader.requestUpload=(t,e)=>this.emit($.RequestUpload,t,e),this.statsUploader.requestUploadStats=t=>this.emit($.RequestUploadStats,t),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}requestReconnect(){return C(this,null,function*(){this.dtlsFailedCount+=1,yield Ue(FE(this.dtlsFailedCount,ge)),this.emit($.RequestReconnect)})}reconnectP2P(){return C(this,null,function*(){})}canPublishLowStream(){return this.localTrackMap.has(V.LocalVideoTrack)||this.pendingLocalTracks.some(t=>t instanceof Yt)}throwIfTrackTypeNotMatch(t){if(t.filter(e=>e instanceof Yt).length>1)throw new k(v.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(t.filter(e=>e instanceof ae).length>1&&(t.some(e=>e instanceof ae&&e._bypassWebAudio)||!Ct().webAudioMediaStreamDest))throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode");for(const e of t){if(e instanceof Yt&&this.pendingLocalTracks.some(i=>i instanceof Yt))throw new k(v.CAN_NOT_PUBLISH_MULTIPLE_VIDEO_TRACKS);if(e instanceof ae&&this.pendingLocalTracks.some(i=>i instanceof ae)&&(!Ct().webAudioMediaStreamDest||e._bypassWebAudio||this.pendingLocalTracks.some(i=>i instanceof ae&&i._bypassWebAudio)))throw new k(v.NOT_SUPPORTED,"cannot publish multiple tracks which one of them configured with bypassWebAudio or your browser doesn't support MediaStreamDestNode")}}getLowVideoTrack(t,e){const i=!y("DISABLE_DUAL_STREAM_USE_ENCODING")&&Ct().supportDualStreamEncoding,n=Th(Th({},{width:160,height:120,framerate:15,bitrate:50}),e);let r;r=i?t._mediaStreamTrack.clone():Xm(t,n);const o=Gt(8,"track-low-"),s=new Yt(r,Th(Th({},i&&{scaleResolutionDownBy:Dm(n,t)}),{},{frameRate:n.framerate,bitrateMax:n.bitrate,bitrateMin:n.bitrate}),void 0,void 0,o);return s.on(ts.TRANSCEIVER_UPDATED,a=>{t._updateRtpTransceiver(a,ua.LOW_STREAM)}),s._hints.push(Vt.LOW_STREAM),t.addListener(J.NEED_CLOSE,()=>{s.close()}),s}globalLock(){return C(this,null,function*(){return this.recvMutex.lock("From P2PChannel2.globalLock")})}reportVideoFirstFrameDecoded(t,e,i,n){var r;const o=Array.from(Ji(r=this.remoteUserMap).call(r)).find(s=>s._videoSSRC===t);if(o){n||this.store.subscribe(o.uid,"video",void 0,void 0,void 0,void 0,Date.now());const s=this.store.keyMetrics,a=s.subscribe.find(c=>c.userId===o.uid&&c.type==="video");Z.firstRemoteVideoDecode(this.store.sessionId,Oe.FIRST_VIDEO_DECODE,Jt.FIRST_VIDEO_DECODE,{peer:o._uintid,videowidth:e,videoheight:i,subscribeElapse:Je.measureFromSubscribeStart(this.store.clientId,t),subscribeRequestid:t,p2pid:this.store.p2pId,apEnd:s.requestAPEnd||0,apStart:s.requestAPStart||0,joinGwEnd:s.joinGatewayEnd||0,joinGwStart:s.joinGatewayStart||0,pcEnd:s.peerConnectionEnd||0,pcStart:s.peerConnectionStart||0,subscriberEnd:(a==null?void 0:a.subscribeEnd)||0,subscriberStart:(a==null?void 0:a.subscribeStart)||0,videoAddNotify:(a==null?void 0:a.streamAdded)||0,state:n?1:0})}}remoteMediaSsrcChanged(t,e,i){return C(this,null,function*(){if(!this.recvConnection)return!1;const n=this.remoteUserMap.get(t);if(!n)return!1;const r=n.get(e);if(!r)return!1;const o=yield this.recvConnection.getRemoteSSRC(r);return o!==void 0&&o!==i})}isPreSubScribe(t){return!1}publishDataChannel(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED)})}unpublishDataChannel(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED)})}subscribeDataChannel(t,e){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED)})}unsubscribeDataChannel(t,e){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED)})}hasPendingRemoteDataChannel(t,e){throw new k(v.NOT_SUPPORTED)}setPendingRemoteDataChannel(t,e){throw new k(v.NOT_SUPPORTED)}preConnect(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED)})}getEstablishParams(){throw new k(v.NOT_SUPPORTED)}reSubscribe(t){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED)})}updateVideoStreamParameter(t,e){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED)})}unbindRtpTransceiver(){this.localTrackMap.size!==0&&Array.from(this.localTrackMap.entries()).forEach(t=>{let[e,{track:i}]=t;e===V.LocalVideoLowTrack?i._updateRtpTransceiver(void 0,ua.LOW_STREAM):i._updateRtpTransceiver(void 0)})}},Q(Zt.prototype,"p2pConnect",[LN],Object.getOwnPropertyDescriptor(Zt.prototype,"p2pConnect"),Zt.prototype),Q(Zt.prototype,"unpublish",[kN],Object.getOwnPropertyDescriptor(Zt.prototype,"unpublish"),Zt.prototype),Q(Zt.prototype,"unpublishLowStream",[MN],Object.getOwnPropertyDescriptor(Zt.prototype,"unpublishLowStream"),Zt.prototype),Q(Zt.prototype,"subscribe",[UN],Object.getOwnPropertyDescriptor(Zt.prototype,"subscribe"),Zt.prototype),Q(Zt.prototype,"mockSubscribe",[xN],Object.getOwnPropertyDescriptor(Zt.prototype,"mockSubscribe"),Zt.prototype),Q(Zt.prototype,"unsubscribe",[VN],Object.getOwnPropertyDescriptor(Zt.prototype,"unsubscribe"),Zt.prototype),Q(Zt.prototype,"muteRemote",[FN],Object.getOwnPropertyDescriptor(Zt.prototype,"muteRemote"),Zt.prototype),Q(Zt.prototype,"unmuteRemote",[BN],Object.getOwnPropertyDescriptor(Zt.prototype,"unmuteRemote"),Zt.prototype),Q(Zt.prototype,"hasRemoteMediaWithLock",[jN],Object.getOwnPropertyDescriptor(Zt.prototype,"hasRemoteMediaWithLock"),Zt.prototype),Q(Zt.prototype,"disconnectForReconnect",[GN],Object.getOwnPropertyDescriptor(Zt.prototype,"disconnectForReconnect"),Zt.prototype),Q(Zt.prototype,"remoteMediaSsrcChanged",[WN],Object.getOwnPropertyDescriptor(Zt.prototype,"remoteMediaSsrcChanged"),Zt.prototype),Zt);function rr(t){return function(e,i,n){const r=e[i];if(typeof r!="function")throw new Error("Cannot use mutex on object property.");return n.value=function(){return C(this,arguments,function*(){for(var o=arguments.length,s=new Array(o),a=0;a<o;a++)s[a]=arguments[a];switch(t){case nr.SEND_ONLY:{const c=yield this.sendMutex.lock("From P2PChannel2.".concat(i));try{return yield r.apply(this,s)}finally{c()}}case nr.RECEIVE_ONLY:{const c=yield this.recvMutex.lock("From P2PChannel2.".concat(i));try{return yield r.apply(this,s)}finally{c()}}default:{const c=yield this.sendMutex.lock("From P2PChannel2.".concat(i)),d=yield this.recvMutex.lock("From P2PChannel2.".concat(i));try{return yield r.apply(this,s)}finally{c(),d()}}}})},n}}class gs extends $t{constructor(e,i){super(),S(this,"signal",void 0),S(this,"token",void 0),S(this,"tokenTimeout",void 0),S(this,"tokenInterval",void 0),S(this,"_sequence",0),S(this,"userMap",new Map),S(this,"encoder",new TextEncoder),this.signal=e,this.token=i;const n=()=>{this.signal.connectionState===Ht.CONNECTED&&this.check(),this.userMap.size===0?this.tokenInterval=window.setTimeout(n,1e3):this.tokenInterval=window.setTimeout(n,3*y("P2P_TOKEN_INTERVAL"))};n()}send(e,i,n,r,o){return C(this,null,function*(){var s;if(this.userMap.size===0)return;const a=Array.from(Ui(s=this.userMap).call(s))[0].token;typeof i!="string"&&(i=JSON.stringify(i)),r=r!=null?r:Gt(6,""),o=o!=null?o:this._sequence++;const c={_id:r,_type:e,_seq:o,_message:i,token:"".concat(this.token,"_").concat(a)};y("SHOW_P2P_LOG")&&_.debug("send message",c,"noNeedResponse : ".concat(n)),this.splitMessage(JSON.stringify(c)).forEach(l=>{this.signal.request(nt.DATA_STREAM,{payload:Eo(this.encoder.encode(l))})});const d=new K((l,u)=>{const h=window.setTimeout(()=>{this.off("res-@".concat(r,"_ack"),p),this.off("res-@".concat(r),m),this.off(ya.ABORT,g),_.debug("[external-signal] request timeout, type: ".concat(e,", requestId: ").concat(r)),this.userMap.size===0?u(new k(v.INVALID_REMOTE_USER)):u(new k(v.TIMEOUT))},y("EXTERNAL_SIGNAL_REQUEST_TIMEOUT")),p=()=>{h&&window.clearTimeout(h),this.off(ya.ABORT,g),n&&l()},g=()=>{h&&window.clearTimeout(h),this.off("res-@".concat(r,"_ack"),p),this.off("res-@".concat(r),m),u(new k(v.EXTERNAL_SIGNAL_ABORT,"type: ".concat(e,", requestId: ").concat(r)))};this.once(ya.ABORT,g),this.once("res-@".concat(r,"_ack"),p);const m=(T,R)=>{f=!0,h&&window.clearTimeout(h),this.off("res-@".concat(r,"_ack"),p),this.off(ya.ABORT,g),T==="success"?l(R):u(new k(v.P2P_MESSAGE_FAILED,"request ".concat(e," failed, requestId: ").concat(r)))};let f=!1;n||(this.once("res-@".concat(r),m),Ue(y("SIGNAL_REQUEST_TIMEOUT")).then(()=>{f||_.warning("external_signal request timeout, type: ".concat(e,", requestId: ").concat(r,", ").concat(c))}))});try{return yield d}catch(l){if(l.code===v.TIMEOUT)return yield this.send(e,i,n,r,o);throw l}})}onMessage(e){var i;const{_uid:n}=e;let r,o=this.userMap.get(n);if(o)r=o.splitMessageMap;else{if(this.userMap.size>0||!("_type"in e)||e._type!==he.CHECK)return;const{token:d}=e;r=new Map,o={uid:n,isStart:!0,token:d,splitMessageMap:r,nextExpectedSequenceNumber:0,receivedMessagesMap:new Map},this.userMap.set(n,o),this.signal.emit(mt.ON_USER_ONLINE,{uid:n}),this.handleUserOnline()}if("id"in e&&"total"in e){var s;const{id:d,total:l}=e,u=(s=r.get(d))!==null&&s!==void 0?s:[];if(u.push(e),r.has(d)||r.set(d,u),u.length!==l)return;{const h=jo(u).call(u,(p,g)=>p.index-g.index).map(p=>p.payload).join("");r.delete(d),(e=JSON.parse(h))._uid=n}}const{_type:a,token:c}=e;if(G(i=[he.ACK,he.CHECK]).call(i,a))return a===he.CHECK&&this.handleCheckToken(o,c),void this.receiveMessage(e);c==="".concat(o.token,"_").concat(this.token)?this.handleReceivedMessage(e):_.debug('Receive unexpected message", '.concat(c,", cur_token: ").concat(o.token,"_").concat(this.token),e)}check(){const e={_id:Gt(6,""),token:this.token,_type:he.CHECK};y("SHOW_P2P_LOG")&&_.debug("send message",e),this.signal.request(nt.DATA_STREAM,{payload:Eo(this.encoder.encode(JSON.stringify(e)))})}ack(e){const i={_id:e,_type:he.ACK,token:this.token};y("SHOW_P2P_LOG")&&_.debug("send message",i),this.signal.request(nt.DATA_STREAM,{payload:Eo(this.encoder.encode(JSON.stringify(i)))})}response(e,i,n){this.send(he.RESPONSE,JSON.stringify({success:!n,message:i}),!0,e)}handleReceivedMessage(e){const i=()=>{this.userMap.forEach(d=>{const{receivedMessagesMap:l,nextExpectedSequenceNumber:u}=d;for(;l.has(u);){const h=l.get(u);l.delete(u),this.receiveMessage(h),d.nextExpectedSequenceNumber++}})};if(!e)return void i();const{_uid:n,_seq:r}=e,o=this.userMap.get(n),{receivedMessagesMap:s,isStart:a,nextExpectedSequenceNumber:c}=o;if(r<c)return this.ack(e._id),void _.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++,i())}receiveMessage(e){const{_id:i,_type:n,_message:r,_uid:o}=e;if(y("SHOW_P2P_LOG")&&_.debug("receive message",e),i){let s;switch(e._type!==he.ACK&&(r&&(s=JSON.parse(r)),this.ack(e._id)),e._type){case he.CANDIDATE:case he.CONTROL:this.signal.emit(n,s,o);break;case he.PUBLISH:case he.UNPUBLISH:case he.RESTART_ICE:case he.CALL:s.uid=o,We(this.signal,n,s).then(a=>{this.response(e._id,a)}).catch(()=>{this.response(e._id,void 0,!0)});break;case he.ACK:this.getListeners("res-@".concat(i,"_ack")).length>0&&this.emit("res-@".concat(i,"_ack"));break;case he.RESPONSE:{const{success:a,message:c}=s;this.emit("res-@".concat(i),a?"success":"failed",c);break}}}}splitMessage(e){if(e.length<gs.MAX_MESSAGE_SIZE)return[e];const i=[],{remoteToken:n}=JSON.parse(e),r=Gt(6,"");let o=0,s=800;const a=Math.ceil(e.length/s);for(;e.length>0;){o++;const c={id:r,index:o,total:a,payload:e.slice(0,s),token:"".concat(this.token,"_").concat(n)};JSON.stringify(c).length>gs.MAX_MESSAGE_SIZE?s-=50:(i.push(c),e=e.slice(s))}return i.map(c=>JSON.stringify(c))}handleCheckToken(e,i){return e.token!==i?(_.debug("token changed, from ".concat(e.token," to ").concat(i)),this.reset(e.uid,i),!1):(this.tokenTimeout&&(window.clearTimeout(this.tokenTimeout),this.tokenTimeout=void 0),this.tokenTimeout=window.setTimeout(()=>{_.debug("token timeout, ".concat(i)),this.reset(e.uid)},y("MAX_P2P_TIMEOUT")),!0)}handleUserOnline(){return C(this,null,function*(){const e=yield We(this.signal,he.CALL,void 0),i=yield this.send(he.CALL,e);this.signal.emit(ot.P2P_CONNECTION,i,!0)})}reset(e,i){return C(this,null,function*(){const n=this.userMap.get(e);n&&(this.emit(ya.ABORT),this.signal.emit(mt.ON_USER_OFFLINE,{uid:n.uid,reason:rW.P2P_TOKEN_CHANGED}),this._sequence=0,this.userMap.clear(),i||(_.debug("change local token from ".concat(i," to ").concat(i)),this.token=Gt(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(ya.ABORT)}}S(gs,"MAX_SIZE",1),S(gs,"MAX_MESSAGE_SIZE",1024);class x4 extends $t{get connectionState(){return this._connectionState}set connectionState(e){e!==this._connectionState&&(this._connectionState=e,e===Ht.CONNECTED?this.emit(ot.WS_CONNECTED):e===Ht.RECONNECTING?this.emit(ot.WS_RECONNECTING,this._websocketReconnectReason):e===Ht.CLOSED&&this.emit(ot.WS_CLOSED,this._disconnectedReason))}get currentURLIndex(){return this.websocket.currentURLIndex}get url(){return this.websocket&&this.websocket.url||null}get rtt(){return this.rttRolling.mean()}constructor(e,i){super(),S(this,"_disconnectedReason",void 0),S(this,"_websocketReconnectReason",void 0),S(this,"_connectionState",Ht.CLOSED),S(this,"reconnectToken",void 0),S(this,"p2pToken",void 0),S(this,"websocket",void 0),S(this,"openConnectionTime",void 0),S(this,"clientId",void 0),S(this,"lastMsgTime",Date.now()),S(this,"uploadCache",[]),S(this,"uploadCacheInterval",void 0),S(this,"rttRolling",new RI(5)),S(this,"pingpongTimer",void 0),S(this,"pingpongTimeoutCount",0),S(this,"joinResponse",void 0),S(this,"multiIpOption",void 0),S(this,"initError",void 0),S(this,"spec",void 0),S(this,"store",void 0),S(this,"_external_signal",void 0),S(this,"onWebsocketMessage",n=>{if(n.data instanceof ArrayBuffer)return void this.emit(ot.ON_BINARY_DATA,n.data);const r=JSON.parse(n.data);if(this.lastMsgTime=Date.now(),Object.prototype.hasOwnProperty.call(r,"_id")){const o="res-@".concat(r._id);this.emit(o,r._result,r._message)}else if(Object.prototype.hasOwnProperty.call(r,"_type")){switch(r._type){case mt.ON_DATA_STREAM:return void this.handleDataStream(r._message);case mt.MUTE_AUDIO:case mt.MUTE_VIDEO:case mt.ON_P2P_LOST:case mt.ON_USER_ONLINE:return;case mt.ON_USER_OFFLINE:const{uid:o}=r._message;return _.debug("[".concat(this.clientId,"] user-offline uid: ").concat(o)),void this._external_signal.reset(o)}if(this.emit(r._type,r._message),r._type===mt.ON_NOTIFICATION&&this.handleNotification(r._message),r._type===mt.ON_USER_BANNED)switch(r._message.error_code){case 14:this.close(bt.UID_BANNED);break;case 15:this.close(bt.IP_BANNED);break;case 16:this.close(bt.CHANNEL_BANNED)}if(r._type===mt.ON_USER_LICENSE_BANNED)switch(r._message.error_code){case tt.ERR_LICENSE_MISSING:this.close(bt.LICENSE_MISSING);break;case tt.ERR_LICENSE_EXPIRED:this.close(bt.LICENSE_EXPIRED);break;case tt.ERR_LICENSE_MINUTES_EXCEEDED:this.close(bt.LICENSE_MINUTES_EXCEEDED);break;case tt.ERR_LICENSE_PERIOD_INVALID:this.close(bt.LICENSE_PERIOD_INVALID);break;case tt.ERR_LICENSE_MULTIPLE_SDK_SERVICE:this.close(bt.LICENSE_MULTIPLE_SDK_SERVICE);break;case tt.ERR_LICENSE_ILLEGAL:this.close(bt.LICENSE_ILLEGAL);break;default:this.close()}}}),this.clientId=e.clientId,this.spec=e,this.store=i,this.websocket=new Om("gateway-".concat(this.clientId),this.spec.retryConfig,!0,y("JOIN_GATEWAY_USE_DUAL_DOMAIN"),y("JOIN_GATEWAY_USE_443PORT_ONLY"),i),this.handleWebsocketEvents(),window.addEventListener("offline",()=>{this.connectionState===Ht.CONNECTED&&this.reconnect("retry",Ge.OFFLINE)}),this.p2pToken=Gt(6,""),this._external_signal=new gs(this,this.p2pToken)}request(e,i,n,r){return C(this,null,function*(){const o=Gt(6,""),s={_id:o,_type:e,_message:i},a=this.websocket.connectionID,c=()=>new K((g,m)=>{if(this.connectionState===Ht.CONNECTED)return g();const f=()=>{this.off(ot.WS_CLOSED,T),g()},T=()=>{this.off(ot.WS_CONNECTED,f),m(new k(v.WS_ABORT))};this.once(ot.WS_CONNECTED,f),this.once(ot.WS_CLOSED,T)});if(this.connectionState!==Ht.CONNECTING&&this.connectionState!==Ht.RECONNECTING||e===nt.JOIN||e===nt.REJOIN||(yield c()),this.websocket.sendMessage(s,!0),r)return;const d=new K((g,m)=>{let f=!1;const T=(A,N)=>{f=!0,g({isSuccess:A==="success",message:N||{}}),this.off(ot.WS_CLOSED,R),this.off(ot.WS_RECONNECTING,R),this.emit(ot.REQUEST_SUCCESS,e,i)};this.once("res-@".concat(o),T);const R=()=>{m(new k(v.WS_ABORT,"type: ".concat(e))),this.off(ot.WS_CLOSED,R),this.off(ot.WS_RECONNECTING,R),this.off("res-@".concat(o),T)};this.once(ot.WS_CLOSED,R),this.once(ot.WS_RECONNECTING,R),Ue(y("SIGNAL_REQUEST_TIMEOUT")).then(()=>{this.websocket.connectionID!==a||f||(_.warning("[".concat(this.clientId,"] ws request timeout, type: ").concat(e)),this.emit(ot.REQUEST_TIMEOUT,e,i))})});let l=null;try{l=yield d}catch(g){if(this.connectionState===Ht.CLOSED||e===nt.LEAVE)throw new k(v.WS_ABORT);return!this.spec.forceWaitGatewayResponse||n?g.throw():e===nt.JOIN||e===nt.REJOIN?null:(yield c(),yield this.request(e,i))}if(l.isSuccess)return l.message;const u=Number(l.message.error_code||l.message.code),h=jc(u),p=new k(v.UNEXPECTED_RESPONSE,"".concat(h.desc,": ").concat(l.message.error_str),{code:u,data:l.message,desc:h.desc});return h.action==="success"?l.message:(_.warning("[".concat(this.clientId,"] [").concat(this.websocket.connectionID,"] unexpected response from type ").concat(e,", error_code: ").concat(u,", message: ").concat(h.desc,", action: ").concat(h.action)),u===tt.ERR_TOO_MANY_BROADCASTERS?((e===nt.JOIN||e===nt.REJOIN)&&(this.initError=p,this.close()),p.throw()):h.action==="failed"?p.throw():h.action==="quit"?(this.initError=p,this.close(),p.throw()):(u===tt.ERR_JOIN_BY_MULTI_IP?(this.multiIpOption=l.message.option,_.warning("[".concat(this.clientId,"] detect multi ip, recover")),this.reconnect("recover",Ge.MULTI_IP)):this.reconnect(h.action,Ge.SERVER_ERROR),e===nt.JOIN||e===nt.REJOIN?null:yield this.request(e,i)))})}waitMessage(e,i){return new K(n=>{const r=o=>{(!i||i(o))&&(this.off(e,r),n(o))};this.on(e,r)})}uploadWRTCStats(e){if(!this.store.sessionId)return void _.warn("[".concat(this.clientId,"] no session id when upload wrtc stats"));const i={lts:Date.now(),sid:this.store.sessionId,uid:this.store.intUid,stats:e};this.upload(Fc.WRTC_STATS,i)}upload(e,i){const n={_type:e,_message:i};try{this.websocket.sendMessage(n)}catch(r){const o=y("MAX_UPLOAD_CACHE")||50;this.uploadCache.push(n),this.uploadCache.length>o&&this.uploadCache.splice(0,1),this.uploadCache.length>0&&!this.uploadCacheInterval&&(this.uploadCacheInterval=window.setInterval(()=>{if(this.connectionState!==Ht.CONNECTED)return;const s=this.uploadCache.splice(0,1)[0];this.uploadCache.length===0&&(window.clearInterval(this.uploadCacheInterval),this.uploadCacheInterval=void 0),this.upload(s._type,s._message)},y("UPLOAD_CACHE_INTERVAL")||2e3))}}send(e,i){const n={_type:e,_message:i};this.websocket.sendMessage(n)}sendExtensionMessage(e,i,n){return C(this,null,function*(){return yield this._external_signal.send(e,i,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 K((i,n)=>{this.once(ot.WS_CONNECTED,()=>i(this.joinResponse)),this.once(ot.WS_CLOSED,()=>n(this.initError||new k(v.WS_ABORT))),this.connectionState=Ht.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||bt.LEAVE,this.connectionState=Ht.CLOSED,_.debug("[".concat(this.clientId,"] ")+"will close websocket in signal"),this.websocket.close(),this.p2pToken=Gt(6,""),this._external_signal.clear(),this._external_signal=new gs(this,this.p2pToken)}join(){return C(this,null,function*(){if(!this.joinResponse){this.emit(ot.ABORT_P2P_EXECUTION);const e=yield We(this,ot.REQUEST_JOIN_INFO),i=yield this.request(nt.JOIN,e);if(!i)return this.emit(ot.REPORT_JOIN_GATEWAY,v.TIMEOUT,this.url||""),!1;this.joinResponse=i,this.emit(ot.JOIN_RESPONSE,this.joinResponse),this.reconnectToken=this.joinResponse.rejoin_token}return this.connectionState=Ht.CONNECTED,this.pingpongTimer&&window.clearInterval(this.pingpongTimer),this.pingpongTimer=window.setInterval(this.handlePingPong.bind(this),3e3),!0})}reconnect(e,i){this.pingpongTimer&&(this.pingpongTimeoutCount=0,window.clearInterval(this.pingpongTimer),this.pingpongTimer=void 0),this.websocket.reconnect(e,i)}handleDataStream(e){try{var i;const n=Qo(e.payload),r=new TextDecoder().decode(n),o=JSON.parse(r);"total"in o&&"id"in o||G(i=Object.values(he)).call(i,o._type)?(o._uid=e.uid,this._external_signal.onMessage(o)):this.emit(mt.ON_DATA_STREAM,e)}catch(n){this.emit(mt.ON_DATA_STREAM,e)}}handleNotification(e){_.debug("[".concat(this.clientId,"] receive notification: "),e);const i=jc(e.code);if(i.action!=="success"){if(i.action!=="failed")return i.action==="quit"?(i.desc==="ERR_REPEAT_JOIN_CHANNEL"&&this.close(bt.UID_BANNED),void this.close()):void this.reconnect(i.action,Ge.SERVER_ERROR);_.error("[".concat(this.clientId,"] ignore error: "),i.desc)}}handlePingPong(){if(!this.websocket||this.websocket.state!=="connected")return;this.pingpongTimeoutCount>0&&this.rttRolling.add(3e3),this.pingpongTimeoutCount+=1;const e=y("PING_PONG_TIME_OUT"),i=Date.now();this.pingpongTimeoutCount>=e&&(_.warning("[".concat(this.clientId,"] PINGPONG Timeout. Last Socket Message: ").concat(i-this.lastMsgTime,"ms")),i-this.lastMsgTime>y("WEBSOCKET_TIMEOUT_MIN"))?this.reconnect("retry",Ge.TIMEOUT):this.request(nt.PING,void 0,!0).then(()=>{this.pingpongTimeoutCount=0;const n=Date.now()-i;this.rttRolling.add(n),y("REPORT_STATS")&&this.send(nt.PING_BACK,{pingpongElapse:n})}).catch(n=>{})}handleWebsocketEvents(){this.websocket.on(dt.RECONNECT_CREATE_CONNECTION,e=>{this.emit(ot.WS_RECONNECT_CREATE_CONNECTION,e)}),this.websocket.on(dt.ON_MESSAGE,this.onWebsocketMessage),this.websocket.on(dt.CLOSED,()=>{this.connectionState=Ht.CLOSED}),this.websocket.on(dt.FAILED,()=>{this._disconnectedReason=bt.NETWORK_ERROR,this.connectionState=Ht.CLOSED}),this.websocket.on(dt.RECONNECTING,e=>{this._websocketReconnectReason=e,this.joinResponse=void 0,this.connectionState===Ht.CONNECTED?this.connectionState=Ht.RECONNECTING:this.connectionState=Ht.CONNECTING}),this.websocket.on(dt.WILL_RECONNECT,(e,i,n)=>{e!=="retry"?(_.debug("".concat(this.clientId," websocket will_connect event, renewSession reconnectMode is ").concat(e)),this.reconnectToken=void 0):_.debug("".concat(this.clientId," reconnect mode is retry, no need to renew session")),n(e)}),this.websocket.on(dt.CONNECTED,()=>{this.openConnectionTime=Date.now(),this.join().catch(e=>{if(this.emit(ot.REPORT_JOIN_GATEWAY,e,this.url||""),e instanceof k&&e.code===v.UNEXPECTED_RESPONSE&&e.data.code===tt.ERR_NO_AUTHORIZED)return _.warning("[".concat(this.clientId,"] reconnect no authorized, recover")),void this.reconnect("recover",Ge.SERVER_ERROR);_.error("[".concat(this.clientId,"] join gateway request failed"),e.toString()),this.spec.forceWaitGatewayResponse?this.reconnect("tryNext",Ge.SERVER_ERROR):(this.initError=e,this.close())})}),this.websocket.on(dt.REQUEST_NEW_URLS,(e,i)=>{We(this,ot.REQUEST_RECOVER,this.multiIpOption).then(e).catch(i)}),this.websocket.on(dt.ON_TOKEN_PRIVILEGE_DID_EXPIRE,()=>{this.emit(mt.ON_TOKEN_PRIVILEGE_DID_EXPIRE)})}}const V4={name:"P2PChannel",create:function(t){let{store:e,statsCollector:i}=t;return new U4(e,i)},createSubmodule:function(t){let{store:e,spec:i}=t;return new x4(i,e)}};function KN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function YN(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?KN(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):KN(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}class F4{constructor(e){S(this,"sessionDesc",void 0),S(this,"localCapabilities",void 0),S(this,"rtpCapabilities",void 0),S(this,"candidates",void 0),S(this,"_originCandidates",void 0),S(this,"iceParameters",void 0),S(this,"dtlsParameters",void 0),S(this,"setup",void 0),S(this,"currentMidIndex",void 0),S(this,"cname",void 0),e=te(e);const{iceParameters:i,dtlsParameters:n,candidates:r,rtpCapabilities:o,setup:s,localCapabilities:a,sdkCodec:c,cname:d}=e,l=Ni(`v=0
o=- 0 0 IN IP4 127.0.0.1
s=AgoraGateway
t=0 0
a=group:BUNDLE audio video
a=msid-semantic: WMS
a=ice-lite
m=audio 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 127.0.0.1
a=rtcp:9 IN IP4 0.0.0.0
a=sendrecv
a=rtcp-mux
a=rtcp-rsize
a=mid:audio
m=video 9 UDP/TLS/RTP/SAVPF 0
c=IN IP4 127.0.0.1
a=rtcp:9 IN IP4 0.0.0.0
a=sendrecv
a=rtcp-mux
a=rtcp-rsize
a=mid:video
`);this.rtpCapabilities=o,this.candidates=r,this._originCandidates=te(r),this.iceParameters=i,this.dtlsParameters=n,this.setup=s,this.localCapabilities=a,this.cname=d;for(let u=0;u<l.mediaDescriptions.length;u++){const h=l.mediaDescriptions[u];if(h.attributes.iceUfrag=i.iceUfrag,h.attributes.icePwd=i.icePwd,h.attributes.fingerprints=n.fingerprints,h.attributes.candidates=r,h.attributes.setup=s,h.media.mediaType==="video"){h.media.fmts=o.videoCodecs.map(g=>g.payloadType.toString(10));let p=o.videoCodecs.filter(g=>{var m,f;return(m=g.rtpMap)===null||m===void 0?void 0:G(f=m.encodingName.toLowerCase()).call(f,c)});p.length===0&&(p=o.videoCodecs),h.attributes.payloads=p,h.attributes.extmaps=o.videoExtensions}h.media.mediaType==="audio"&&(h.media.fmts=o.audioCodecs.map(p=>p.payloadType.toString(10)),h.attributes.payloads=o.audioCodecs,h.attributes.extmaps=o.audioExtensions),l.mediaDescriptions[u]=this.mungMediaDesc(h)}this.sessionDesc=l,this.currentMidIndex=l.mediaDescriptions.length-1}toString(){return mo(this.sessionDesc)}send(e,i,n){const{ssrcs:r,ssrcGroups:o}=as(i,this.cname),s=this.sessionDesc.mediaDescriptions.find(d=>e===q.VIDEO?d.media.mediaType==="video":d.media.mediaType==="audio"),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(i=>{let{kind:n,ssrcMsg:r}=i;return this.send(n,r,void 0)})}stopSending(e){this.sessionDesc.mediaDescriptions.forEach(i=>{const n=[],r=[],o=[];i.attributes.ssrcs.forEach(s=>{G(e).call(e,s.attributes.label||"")?o.push(s):n.push(s)}),i.attributes.ssrcGroups.forEach(s=>{var a;G(a=o.map(c=>c.ssrcId)).call(a,s.ssrcIds[0])||r.push(s)}),i.attributes.ssrcs=n,i.attributes.ssrcGroups=r})}mute(e){const i=this.sessionDesc.mediaDescriptions.find(n=>n.attributes.mid===e);if(!i)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.mute."));i.attributes.direction="inactive"}unmute(e){const i=this.sessionDesc.mediaDescriptions.find(n=>n.attributes.mid===e);if(!i)throw new Error("mediaDescription not found with ".concat(e," in remote SDP when calling RemoteSDP.unmute."));i.attributes.direction="sendonly"}receive(e,i,n){e.forEach((r,o)=>{const s=r._mediaStreamTrack,a=this.sessionDesc.mediaDescriptions.findIndex(d=>d.attributes.mid===s.kind),c=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[a],r);this.sessionDesc.mediaDescriptions[a]=c})}stopReceiving(e){}updateCandidates(e){const i=this._originCandidates.filter(r=>r.transport==="udp"),n=[];if(i.forEach(r=>{n.push(YN(YN({},r),{},{foundation:"tcpcandidate",priority:Number(r.priority)-1+"",transport:"tcp",port:Number(r.port)+90+""}))}),i.length!==0){switch(e){case Xe.TCP_RELAY:this.candidates=n;break;case Xe.UDP_TCP_RELAY:case Xe.RELAY:this.candidates=[...i,...n];break;default:this.candidates=i}for(const r of this.sessionDesc.mediaDescriptions)r.attributes.candidates=this.candidates}}restartICE(e){e=te(e),this.iceParameters=e,this.sessionDesc.mediaDescriptions.forEach(i=>{i.attributes.iceUfrag=e.iceUfrag,i.attributes.icePwd=e.icePwd})}predictReceivingMids(e){const i=[];for(let n=0;n<e;n++)i.push((this.currentMidIndex+n+1).toString(10));return i}mungRecvMediaDsec(e,i){const n=te(e);return ba(n,i),Lm(n,i),n}updateRecvMedia(e,i){const n=this.sessionDesc.mediaDescriptions.findIndex(r=>r.attributes.mid===e);if(n!==-1){const r=this.mungRecvMediaDsec(this.sessionDesc.mediaDescriptions[n],i);this.sessionDesc.mediaDescriptions[n]=r}}bumpMid(e){this.currentMidIndex+=e}updateTrackLabel(e,i,n){const r=this.sessionDesc.mediaDescriptions.find(s=>e===q.VIDEO?s.attributes.mid==="video":s.attributes.mid==="audio");if(r){const s=r.attributes.ssrcs.find(a=>a.attributes.label===i);var o;s&&(s.attributes.label=n,(o=s.attributes.msid)===null||o===void 0||o.replace(i,n))}}mungMediaDesc(e){const i=te(e);return Pm(i),function(n){const r=n.attributes.extmaps.find(o=>Bu(o.extensionName));r&&n.attributes.extmaps.splice(n.attributes.extmaps.indexOf(r),1),n.attributes.payloads.forEach(o=>{const s=o.rtcpFeedbacks.findIndex(a=>a.type==="transport-cc");s!==-1&&o.rtcpFeedbacks.splice(s,1)})}(i),i}getSSRC(e){for(const i of this.sessionDesc.mediaDescriptions)for(const n of i.attributes.ssrcs)if(n.attributes.label===e)return[n]}}var jt;function qN(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),i.push.apply(i,n)}return i}function Rh(t){for(var e=1;e<arguments.length;e++){var i=arguments[e]!=null?arguments[e]:{};e%2?qN(Object(i),!0).forEach(function(n){S(t,n,i[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):qN(Object(i)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(i,n))})}return t}let B4=(jt=class Cd extends rw{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 i;return G(i=Object.keys(Eu)).call(i,e)}))]}constructor(e,i){super(e,i),S(this,"store",void 0),S(this,"peerConnection",void 0),S(this,"remoteSDP",void 0),S(this,"initialOffer",void 0),S(this,"statsFilter",void 0),S(this,"useRTX",!1),S(this,"localCapabilities",void 0),S(this,"localCandidateCount",0),S(this,"allCandidatesReceived",!1),S(this,"establishPromise",void 0),S(this,"mutex",void 0),this.store=i,this.mutex=new qe("P2PConnection-mutex",i.clientId),this.peerConnection=new RTCPeerConnection(Cd.resolvePCConfiguration(e),{optional:[{googDscp:!0}]}),this.statsFilter=KE(this.peerConnection,y("STATS_UPDATE_INTERVAL"),void 0,ne()?1200:void 0),this.bindPCEvents(),this.bindStatsEvents(),this.store.p2pId=this.store.p2pId+1,this.establishPromise=this.establish()}establish(){return C(this,null,function*(){try{const e=yield this.peerConnection.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0});if(!e.sdp)throw new Error("Cannot get initialOffer.sdp when trying to establish PeerConnection.");const i=Ro(e.sdp),n=Hc(e.sdp,{filterRTX:!this.useRTX,filterVideoFec:y("FILTER_VIDEO_FEC"),filterAudioFec:y("FILTER_AUDIO_FEC"),filterAudioCodec:["opus"]});return this.localCapabilities=n,this.initialOffer=e,Rh(Rh({},i),{},{rtpCapabilities:{send:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},recv:{audioCodecs:[],audioExtensions:[],videoCodecs:[],videoExtensions:[]},sendrecv:n},offerSDP:e.sdp})}catch(e){throw new k(v.GET_LOCAL_CONNECTION_PARAMS_FAILED,e.toString())}})}updateRemoteConnect(){return C(this,null,function*(){})}connect(e){return C(this,null,function*(){try{if(!this.initialOffer)throw new Error("Cannot establish P2PConnection without initial offer.");this.remoteSDP=new F4(Rh(Rh({},e),{},{rtpCapabilities:e.rtpCapabilities.send,localCapabilities:this.localCapabilities,sdkCodec:this.store.codec}));const i=this.remoteSDP.toString();yield this.peerConnection.setLocalDescription(this.initialOffer),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:i})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.connect failed; ".concat(i.toString()))}})}updateRemoteRTPCapabilities(e,i){return C(this,null,function*(){throw new k(v.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")})}getPreMedia(e){}send(e,i){var n=this;return cn(function*(){const r=yield Rt(n.mutex.lock());try{if(!n.remoteSDP)throw new Error("Cannot call P2PConnection.send before remote SDP created");const o=e.map(h=>n.peerConnection.addTrack(h._mediaStreamTrack)),s=yield Rt(n.peerConnection.createOffer()),a=Ni(s.sdp),c=e.map(h=>{const p=h._mediaStreamTrack,g=a.mediaDescriptions.find(m=>m.attributes.mid===p.kind);if(!g)throw new Error("Cannot extract ssrc from mediaDescription.");return function(m,f,T){const R=m.attributes.ssrcs.filter(N=>N.attributes.label===f),A=m.attributes.ssrcGroups;if(R.length===0)throw new Error("Cannot extract ssrc from plan-b SDP.");if(A&&R.length>1){const N=A.find(O=>O.ssrcIds.indexOf(R[0].ssrcId)!==-1);return N?[{ssrcId:N.ssrcIds[0],rtx:T?N.ssrcIds[1]:void 0}]:[{ssrcId:R[0].ssrcId}]}return[{ssrcId:R[0].ssrcId}]}(g,p.id,n.useRTX)});let d;try{d=yield c}catch(h){throw o.forEach(p=>{je()&&p.replaceTrack(null),n.peerConnection.removeTrack(p)}),h}const l=n.mungSendOfferSDP(s.sdp,e);n.remoteSDP.receive(e,i,d);const u=n.remoteSDP.toString();return yield Rt(n.peerConnection.setLocalDescription({type:"offer",sdp:l})),yield Rt(n.applySendEncodings(o,e)),yield Rt(n.peerConnection.setRemoteDescription({type:"answer",sdp:u})),e.map((h,p)=>{const g=h._mediaStreamTrack.id;return{localSSRC:c[p],id:g}})}catch(o){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.send failed; ".concat(o.toString()))}finally{r()}})()}stopSending(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopSending before remote SDP created");const i=this.peerConnection.getSenders().filter(o=>{var s;return e.indexOf(((s=o.track)===null||s===void 0?void 0:s.id)||"")!==-1});if(i.length!==e.length)throw new Error("Transceivers' length doesn't match mids' length when trying to call P2PConnection.stopSending.");i.map(o=>{je()&&o.replaceTrack(null),this.peerConnection.removeTrack(o)});const n=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(n),this.remoteSDP.stopReceiving(e);const r=this.remoteSDP.toString();yield this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.stopSending failed; ".concat(i.toString()))}})}receive(e,i,n,r){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.receive ".concat(e," before remoteSDP created."));const{id:o,mslabel:s}=this.remoteSDP.send(e,i,r),a=new K((l,u)=>{const h=setTimeout(()=>{u(new Error("Cannot receive track, id: ".concat(o)))},1e4),p=g=>{const m=vt();if((m.name==="Safari"&&Number(m.version)===11||li())&&g.track.id!==o&&g.streams[0].id===s){var f;const T=g.streams[0].getTracks()[0];return(f=this.remoteSDP)===null||f===void 0||f.updateTrackLabel(e,o,g.track.id),this.peerConnection.removeEventListener("track",p),clearTimeout(h),void l(T)}if(g.track.id===o)return this.peerConnection.removeEventListener("track",p),clearTimeout(h),void l(g.track)};this.peerConnection.addEventListener("track",p)}),c=this.remoteSDP.toString();yield this.peerConnection.setRemoteDescription({type:"offer",sdp:c});const d=yield this.peerConnection.createAnswer();return yield this.peerConnection.setLocalDescription(d),{track:yield a,id:o}}catch(o){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(o.toString()))}})}stopReceiving(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.stopReceiving before remote SDP created.");this.remoteSDP.stopSending(e);const i=this.remoteSDP.toString();yield this.peerConnection.setRemoteDescription({type:"offer",sdp:i});const n=yield this.peerConnection.createAnswer();yield this.peerConnection.setLocalDescription(n)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection stopReceiving failed; ".concat(i.toString()))}})}muteRemote(e){return C(this,null,function*(){})}unmuteRemote(e){return C(this,null,function*(){})}muteLocal(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.muteLocal before remote SDP created.");const i=this.peerConnection.getSenders().filter(n=>{var r;return e.indexOf(((r=n.track)===null||r===void 0?void 0:r.id)||"")!==-1});if(i.length!==e.length)throw new Error("sender' length doesn't match mids' length.");i.map(n=>{if(je()&&n.track)n.track.enabled=!1;else{const r=n.getParameters();r.encodings.forEach(o=>o.active=!1),n.setParameters(r)}})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.muteLocal failed; ".concat(i.toString()))}})}unmuteLocal(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.unmuteLocal before remote SDP created.");const i=this.peerConnection.getSenders().filter(o=>{var s;return e.indexOf(((s=o.track)===null||s===void 0?void 0:s.id)||"")!==-1});if(i.length!==e.length)throw new Error("Senders' length doesn't match mids' length.");i.map(o=>C(this,null,function*(){if(je()&&o.track)o.track.enabled=!0;else{const s=o.getParameters();s.encodings.forEach(a=>a.active=!0),yield o.setParameters(s)}}));const n=yield this.peerConnection.createOffer();yield this.peerConnection.setLocalDescription(n);const r=this.remoteSDP.toString();yield this.peerConnection.setRemoteDescription({type:"answer",sdp:r})}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.unmuteLocal failed; ".concat(i.toString()))}})}restartICE(e){var i=this;return cn(function*(){const n=yield Rt(i.mutex.lock("From P2PConnection.restartICE"));try{if(!i.remoteSDP)throw new Error("Cannot restartICE before remoteSDP created.");const r=Ct().supportPCSetConfiguration;if(e===Xe.RELAY&&!r)return;if(r){const d=i.peerConnection.getConfiguration(),l=e===Xe.RELAY?"relay":"all";d.iceTransportPolicy!==l&&(_.debug("[".concat(i.store.clientId,"] restartICE change iceTransportPolicy from [").concat(d.iceTransportPolicy,"] to [").concat(l,"]")),d.iceTransportPolicy=l,i.peerConnection.setConfiguration(d))}e!==Xe.RELAY&&i.remoteSDP.updateCandidates(e);const o=yield Rt(i.peerConnection.createOffer({iceRestart:!0}));if(!o.sdp)throw new Error("Cannot restartICE because restart offer SDP does not exist.");const s=Ro(o.sdp),{remoteIceParameters:a}=yield s.iceParameters;i.remoteSDP.restartICE(a);const c=i.remoteSDP.toString();yield Rt(i.peerConnection.setLocalDescription(o)),yield Rt(i.peerConnection.setRemoteDescription({type:"answer",sdp:c}))}catch(r){_.warning("[".concat(i.store.clientId,"] restart ICE failed, abort operation"),r)}finally{n()}})()}close(){var e;this.peerConnection.close(),(e=this.onConnectionStateChange)===null||e===void 0||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)}updateEncoderConfig(e,i){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.updateEncoderConfig before remote SDP created.");const n=yield this.peerConnection.createOffer(),r=this.mungSendOfferSDP(n.sdp,[i]);this.remoteSDP.updateRecvMedia(i._mediaStreamTrack.kind,i);const o=this.remoteSDP.toString();yield this.peerConnection.setLocalDescription({type:"offer",sdp:r}),yield this.peerConnection.setRemoteDescription({type:"answer",sdp:o})}catch(n){throw new k(v.EXCHANGE_SDP_FAILED,n.toString())}})}updateSendParameters(e,i){return C(this,null,function*(){const n=this.peerConnection.getSenders().filter(r=>{var o;return((o=r.track)===null||o===void 0?void 0:o.id)===e});n.length===1&&(yield this.applySendEncodings(n,[i]))})}setStatsRemoteVideoIsReady(e,i){this.statsFilter.setVideoIsReady2(e,i)}replaceTrack(e,i){return C(this,null,function*(){const n=this.peerConnection.getSenders().find(r=>{var o;return((o=r.track)===null||o===void 0?void 0:o.id)===i});n&&(yield n.replaceTrack(e._mediaStreamTrack))})}createDataChannels(e,i){throw new k(v.NOT_SUPPORTED,"Planb mode does not support createDataChannels.")}stopDataChannels(e){throw new k(v.NOT_SUPPORTED,"Planb mode does not support stopDataChannels.")}bindPCEvents(){this.peerConnection.oniceconnectionstatechange=()=>{var e;(e=this.onICEConnectionStateChange)===null||e===void 0||e.call(this,this.peerConnection.iceConnectionState)},this.peerConnection.onconnectionstatechange=()=>{var e;(e=this.onConnectionStateChange)===null||e===void 0||e.call(this,this.peerConnection.connectionState)},this.peerConnection.onicecandidate=e=>{e.candidate?this.localCandidateCount+=1:(this.peerConnection.onicecandidate=null,this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] local candidate count"),this.localCandidateCount))},setTimeout(()=>{this.allCandidatesReceived||(this.allCandidatesReceived=!0,_.debug("[".concat(this.store.clientId,"] [pc-").concat(this.store.p2pId,"] onicecandidate timeout, local candidate count"),this.localCandidateCount))},y("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(e){const i={iceServers:[],sdpSemantics:"plan-b"};return e.iceServers?i.iceServers=e.iceServers:e.turnServer&&e.turnServer.mode!=="off"&&(Nc(e.turnServer.servers)?i.iceServers=e.turnServer.servers:(i.iceServers&&i.iceServers.push(...Cd.turnServerConfigToIceServers(e.turnServer.servers)),y("USE_TURN_SERVER_OF_GATEWAY")&&i.iceServers&&e.turnServer.serversFromGateway&&i.iceServers.push(...Cd.turnServerConfigToIceServers(e.turnServer.serversFromGateway)),e.turnServer.servers.concat(e.turnServer.serversFromGateway||[]).forEach(n=>{n.forceturn&&(i.iceTransportPolicy="relay")}))),i}static turnServerConfigToIceServers(e){const i=[];return e.forEach(n=>{n.security?n.tcpport&&i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turns:".concat(n.turnServerURL,":").concat(n.tcpport,"?transport=tcp")}):(n.udpport&&i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turn:".concat(n.turnServerURL,":").concat(n.udpport,"?transport=udp")}),n.tcpport&&i.push({username:n.username,credential:n.password,credentialType:"password",urls:"turn:".concat(n.turnServerURL,":").concat(n.tcpport,"?transport=tcp")}))}),i}updateRtpSenderEncodings(e,i){return C(this,null,function*(){var n;if(i||(i=this.peerConnection.getSenders().find(d=>{var l;return((l=d.track)===null||l===void 0?void 0:l.id)===e._mediaStreamTrack.id})),!i)return _.warn("[".concat(e.getTrackId(),"] no rtpSender found}"));if(!Ct().supportSetRtpSenderParameters)return _.warn("Browser not support set rtp-sender parameters");const r={},o={};if(e instanceof Yt)switch(e._optimizationMode){case"motion":r.degradationPreference="maintain-framerate";break;case"detail":r.degradationPreference="maintain-resolution";break;default:r.degradationPreference="balanced"}if(y("DSCP_TYPE")&&Vr()){var s;const d=y("DSCP_TYPE");G(s=["very-low","low","medium","high"]).call(s,d)&&(o.networkPriority=d)}const a=i.getParameters(),c=(n=a.encodings)===null||n===void 0?void 0:n[0];c&&Object.assign(c,o),Object.assign(a,r),_.debug("[".concat(e.getTrackId(),"] updateRtpSenderEncodings: ").concat(JSON.stringify(a.encodings))),yield i.setParameters(a)})}applySendEncodings(e,i){return C(this,null,function*(){try{if(!Ct().supportSetRtpSenderParameters||e.length!==i.length)return;for(let n=0;n<e.length;n++){const r=e[n],o=i[n];r&&o&&(yield this.updateRtpSenderEncodings(o,r))}}catch(n){_.debug("[".concat(this.store.clientId,"] Apply RTPSendEncodings failed."))}})}mungSendOfferSDP(e,i){const n=Ni(e);return i.forEach((r,o)=>{const s=r._mediaStreamTrack,a=n.mediaDescriptions.find(c=>c.attributes.mid===s.kind);a&&ba(a,r)}),mo(n)}bindStatsEvents(){this.statsFilter.onFirstAudioReceived=e=>{var i;(i=this.onFirstAudioReceived)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstVideoReceived=e=>{var i;(i=this.onFirstVideoReceived)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstAudioDecoded=e=>{var i;(i=this.onFirstAudioDecoded)===null||i===void 0||i.call(this,e)},this.statsFilter.onFirstVideoDecoded=(e,i,n)=>{var r;(r=this.onFirstVideoDecoded)===null||r===void 0||r.call(this,e,i,n)},this.statsFilter.onSelectedLocalCandidateChanged=(e,i)=>{var n;(n=this.onSelectedLocalCandidateChanged)===null||n===void 0||n.call(this,e,i)},this.statsFilter.onSelectedRemoteCandidateChanged=(e,i)=>{var n;(n=this.onSelectedRemoteCandidateChanged)===null||n===void 0||n.call(this,e,i)}}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}batchReceive(e){return C(this,null,function*(){try{if(!this.remoteSDP)throw new Error("Cannot call P2PConnection.batchReceive before remoteSDP created.");const i=this.remoteSDP.batchSend(e).map((o,s)=>{let{id:a,mslabel:c}=o;const{kind:d}=e[s];return new K((l,u)=>{const h=setTimeout(()=>{u(new Error("Cannot receive track, id: ".concat(a)))},1e4),p=g=>{const m=vt();if(m.name==="Safari"&&Number(m.version)===11&&g.track.id!==a&&g.streams[0].id===c){var f;const T=g.streams[0].getTracks()[0];return(f=this.remoteSDP)===null||f===void 0||f.updateTrackLabel(d,a,g.track.id),this.peerConnection.removeEventListener("track",p),clearTimeout(h),void l({track:T,id:a})}if(g.track.id===a)return this.peerConnection.removeEventListener("track",p),clearTimeout(h),void l({track:g.track,id:a})};this.peerConnection.addEventListener("track",p)})}),n=this.remoteSDP.toString();yield this.peerConnection.setRemoteDescription({type:"offer",sdp:n});const r=yield this.peerConnection.createAnswer();return yield this.peerConnection.setLocalDescription(r),yield K.all(i)}catch(i){throw new k(v.EXCHANGE_SDP_FAILED,"P2PConnection.receive failed; ".concat(i.toString()))}})}getRemoteSSRC(e){return C(this,null,function*(){if(!this.remoteSDP)return;const i=this.remoteSDP.getSSRC(e);return i==null?void 0:i[0].ssrcId})}setConfiguration(e){if(Ct().supportPCSetConfiguration){const i=Cd.resolvePCConfiguration(e);this.peerConnection.setConfiguration(i)}}},Q(jt.prototype,"connect",[En],Object.getOwnPropertyDescriptor(jt.prototype,"connect"),jt.prototype),Q(jt.prototype,"stopSending",[En],Object.getOwnPropertyDescriptor(jt.prototype,"stopSending"),jt.prototype),Q(jt.prototype,"receive",[En],Object.getOwnPropertyDescriptor(jt.prototype,"receive"),jt.prototype),Q(jt.prototype,"stopReceiving",[En],Object.getOwnPropertyDescriptor(jt.prototype,"stopReceiving"),jt.prototype),Q(jt.prototype,"muteRemote",[En],Object.getOwnPropertyDescriptor(jt.prototype,"muteRemote"),jt.prototype),Q(jt.prototype,"unmuteRemote",[En],Object.getOwnPropertyDescriptor(jt.prototype,"unmuteRemote"),jt.prototype),Q(jt.prototype,"muteLocal",[En],Object.getOwnPropertyDescriptor(jt.prototype,"muteLocal"),jt.prototype),Q(jt.prototype,"unmuteLocal",[En],Object.getOwnPropertyDescriptor(jt.prototype,"unmuteLocal"),jt.prototype),Q(jt.prototype,"close",[En],Object.getOwnPropertyDescriptor(jt.prototype,"close"),jt.prototype),Q(jt.prototype,"updateEncoderConfig",[En],Object.getOwnPropertyDescriptor(jt.prototype,"updateEncoderConfig"),jt.prototype),Q(jt.prototype,"updateSendParameters",[En],Object.getOwnPropertyDescriptor(jt.prototype,"updateSendParameters"),jt.prototype),Q(jt.prototype,"replaceTrack",[En],Object.getOwnPropertyDescriptor(jt.prototype,"replaceTrack"),jt.prototype),Q(jt.prototype,"getRemoteSSRC",[En],Object.getOwnPropertyDescriptor(jt.prototype,"getRemoteSSRC"),jt.prototype),jt);function En(t,e,i){const n=t[e];if(typeof n!="function")throw new Error("Cannot use mutex on object property.");return i.value=function(){return C(this,arguments,function*(){const r=this.mutex,o=yield r.lock("Locking from P2PConnection.".concat(e));try{for(var s=arguments.length,a=new Array(s),c=0;c<s;c++)a[c]=arguments[c];return yield n.apply(this,a)}finally{o()}})},i}const j4={name:"PlanBConnection",create:function(t){let{store:e,spec:i}=t;return new B4(i,e)}},G4={interceptLocalAudioFrame:function(e){return C(this,arguments,function*(t){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Ct().supportWebRTCEncodedTransform)return void _.warning("browser not support audio encoded transform");if(yu.has(t)||!t.track)return;const n={track:t.track};if(xr()){if(!t.createEncodedStreams)return void _.warning("browser not support createEncodedStreams() API");let o=null;try{o=t.createEncodedStreams()}catch(a){return void _.error("create audio-encoded-streams error",a&&a.message)}const s=new TransformStream({transform(a,c){n.controller||(n.controller=c),t.track&&t.track.id!==n.track.id&&(_.debug("audio track changed: ".concat(n.track.id," => ").concat(t.track.id)),n.track.removeEventListener("ended",r),n.track=t.track,n.track.addEventListener("ended",r));const d=i.metadata&&i.metadata();d?function(l,u){const{chunk:h,controller:p}=u,g=y("ENABLE_AUDIO_PTS_METADATA")?jr.AUDIO_64_BIT_PTS:jr.METADATA;h.data=function(m,f,T){const R=T.byteLength,A=R+Em+Wb,N=pm+_m+A,O=new ArrayBuffer(m.byteLength+N),w=new DataView(O);w.setUint8(0,Gb),w.setUint16(1,A),w.setUint8(3,f),w.setUint16(4,R);for(let M=0;M<R;M++)w.setUint8(6+M,T[M]);const L=new Uint8Array(w.buffer);return L.set(new Uint8Array(m),N),L.buffer}(h.data,g,l),p.enqueue(h)}(d,{sender:t,chunk:a,controller:c}):c.enqueue(a)}});o.readable.pipeThrough(s).pipeTo(o.writable)}else if(je()){if(typeof RTCRtpScriptTransform=="undefined")return void _.warning("browser not support RTCRtpScriptTransform");const o=Cu(),s=new MessageChannel;yield new K(c=>o.onmessage=d=>{d.data==="registered"&&c(void 0)});const a=new RTCRtpScriptTransform(o,{name:"audio-metadata-tx",port:s.port2},[s.port2]);t.transform=a,yield new K(c=>o.onmessage=d=>{d.data==="started"&&c(void 0)}),s.port1.onmessage=c=>{var d;if(c.data.transformed&&t.track&&((d=t.track)===null||d===void 0?void 0:d.id)!==n.track.id)_.debug("audio track changed: ".concat(n.track.id," => ").concat(t.track.id)),n.track.removeEventListener("ended",r),n.track=t.track,n.track.addEventListener("ended",r);else if(c.data.getMetadata){const l=i.metadata&&i.metadata();l&&s.port1.postMessage({metadata:l})}},n.worker=o}function r(){if(t.track){if(this.id!==t.track.id)return;t.track.removeEventListener("ended",r)}const o=yu.get(t);if(o){yu.delete(t);try{var s,a;(s=o.controller)===null||s===void 0||s.terminate(),(a=o.worker)===null||a===void 0||a.terminate()}catch(c){_.warning(c&&c.message)}}}yu.set(t,n),t.track.addEventListener("ended",r)})},interceptRemoteAudioFrame:function(e){return C(this,arguments,function*(t){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Ct().supportWebRTCEncodedTransform)return void _.warning("browser not support audio encoded transform");if(Nu.has(t))return;const n={track:t.track,onMetadata:i.onMetadata};if(xr()){if(!t.createEncodedStreams)return void _.warning("browser not support createEncodedStreams() API");AE(It.CHROME,87,116)||(i.enableTopn=!1);let o=null;try{o=t.createEncodedStreams()}catch(a){return void _.error("create audio-encoded-streams error",a&&a.message)}const s=new TransformStream({transform(a,c){n.controller||(n.controller=c),t.track&&t.track.id!==n.track.id&&(_.debug("audio track changed: ".concat(n.track.id," => ").concat(t.track.id)),n.track.removeEventListener("ended",r),n.track=t.track,n.track.addEventListener("ended",r)),i.enableTopn?function(d,l,u){var h;const p=Hb(new DataView(l.data));if(!p)return u.enqueue(l);const g=d.track.id;y3.set(g,d.track);const m=(h=p.tlv.find(O=>O.tag===jr.AUDIO_LEVEL))===null||h===void 0?void 0:h.value;let f=0;typeof m=="number"&&(f=127-m);const T=Math.round(Math.pow(10,f/60)-1),{selected:R,speaker:A}=function(O,w){let L=Ta.get(O);if(L||(L=function(M){const j=new Yb;return Ta.set(M,j),Zn||(Zn=new v3(y("TOPN_SILENCE_THRESHOLD")||500),Zn.on("ActiveSpeakerChanged",H=>{H!=null&&(bu=H)})),Zn.addSpeakers([j]),j}(O)),Ta.size<=qb)return{selected:!0,speaker:L};if(!Zn)throw new Error("no active speaker detector");return Zn.levelChanged(L.id,w),rs=Zn.loudest.map(M=>M.id),bu&&!G(rs).call(rs,bu)&&rs.length>=qb&&rs.pop(),{selected:G(rs).call(rs,L.id)||L.id===bu,speaker:L}}(d,T),N=function(O,w,L){const M=$n.get(O)||new C3(O,w);return M.score=L,$n.set(O,M),function(j){if(wu.set(j,!0),!Ou)return void(Ou=Date.now());const H=Date.now();H-Ou>1e3&&(wu.get(j)?wu.set(j,!1):(zb(j),wu.delete(j)),Ou=H)}(O),M}(g,d.track,A.energyScore);N.addSample(R),N.active&&(l.data=p.frame.buffer,u.enqueue(l))}(t,a,c):i.enableMetadata?function(d,l,u){const h=Hb(new DataView(d.data));if(!h)return l.enqueue(d);const p=h.tlv.find(g=>g.tag===jr.METADATA||g.tag===jr.AUDIO_64_BIT_PTS);p&&u&&p.value instanceof Uint8Array&&u(p.value),d.data=h.frame.buffer,l.enqueue(d)}(a,c,i.onMetadata):c.enqueue(a)}});o.readable.pipeThrough(s).pipeTo(o.writable)}else if(je()){if(typeof RTCRtpScriptTransform=="undefined")return void _.warning("browser not support RTCRtpScriptTransform");const o=Cu(),s=new MessageChannel;yield new K(c=>o.onmessage=d=>{d.data==="registered"&&c(void 0)});const a=new RTCRtpScriptTransform(o,{name:"audio-metadata-rx",port:s.port2},[s.port2]);t.transform=a,yield new K(c=>o.onmessage=d=>{d.data==="started"&&c(void 0)}),s.port1.onmessage=c=>{var d;c.data.transformed&&t.track&&((d=t.track)===null||d===void 0?void 0:d.id)!==n.track.id?(_.debug("audio track changed: ".concat(n.track.id," => ").concat(t.track.id)),n.track.removeEventListener("ended",r),n.track=t.track,n.track.addEventListener("ended",r)):c.data.metadata&&n.onMetadata&&n.onMetadata(c.data.metadata)},n.worker=o}function r(){t.track.removeEventListener("ended",r),function(o){const s=Nu.get(o);if(s){(function(d){const l=Ta.get(d);l&&(Ta.delete(d),Zn&&(Zn.removeSpeakers([l]),Ta.size===0&&(Zn.destroy(),Zn=null)))})(o),zb(o.track.id),Nu.delete(o);try{var a,c;(a=s.controller)===null||a===void 0||a.terminate(),(c=s.worker)===null||c===void 0||c.terminate()}catch(d){_.warning(d&&d.message)}}}(t)}Nu.set(t,n),t.track.addEventListener("ended",r)})},interceptLocalVideoFrame:function(t,e){return C(this,null,function*(){if(!Ct().supportWebRTCEncodedTransform)return void _.warning("browser not support video encoded transform");if(Du.has(t)||!t.track)return;const i={track:t.track};if(xr()){if(!t.createEncodedStreams)return void _.warning("browser not support createEncodedStreams() API");let r=null;try{r=t.createEncodedStreams()}catch(a){return void _.error("create video-encoded-streams error",a&&a.message)}const o=[];e.on("sei-to-send",a=>{o.push(a)});const s=new TransformStream({transform(a,c){i.controller||(i.controller=c),t.track&&t.track.id!==i.track.id&&(_.debug("video track changed: ".concat(i.track.id," => ").concat(t.track.id)),i.track.removeEventListener("ended",n),i.track=t.track,i.track.addEventListener("ended",n));const d=o.shift();d&&(a.data=function(l,u){const h=function(R){const A=R.length;let N=[],O=0;for(;O<A;)O+2<A&&R[O]===0&&R[O+1]===0&&(R[O+2]===0||R[O+2]===1||R[O+2]===2||R[O+2]===3)?(N.push(R[O],R[O+1],3,R[O+2]),O+=3):(N.push(R[O]),O++);return new Uint8Array(N)}(u),p=h.length,g=Math.floor(p/255),m=p%255,f=new Uint8Array(6+g+1+p+l.byteLength);f[0]=0,f[1]=0,f[2]=0,f[3]=1,f[4]=6,f[5]=101;let T=0;for(;T<g;)f[6+T]=255,T++;return f[6+T]=m,T++,f.set(h,6+T),f.set(new Uint8Array(l),6+T+p),f.buffer}(a.data,d)),c.enqueue(a)}});r.readable.pipeThrough(s).pipeTo(r.writable)}else{if(!je())return;{if(typeof RTCRtpScriptTransform=="undefined")return void _.warning("browser not support RTCRtpScriptTransform");const r=Cu(),o=new MessageChannel;yield new K(a=>r.onmessage=c=>{c.data==="registered"&&a(void 0)});const s=new RTCRtpScriptTransform(r,{name:"sei-tx",port:o.port2},[o.port2]);t.transform=s,yield new K(a=>r.onmessage=c=>{c.data==="started"&&a(void 0)}),e.on("sei-to-send",a=>{o.port1.postMessage({sei:a})}),o.port1.onmessage=a=>{var c;a.data.transformed&&t.track&&((c=t.track)===null||c===void 0?void 0:c.id)!==i.track.id&&(_.debug("video track changed: ".concat(i.track.id," => ").concat(t.track.id)),i.track.removeEventListener("ended",n),i.track=t.track,i.track.addEventListener("ended",n))},i.worker=r}}function n(){if(t.track){if(this.id!==t.track.id)return;t.track.removeEventListener("ended",n)}const r=Du.get(t);if(r){Du.delete(t);try{var o,s;(o=r.controller)===null||o===void 0||o.terminate(),(s=r.worker)===null||s===void 0||s.terminate()}catch(a){_.warning(a&&a.message)}}}Du.set(t,i),t.track.addEventListener("ended",n)})},interceptRemoteVideoFrame:function(e){return C(this,arguments,function*(t){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!Ct().supportWebRTCEncodedTransform)return void _.warning("browser not support video encoded transform");if(!t.track)return;if(Vc.has(t)){const o=Vc.get(t);return void(o&&(o.onSei=i.onSei))}const n={track:t.track,onSei:i.onSei};if(xr()){if(!t.createEncodedStreams)return void _.warning("browser not support createEncodedStreams() API");let o=null;try{o=t.createEncodedStreams()}catch(a){return void _.error("create video-encoded-streams error",a&&a.message)}const s=new TransformStream({transform(a,c){n.controller||(n.controller=c),t.track&&t.track.id!==n.track.id&&(_.debug("video track changed: ".concat(n.track.id," => ").concat(t.track.id)),n.track.removeEventListener("ended",r),n.track=t.track,n.track.addEventListener("ended",r));const d=function(l){const u=new DataView(l.data);let h=0;for(;h+4<l.data.byteLength;){if(u.getUint8(h+0)===0&&u.getUint8(h+1)===0&&u.getUint8(h+2)===0&&u.getUint8(h+3)===1&&u.getUint8(h+4)===6){let p=h+6,g=0,m=0;for(;(m=u.getUint8(p++))===255;)g+=255;g+=m;const f=I3(l.data,p,g);return new Uint8Array(f)}h++}return null}(a);d&&n.onSei&&n.onSei(d),c.enqueue(a)}});o.readable.pipeThrough(s).pipeTo(o.writable)}else if(je()){if(typeof RTCRtpScriptTransform=="undefined")return void _.warning("browser not support RTCRtpScriptTransform");const o=Cu(),s=new MessageChannel;yield new K(c=>o.onmessage=d=>{d.data==="registered"&&c(void 0)});const a=new RTCRtpScriptTransform(o,{name:"sei-rx",port:s.port2},[s.port2]);t.transform=a,yield new K(c=>o.onmessage=d=>{d.data==="started"&&c(void 0)}),s.port1.onmessage=c=>{var d;c.data.transformed&&t.track&&((d=t.track)===null||d===void 0?void 0:d.id)!==n.track.id?(_.debug("video track changed: ".concat(n.track.id," => ").concat(t.track.id)),n.track.removeEventListener("ended",r),n.track=t.track,n.track.addEventListener("ended",r)):c.data.sei&&n.onSei&&n.onSei(c.data.sei)},n.worker=o}function r(){if(t.track){if(this.id!==t.track.id)return;t.track.removeEventListener("ended",r)}(function(o){const s=Vc.get(o);if(s){Vc.delete(o);try{var a,c;(a=s.controller)===null||a===void 0||a.terminate(),(c=s.worker)===null||c===void 0||c.terminate()}catch(d){_.warning(d&&d.message)}}})(t)}Vc.set(t,n),t.track.addEventListener("ended",r)})}},W4={name:"InterceptFrame",create:()=>G4};YE(),kt("PROCESS_ID","process-".concat(Gt(8,""),"-").concat(Gt(4,""),"-").concat(Gt(4,""),"-").concat(Gt(4,""),"-").concat(Gt(12,""))),function(){let t;try{t=window.localStorage.getItem("websdk_ng_global_parameter")}catch(e){return void _.error("Error loading sdk config",e.message)}if(t)try{const e=JSON.parse(window.atob(t)),i=Date.now();_.debug("Loading global parameters from cache",e),Object.keys(e).forEach(n=>{if(Object.prototype.hasOwnProperty.call(Xt,n)){const{value:r,expires:o}=e[n];if(o&&o<=i)return;Qn[n]=r,Xt[n]=r}})}catch(e){_.error("Error loading mutableParamsCache: ".concat(t),e.message)}}(),Array.isArray(Qn.AREAS)&&Qn.AREAS.length>0&&Vm(Qn.AREAS,!0);const zN=(t,e,i)=>{_.debug("setParameter key:".concat(t,", value:").concat(JSON.stringify(e))),kt(t,e,i)};vo(h4,!1),vo(E4,!1),vo(JW,!1),vo(A4,!1),vo(d4,!1),vo(V4,!1),vo(j4,!1),vo(W4,!1);const Se=function(t){const e=new $t,i=t,n={getListeners:e.getListeners.bind(e),on:(r,o)=>(function(s,a){s===Tr.SECURITY_POLICY_VIOLATION&&wO(a,!0)}(r,o),e.on.bind(e)(r,o)),addListener:e.addListener.bind(e),once:e.once.bind(e),off:e.off.bind(e),removeAllListeners:e.removeAllListeners.bind(e),emit:e.emit.bind(e),safeEmit:e.safeEmit.bind(e)};return bO(bO({},i),n)}({__TRACK_LIST__:la,VERSION:dn,BUILD:XE,ESM_BUNDLER:!1,ESM:!1,UMD:!0,DEV:!1,setParameter:zN,getParameter:y,getSupportedCodec:function(){return C(this,null,function*(){let t={audio:[],video:[]};try{let e=new RTCPeerConnection;const i=yield function(n){return C(this,null,function*(){let r;return Ct().supportUnifiedPlan?(n.addTransceiver("video",{direction:"recvonly"}),n.addTransceiver("audio",{direction:"recvonly"}),r=(yield n.createOffer()).sdp):r=(yield n.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0})).sdp,r})}(e);if(!i)return t;e.close(),e=null,t=function(n){const r={video:[],audio:[]};return n.match(/ VP8/i)&&r.video.push("VP8"),n.match(/ VP9/i)&&r.video.push("VP9"),n.match(/ AV1/i)&&r.video.push("AV1"),n.match(/ H264/i)&&r.video.push("H264"),n.match(/ H265/i)&&r.video.push("H265"),n.match(/ opus/i)&&r.audio.push("OPUS"),n.match(/ PCMU/i)&&r.audio.push("PCMU"),n.match(/ PCMA/i)&&r.audio.push("PCMA"),n.match(/ G722/i)&&r.audio.push("G722"),r}(i)}catch(e){throw new P(v.CREATE_OFFER_FAILED,e.toString&&e.toString()).print()}return t})},checkSystemRequirements:function(){const t=Z.reportApiInvoke(null,{name:_e.CHECK_SYSTEM_REQUIREMENTS,options:[],tag:oe.TRACER});let e=!1;try{const o=window.RTCPeerConnection,s=navigator.mediaDevices&&navigator.mediaDevices.getUserMedia,a=window.WebSocket;e=!!(o&&s&&a),e&&NE()&&Jy(75)&&new o().close()}catch(o){return _.error("check system requirement failed: ",o),!1}let i=!1;const n=vt();n.name===It.CHROME&&Number(n.version)>=58&&(Xn.engine.name!=="WebKit"||function(){const o=vt();if(su()){if(o.os===we.MAC_OS)return!0;if(o.os===we.IOS){const s=Xn.os.version&&Xn.os.version.split(".");if(s&&Number(s[0])===14&&s[1]&&Number(s[1])>=3||s&&Number(s[0])>14)return!0}}return!1}())&&(i=!0),(n.name===It.FIREFOX&&Number(n.version)>=56||n.name===It.OPERA&&Number(n.version)>=45||n.name===It.SAFARI&&Number(n.version)>=11||n.name==="WebKit"&&(li()||bn())&&n.osVersion&&Number(n.osVersion.split(".")[0])>=11||iI()||vt().name===It.QQ)&&(i=!0),_.debug("checkSystemRequirements, api:",e,"browser",i);const r=e&&i;return t.onSuccess(r),r},getDevices:function(t){return en.enumerateDevices(!0,!0,t)},getMicrophones:function(t){return en.getRecordingDevices(t)},getCameras:function(t){return en.getCamerasDevices(t)},getElectronScreenSources:JI,getPlaybackDevices:function(t){return en.getSpeakers(t)},createClient:function(){var t;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{codec:"vp8",audioCodec:"opus",mode:"rtc"};const i=Gt(5,"client-"),n=Z.reportApiInvoke(null,{id:i,name:_e.CREATE_CLIENT,options:[e],tag:oe.TRACER});try{(function(r){Ae(r.codec,"config.codec",["vp8","vp9","av1","h264","h265"]),Ae(r.mode,"config.mode",["rtc","live","p2p"]),r.audioCodec!==void 0&&Ae(r.audioCodec,"config.audioCodec",["opus","pcmu","pcma","g722"]),r.proxyServer!==void 0&&Me(r.proxyServer,"config.proxyServer",1,1e4),r.turnServer!==void 0&&lI(r.turnServer),r.httpRetryConfig!==void 0&&dI(r.httpRetryConfig),r.websocketRetryConfig!==void 0&&dI(r.websocketRetryConfig)})(e)}catch(r){throw n.onError(r),r}return(Zy(16,0)||$y(16,0))&&(e.codec==="vp9"&&(e.codec="vp8",_.debug("browser not support vp9, force use vp8")),kt("UNSUPPORTED_VIDEO_CODEC",["vp9"])),e.audioCodec===void 0&&(e.audioCodec="opus"),n.onSuccess(),new QW(xn(xn({forceWaitGatewayResponse:!0},e),{},{role:G(t=["rtc","p2p"]).call(t,e.mode)?"host":e.role||"audience"}),i)},createCameraVideoTrack:function(){return C(this,arguments,function*(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=y("CAMERA_CAPTURE_CONFIG"),i=Gt(8,"track-cam-"),n=Z.reportApiInvoke(null,{id:i,tag:oe.TRACER,name:_e.CREATE_CAM_VIDEO_TRACK,options:[Qt({},t),e]});e&&(t.encoderConfig=e);const r=Ru(t);let o=null;_.info("start create camera video track with config",JSON.stringify(t),"trackId",i);try{o=(yield tn({video:r},i)).getVideoTracks()[0]||null}catch(a){throw n.onError(a),a}if(!o){const a=new k(v.UNEXPECTED_ERROR,"can not find track in media stream");return n.onError(a),a.throw(_)}if(t.optimizationMode&&hm(i,o,t,Nn(t.encoderConfig)),y("USE_STANDARD_BITRATE_DEFAULT")){const a=Nn(t.encoderConfig);t.encoderConfig=a,delete a.bitrateMax,delete a.bitrateMin}const s=new um(o,t,r,t.scalabiltyMode?fu(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,i);return n.onSuccess(s.getTrackId()),_.info("create camera video success, trackId:",i),s})},createCustomVideoTrack:function(t){const e=Gt(8,"track-cus-"),i=Z.reportApiInvoke(null,{id:e,tag:oe.TRACER,name:_e.CREATE_CUSTOM_VIDEO_TRACK,options:[t]});y("USE_STANDARD_BITRATE_DEFAULT")&&(delete t.bitrateMax,delete t.bitrateMin);const n=new Yt(t.mediaStreamTrack,{width:t.width,height:t.height,frameRate:t.frameRate,bitrateMax:t.bitrateMax,bitrateMin:t.bitrateMin},t.scalabiltyMode?fu(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,e,[Vt.CUSTOM_TRACK]);return i.onSuccess(n.getTrackId()),_.info("create custom video track success with config",t,"trackId",n.getTrackId()),n},createScreenVideoTrack:function(){return C(this,arguments,function*(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"disable";const i=typeof e=="object"?function(h){return sA(h)}(e):void 0;i&&(e="auto");const n=Gt(8,"track-scr-v-"),r=Z.reportApiInvoke(null,{id:n,tag:oe.TRACER,name:_e.CREATE_SCREEN_VIDEO_TRACK,options:[Qt({},t),e]});t.encoderConfig?typeof t.encoderConfig=="string"||t.encoderConfig.width&&t.encoderConfig.height||(t.encoderConfig.width={max:1920},t.encoderConfig.height={max:1080}):t.encoderConfig="1080p_2";const o=function(h){const p={};h.screenSourceType&&(p.mediaSource=h.screenSourceType),h.extensionId&&xr()&&(p.extensionId=h.extensionId);const{displaySurface:g,selfBrowserSurface:m,surfaceSwitching:f,systemAudio:T,preferCurrentTab:R}=h;(Ac(107)||bE(107)||wE(93))&&(g&&(Ae(g,"displaySurface",["browser","window","monitor"]),p.displaySurface=g),m?(Ae(m,"selfBrowserSurface",["exclude","include"]),p.selfBrowserSurface=m):p.selfBrowserSurface="include",f&&(Ae(f,"surfaceSwitching",["exclude","include"]),p.surfaceSwitching=f)),(Ac(105)||bE(105)||wE(91))&&T&&(Ae(T,"systemAudio",["exclude","include"]),p.systemAudio=T),(Ac(94)||bE(94)||wE(80))&&R&&(p.preferCurrentTab=!0),h.electronScreenSourceId&&(p.sourceId=h.electronScreenSourceId);const A=h.encoderConfig?tm(h.encoderConfig):null;return p.mandatory={chromeMediaSource:"desktop",maxWidth:A?A.width:void 0,maxHeight:A?A.height:void 0},A&&(A.frameRate&&(typeof A.frameRate=="number"?(p.mandatory.maxFrameRate=A.frameRate,p.mandatory.minFrameRate=A.frameRate):(p.mandatory.maxFrameRate=A.frameRate.max||A.frameRate.ideal||A.frameRate.exact||void 0,p.mandatory.minFrameRate=A.frameRate.min||A.frameRate.ideal||A.frameRate.exact||void 0),p.frameRate=A.frameRate),A.width&&(p.width=A.width),A.height&&(p.height=A.height)),p}(t);let s=null,a=null;const c=Ct();if(!c.supportShareAudio&&e==="enable"){const h=new k(v.NOT_SUPPORTED,"your browser or platform is not support share-screen with audio");return r.onError(h),h.throw(_)}_.info("start create screen video track with config",t,"withAudio",e,"trackId",n);const d=c.supportShareAudio&&e!=="disable";try{const h=yield tn({screen:o,screenAudio:d?i||!0:void 0},n);s=h.getVideoTracks()[0]||null,a=h.getAudioTracks()[0]||null}catch(h){throw r.onError(h),h}if(!s){const h=new k(v.UNEXPECTED_ERROR,"can not find track in media stream");return r.onError(h),h.throw(_)}if(!a&&e==="enable"){s&&s.stop();const h=new k(v.SHARE_AUDIO_NOT_ALLOWED);return r.onError(h),h.throw(_)}t.optimizationMode||(t.optimizationMode="detail"),t.optimizationMode&&(hm(n,s,t,t.encoderConfig&&tm(t.encoderConfig)||void 0),t.encoderConfig&&typeof t.encoderConfig!="string"&&(t.encoderConfig.bitrateMin=t.encoderConfig.bitrateMax));const l=new Yt(s,t.encoderConfig?tm(t.encoderConfig):{},t.scalabiltyMode?fu(t.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},t.optimizationMode,n,[Vt.SCREEN_TRACK]);if(!a)return r.onSuccess(l.getTrackId()),_.info("create screen video track success","video:",l.getTrackId()),l;const u=new ae(a,void 0,Gt(8,"track-scr-a-"),!1);return r.onSuccess([l.getTrackId(),u.getTrackId()]),_.info("create screen video track success","video:",l.getTrackId(),"audio:",u.getTrackId()),[l,u]})},createMicrophoneAndCameraTracks:function(){return C(this,arguments,function*(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=y("CAMERA_CAPTURE_CONFIG"),n=Gt(8,"track-mic-"),r=Gt(8,"track-cam-"),o=Z.reportApiInvoke(null,{id:"".concat(n,"-").concat(r),tag:oe.TRACER,name:_e.CREATE_MIC_AND_CAM_TRACKS,options:[t,e,i]});i&&(e.encoderConfig=i);const s=Ru(e),a=aA(t);let c=null,d=null;_.info("start create camera video track(".concat(r,") and microphone audio track(").concat(n,") with config, audio: ").concat(JSON.stringify(t),", video: ").concat(JSON.stringify(e)));try{const h=yield tn({audio:a,video:s},"".concat(n,"-").concat(r));c=h.getAudioTracks()[0],d=h.getVideoTracks()[0]}catch(h){throw o.onError(h),h}if(!c||!d){const h=new k(v.UNEXPECTED_ERROR,"can not find tracks in media stream");return o.onError(h),h.throw(_)}if(e.optimizationMode&&hm(r,d,e,Nn(e.encoderConfig)),y("USE_STANDARD_BITRATE_DEFAULT")){const h=Nn(e.encoderConfig);e.encoderConfig=h,delete h.bitrateMax,delete h.bitrateMin}const l=new xc(c,t,a,n),u=new um(d,e,s,e.scalabiltyMode?fu(e.scalabiltyMode):{numSpatialLayers:1,numTemporalLayers:1},e.optimizationMode,r);return o.onSuccess([l.getTrackId(),u.getTrackId()]),_.info("create camera video track(".concat(r,") and microphone audio track(").concat(n,") success")),[l,u]})},createMicrophoneAudioTrack:function(){return C(this,arguments,function*(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Gt(8,"track-mic-"),i=Z.reportApiInvoke(null,{id:e,tag:oe.TRACER,name:_e.CREATE_MIC_AUDIO_TRACK,options:[t]}),n=aA(t);let r=null;_.info("start create microphone audio track with config",JSON.stringify(t),"trackId",e);try{r=(yield tn({audio:n},e)).getAudioTracks()[0]||null}catch(s){throw i.onError(s),s}if(!r){const s=new k(v.UNEXPECTED_ERROR,"can not find track in media stream");return i.onError(s),s.throw(_)}const o=new xc(r,t,n,e);return i.onSuccess(o.getTrackId()),_.info("create microphone audio track success, trackId:",e),o})},createCustomAudioTrack:function(t){const e=Gt(8,"track-cus-"),i=Z.reportApiInvoke(null,{id:e,tag:oe.TRACER,name:_e.CREATE_CUSTOM_AUDIO_TRACK,options:[t]}),n=new ae(t.mediaStreamTrack,t.encoderConfig?gu(t.encoderConfig):{},e,!1);return _.info("create custom audio track success with config",t,"trackId",n.getTrackId()),i.onSuccess(n.getTrackId()),n},createBufferSourceAudioTrack:function(t){return C(this,null,function*(){var e;const{cacheOnlineFile:i,encoderConfig:n}=t;let{source:r}=t;const o={source:r instanceof AudioBuffer?"AudioBuffer":r instanceof File?(e=File.name)!==null&&e!==void 0?e:"File":r,cacheOnlineFile:i,encoderConfig:n},s=Gt(8,"track-buf-"),a=Z.reportApiInvoke(null,{id:s,tag:oe.TRACER,name:_e.CREATE_BUFFER_AUDIO_TRACK,options:[o]});if(y("DISABLE_WEBAUDIO"))throw new k(v.NOT_SUPPORTED,"can not create BufferSourceAudioTrack when WebAudio disabled");_.info("start create buffer source audio track with config",JSON.stringify(o),"trackId",s);const c=r;if(!(r instanceof AudioBuffer))try{r=yield function(u,h){return C(this,null,function*(){let p=null;if(typeof u=="string"){const m=qA.get(u);if(m)return _.debug("use cached audio resource: ",u),m;try{p=(yield Jn(()=>Ti.get(u,{responseType:"arraybuffer"}),void 0,void 0,{maxRetryCount:3})).data}catch(f){throw new k(v.FETCH_AUDIO_FILE_FAILED,f.toString())}}else p=yield new K((f,T)=>{const R=new FileReader;R.onload=A=>{A.target?f(A.target.result):T(new k(v.READ_LOCAL_AUDIO_FILE_ERROR))},R.onerror=()=>{T(new k(v.READ_LOCAL_AUDIO_FILE_ERROR))},R.readAsArrayBuffer(u)});const g=yield function(m){const f=ma();return new K((T,R)=>{f.decodeAudioData(m,A=>{T(A)},A=>{R(new k(v.DECODE_AUDIO_FILE_FAILED,A.toString()))})})}(p);return typeof u=="string"&&h&&qA.set(u,g),g})}(r,i)}catch(u){return a.onError(u),u.throw(_)}const d=new f3(r),l=new m3(c,d,n?gu(n):{},s);return _.info("create buffer source audio track success, trackId:",s),a.onSuccess(l.getTrackId()),l})},setAppType:function(t){if(_.debug("setAppType: ".concat(t)),!(Number.isInteger(t)&&t>=0))throw _.debug("Invalid appType"),new P(v.INVALID_PARAMS,"invalid app type",t);kt("APP_TYPE",Math.floor(t))},setLogLevel:function(t){_.setLogLevel(t)},enableLogUpload:function(){y("USE_NEW_LOG")?kt("UPLOAD_LOG",!0):_.enableLogUpload()},disableLogUpload:function(){y("USE_NEW_LOG")?kt("UPLOAD_LOG",!1):_.disableLogUpload()},createChannelMediaRelayConfiguration:function(){return new qw},checkAudioTrackIsActive:function(e){return C(this,arguments,function*(t){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const n=Z.reportApiInvoke(null,{tag:oe.TRACER,name:_e.CHECK_AUDIO_TRACK_IS_ACTIVE,options:[i]});if(!(t instanceof ae||t instanceof Sa)){const d=new P(v.INVALID_TRACK,"the parameter is not a audio track");return n.onError(d),d.throw()}i&&i<1e3&&(i=1e3);const r=t instanceof ae?t.getTrackLabel():"remote_track",o=t.getVolumeLevel();let s=o,a=o;const c=Date.now();return new K(d=>{const l=setInterval(()=>{const u=t.getVolumeLevel();s=u>s?u:s,a=u<a?u:a;const h=s-a>1e-4,p=Date.now()-c;if(h||p>i){clearInterval(l);const g=h,m={duration:p,deviceLabel:r,maxVolumeLevel:s,result:g};_.info("[track-".concat(t.getTrackId(),"] check audio track active completed. ").concat(JSON.stringify(m))),n.onSuccess(m),d(g)}},200)})})},checkVideoTrackIsActive:function(e){return C(this,arguments,function*(t){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:5e3;const n=Z.reportApiInvoke(null,{tag:oe.TRACER,name:_e.CHECK_VIDEO_TRACK_IS_ACTIVE,options:[i]});if(!(t instanceof Yt||t instanceof ga)){const h=new P(v.INVALID_TRACK,"the parameter is not a video track");return n.onError(h),h.throw()}i&&i<1e3&&(i=1e3);const r=t instanceof Yt?t.getTrackLabel():"remote_track",o=t.getMediaStreamTrack(!0),s=document.createElement("video");s.style.width="1px",s.style.height="1px",s.setAttribute("muted",""),s.muted=!0,s.setAttribute("playsinline",""),s.controls=!1,(je()||su())&&(s.style.opacity="0.01",s.style.position="fixed",s.style.left="0",s.style.top="0",document.body.appendChild(s)),s.srcObject=new MediaStream([o]),s.play();const a=document.createElement("canvas");a.width=160,a.height=120;let c=0,d=0;try{const h=Date.now();c=yield function(p,g,m,f){let T,R=0,A=null;return new K((N,O)=>{function w(){R>f&&T&&(T(),N(R));const L=m.getContext("2d");if(!L){const H=new P(v.UNEXPECTED_ERROR,"can not get canvas 2d context.");return _.error(H.toString()),void O(H)}L.drawImage(p,0,0,160,120);const M=L.getImageData(0,0,m.width,m.height),j=Math.floor(M.data.length/3);if(A){for(let H=0;H<j;H+=3)if(M.data[H]!==A[H])return R+=1,void(A=M.data);A=M.data}else A=M.data}setTimeout(()=>{T&&(T(),N(R))},g),T=om(()=>{w()},30)})}(s,i,a,4),d=Date.now()-h}catch(h){throw n.onError(h),h}xW===It.SAFARI&&(s.pause(),s.remove()),s.srcObject=null;const l=c>4,u={duration:d,changedPicNum:c,deviceLabel:r,result:l};return _.info("[track-".concat(t.getTrackId(),"] check video track active completed. ").concat(JSON.stringify(u))),n.onSuccess(u),l})},setArea:Vm,audioElementPlayCenter:Ri,resumeAudioContext:function(){Ri.autoResumeAfterInterruption(!0)},processExternalMediaAEC:function(t){$W.processExternalMediaAEC(t)},registerExtensions:function(t){const e=y("PLUGIN_INFO")||[];t.forEach(i=>{"name"in i&&!G(e).call(e,i.name)&&e.push(i.name);const n=i;n.__registered__=!0,n.logger.hookLog=_.extLog,n.reporter.hookApiInvoke=Z.extApiInvoke,n.parameters&&Object.keys(n.parameters).forEach(r=>{n.parameters[r]=y(r)})}),zN("PLUGIN_INFO",e)},ChannelMediaRelayError:va,ChannelMediaRelayEvent:Wr,ChannelMediaRelayState:Di,RemoteStreamFallbackType:d3,RemoteStreamType:c3,ConnectionDisconnectedReason:bt,AudienceLatencyLevelType:FG,AREAS:At,preload:function(t,e,i,n){return C(this,null,function*(){return g0(t,e,i,n)})}});return Object.defineProperties(Se,{onAudioAutoplayFailed:{get:()=>nn.onAudioAutoplayFailed,set:t=>{nn.onAudioAutoplayFailed=t}},onAutoplayFailed:{get:()=>nn.onAutoplayFailed,set:t=>{nn.onAutoplayFailed=t}},_onSecurityPolicyViolation:{value:void 0,writable:!0},_cspEventHandlerPointer:{value:void 0,writable:!0},onSecurityPolicyViolation:{get:()=>Se._onSecurityPolicyViolation,set(t){Se._onSecurityPolicyViolation=t,wO(t)}},__CLIENT_LIST__:{get:()=>y("SHOW_GLOBAL_CLIENT_LIST")?os:[]}}),en.on(es.CAMERA_DEVICE_CHANGED,t=>{_.info("camera device changed",JSON.stringify(t)),Se.onCameraChanged&&Se.onCameraChanged(t),Se.safeEmit(Tr.CAMERA_CHANGED,t)}),en.on(es.RECORDING_DEVICE_CHANGED,t=>{_.info("microphone device changed",JSON.stringify(t)),Se.onMicrophoneChanged&&Se.onMicrophoneChanged(t),Se.safeEmit(Tr.MICROPHONE_CHANGED,t)}),en.on(es.PLAYOUT_DEVICE_CHANGED,t=>{_.debug("playout device changed",JSON.stringify(t)),Se.onPlaybackDeviceChanged&&Se.onPlaybackDeviceChanged(t),Se.safeEmit(Tr.PLAYBACK_DEVICE_CHANGED,t)}),Ri.onAutoplayFailed=()=>{_.info("detect audio element autoplay failed"),nn.onAudioAutoplayFailed&&nn.onAudioAutoplayFailed()},Mt.on("autoplay-failed",()=>{_.info("detect webaudio autoplay failed"),nn.onAudioAutoplayFailed&&nn.onAudioAutoplayFailed(),Se.safeEmit(Tr.AUTOPLAY_FAILED)}),Mt.on(Ve.STATE_CHANGE,(t,e)=>{_.info("audio context state changed: ".concat(e," => ").concat(t)),Se.onAudioContextStateChanged&&Se.onAudioContextStateChanged(t,e),Se.safeEmit(Tr.AUDIO_CONTEXT_STATE_CHANGED,t,e)}),Ee.on(ra.NETWORK_STATE_CHANGE,(t,e)=>{_.info("[network-indicator] network state changed, ".concat(e," => ").concat(t))}),window&&(window.__ARTC__=Se),Se})}(Ih)),Ih.exports}var sH=oH();const aH=z4(sH),cH={id:"app"},dH={key:0,class:"loading"},lH={key:1,class:"no-videos"},uH={key:2,class:"video-grid"},hH={class:"video-header"},pH=["id"],_H={class:"video-actions"},EH=["onClick"],mH={key:3,class:"fullscreen"},fH=[".srcObject"],gH=X4({__name:"demo",props:["result","userId","roomId"],setup(ai){const ce=ai,Ai=Rs("a3f0f0c78307434fa1c697c3429fbdcf"),Qe=Rs(ce.roomId),Pt=Rs(ce.result.token),Lt=Rs(!1),bi=Rs(!1),Ze=Rs([]),mi=Rs(null),Wi=J4({bitrate:0,packetLoss:0,resolution:"0x0"});let Gn=null;const de=()=>C(this,null,function*(){if(!Ai.value||!Qe.value){alert("请输入App ID和频道名称");return}try{Lt.value=!0,Gn=aH.createClient({mode:"live",codec:"h264"}),Gn.on("user-published",$e),Gn.on("user-unpublished",Lo),Gn.on("user-left",ie),yield Gn.join(Ai.value,Qe.value.toString(),Pt.value||null,+ce.userId,"live","audience"),bi.value=!0,setInterval(()=>{Ze.value.length>0&&(Wi.bitrate=Math.floor(Math.random()*5e3),Wi.packetLoss=Math.random().toFixed(2),Wi.resolution=`${Math.floor(Math.random()*1920)}x${Math.floor(Math.random()*1080)}`)},1e3)}catch(ci){console.error("加入频道失败:",ci),alert(`加入频道失败: ${ci.message}`)}finally{Lt.value=!1}}),$e=(ci,be)=>C(this,null,function*(){be==="video"&&(yield Gn.subscribe(ci,be),Ze.value=[...Ze.value,ci],setTimeout(()=>{const fi=document.getElementById(`player-${+ce.userId}`);fi&&ci.videoTrack.play(fi)},100))}),Lo=(ci,be)=>{be==="video"&&(ci.videoTrack&&ci.videoTrack.stop(),Ze.value=Ze.value.filter(fi=>fi.uid!==+ce.userId))},ie=ci=>{Ze.value=Ze.value.filter(be=>be.uid!==+ce.userId)},Ah=()=>C(this,null,function*(){Gn&&(Ze.value.forEach(ci=>{ci.videoTrack&&ci.videoTrack.stop()}),yield Gn.leave(),bi.value=!1,Ze.value=[],Wi.bitrate=0,Wi.packetLoss=0,Wi.resolution="0x0")}),yd=ci=>{const be=document.getElementById(`player-${+ce.userId}`);if(!be)return;const fi=be.querySelector("video");if(!fi)return;const ar=document.createElement("canvas");ar.width=fi.videoWidth,ar.height=fi.videoHeight,ar.getContext("2d").drawImage(fi,0,0,ar.width,ar.height);const Ha=document.createElement("a");Ha.download=`视频巡查截图_${+ce.userId}_${new Date().toISOString().slice(0,19).replace(/:/g,"-")}.png`,Ha.href=ar.toDataURL("image/png"),Ha.click(),alert(`已保存用户 ${+ce.userId} 的视频截图`)};return Q4(()=>{de()}),Z4(()=>{Gn&&bi.value&&Ah()}),(ci,be)=>(vs(),Cs("div",cH,[Lt.value?(vs(),Cs("div",dH,be[1]||(be[1]=[Gi("div",{class:"spinner"},null,-1)]))):Ze.value.length===0?(vs(),Cs("div",lH,be[2]||(be[2]=[Gi("i",{class:"fas fa-video-slash"},null,-1),Gi("h3",null,"没有可用的视频流",-1),Gi("p",null,"请加入频道以查看视频,或等待其他用户发布视频流",-1)]))):(vs(),Cs("div",uH,[(vs(!0),Cs($4,null,tH(Ze.value,fi=>(vs(),Cs("div",{key:+ce.userId,class:"video-item"},[Gi("div",hH,[Gi("div",null,"用户 ID: "+eH(+ce.userId),1),be[3]||(be[3]=Gi("div",{class:"status-indicator"},[Gi("span",{class:"indicator connected"}),JN(" 在线 ")],-1))]),Gi("div",{class:"video-player",id:"player-"+ +ce.userId},null,8,pH),Gi("div",_H,[Gi("button",{class:"btn btn-secondary",onClick:ar=>yd()},be[4]||(be[4]=[Gi("i",{class:"fas fa-camera"},null,-1),JN(" 截图 ")]),8,EH)])]))),128))])),mi.value?(vs(),Cs("div",mH,[Gi("button",{class:"close-fullscreen",onClick:be[0]||(be[0]=fi=>mi.value=null)},be[5]||(be[5]=[Gi("i",{class:"fas fa-times"},null,-1)])),Gi("video",{".srcObject":mi.value.videoTrack.getMediaStream(),autoplay:"",playsinline:""},null,40,fH)])):iH("",!0)]))}}),bH=nH(gH,[["__scopeId","data-v-b32a5d21"]]);export{bH as default};